// 02 — Funding card in-chat (QR + amount + pending → success)
// Killer moment: agente recibe USDC, confirma onchain en seg

function ScreenFundingCard() {
  const [phase, setPhase] = React.useState('await'); // await → received → confirmed
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const seq = [
      { d: 2200, p: 'received' },
      { d: 1800, p: 'confirmed' },
      { d: 4000, p: 'await' },
    ];
    let i = 0; let cancelled = false;
    const tick = () => {
      if (cancelled) return;
      const cur = seq[i % seq.length];
      const t = setTimeout(() => {
        setPhase(cur.p);
        i++;
        tick();
      }, cur.d);
      return t;
    };
    tick();
    return () => { cancelled = true; };
  }, []);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [phase]);

  return (
    <div className="tg">
      <StatusBar tint="light" />
      <TelegramHeader name="Bia" sub="online · agent" />
      <div className="tg-body" ref={scrollRef}>
        <TgDay>Today</TgDay>

        <TgMsg side="me" time="09:42" check>
          USDC native — voy
        </TgMsg>

        <TgMsg side="them" time="09:42">
          Acá tenés. Mandame al QR o copiá la dirección — Base mainnet.
        </TgMsg>

        {/* the funding card */}
        <div className="gp-card" style={{margin:'8px 4px'}}>
          <div className="gp-card-head">
            <div className="gp-card-brand">
              <span className="mk">grip</span>
              <span className="pay">fund · usdc</span>
            </div>
            <FundStatus phase={phase} />
          </div>
          <div className="gp-card-body" style={{padding:'18px 16px 14px'}}>
            <FundQR phase={phase} />
            <FundFooter phase={phase} />
          </div>
        </div>

        {phase === 'received' && (
          <div style={{animation:'fadeUp .35s'}}>
            <TgMsg side="them" time="09:42">
              Detecté la tx. Esperando 1 conf en Base.
            </TgMsg>
          </div>
        )}
        {phase === 'confirmed' && (
          <div style={{animation:'fadeUp .35s'}}>
            <TgMsg side="them" time="09:43">
              Listo — <span style={{color:'#3FCA8C', fontWeight:600}}>$500.00 USDC</span> en wallet. ¿Qué hacemos primero?
            </TgMsg>
          </div>
        )}

        <div style={{height: 8}}/>
      </div>
      <TgInput placeholder="Message" />
    </div>
  );
}

function FundStatus({ phase }) {
  if (phase === 'await') {
    return (
      <div className="gp-card-tag" style={{color:'var(--ochre)'}}>
        <span className="pulse" style={{background:'var(--ochre)', boxShadow:'0 0 6px var(--ochre)'}}/>
        awaiting
      </div>
    );
  }
  if (phase === 'received') {
    return (
      <div className="gp-card-tag" style={{color:'var(--blue)'}}>
        <span className="pulse" style={{background:'var(--blue)', boxShadow:'0 0 6px var(--blue)'}}/>
        detected
      </div>
    );
  }
  return (
    <div className="gp-card-tag">
      <span className="pulse"/>
      confirmed
    </div>
  );
}

function FundQR({ phase }) {
  const isDone = phase === 'confirmed';
  return (
    <div style={{
      display:'flex', flexDirection:'column', alignItems:'center', gap:14,
      padding:'8px 0',
    }}>
      <div style={{
        width:148, height:148, borderRadius:10,
        background:'#fff',
        padding:10,
        position:'relative',
        boxShadow:'0 8px 24px -8px rgba(0,0,0,0.4)',
        transition:'transform .4s, opacity .4s',
        transform: isDone ? 'scale(0.92)' : 'scale(1)',
        opacity: isDone ? 0.5 : 1,
      }}>
        <QRSvg />
        {isDone && (
          <div style={{
            position:'absolute', inset:0, display:'flex',
            alignItems:'center', justifyContent:'center',
            animation:'successPop .4s',
          }}>
            <div style={{
              width:60, height:60, borderRadius:'50%', background:'#3FCA8C',
              display:'flex', alignItems:'center', justifyContent:'center',
              color:'#080C0A', fontSize:36, fontWeight:600,
              boxShadow:'0 0 24px rgba(63,202,140,0.6)',
            }}>✓</div>
          </div>
        )}
      </div>
      <div style={{
        fontFamily:'var(--mono)', fontSize:10.5, color:'var(--ink-mute)',
        letterSpacing:'0.04em',
        background:'rgba(255,255,255,0.03)',
        padding:'6px 10px', borderRadius:5,
        border:'1px solid var(--line)',
      }}>0xA4F2…91Bc · base</div>
    </div>
  );
}

function QRSvg() {
  // pseudo-random but deterministic QR-like pattern
  const cells = React.useMemo(() => {
    const rng = (s) => { let x = s; return () => { x = (x * 9301 + 49297) % 233280; return x / 233280; }; };
    const r = rng(7);
    const out = [];
    for (let y = 0; y < 21; y++) for (let x = 0; x < 21; x++) {
      out.push(r() > 0.5 ? 1 : 0);
    }
    return out;
  }, []);
  const cell = (x, y) => {
    // finder patterns at 3 corners
    const isFinder = (x, y) =>
      (x < 7 && y < 7) || (x > 13 && y < 7) || (x < 7 && y > 13);
    if (isFinder(x, y)) {
      // black inside, white middle, black outside
      const lx = x < 7 ? x : x > 13 ? x - 14 : x;
      const ly = y < 7 ? y : y > 13 ? y - 14 : y;
      const inFinder =
        (lx === 0 || lx === 6 || ly === 0 || ly === 6) ||
        (lx >= 2 && lx <= 4 && ly >= 2 && ly <= 4);
      return inFinder;
    }
    return cells[y * 21 + x] === 1;
  };
  const rects = [];
  for (let y = 0; y < 21; y++) for (let x = 0; x < 21; x++) {
    if (cell(x, y)) {
      rects.push(<rect key={`${x}-${y}`} x={x*6} y={y*6} width="6" height="6" fill="#000"/>);
    }
  }
  return (
    <svg viewBox="0 0 126 126" width="100%" height="100%">
      {rects}
      {/* grip mark in center */}
      <rect x="48" y="48" width="30" height="30" rx="6" fill="#fff"/>
      <rect x="51" y="51" width="24" height="24" rx="4" fill="#3FCA8C"/>
      <text x="63" y="71" textAnchor="middle"
        fontFamily="Fraunces, serif" fontStyle="italic" fontSize="18"
        fontWeight="600" fill="#080C0A">g</text>
    </svg>
  );
}

function FundFooter({ phase }) {
  return (
    <div style={{
      marginTop:14, paddingTop:14,
      borderTop:'1px solid var(--line)',
      display:'grid', gridTemplateColumns:'1fr 1fr', gap:10,
    }}>
      <Field k="amount" v={
        <span>
          <span style={{color:'var(--green)'}}>500.</span>
          <span style={{color:'var(--ink-mute)'}}>00</span>
          <span style={{fontSize:10, color:'var(--ink-mute)', marginLeft:5, letterSpacing:'0.06em'}}>USDC</span>
        </span>
      }/>
      <Field k="network" v={<span>Base <span style={{color:'var(--ink-mute)'}}>· L2</span></span>}/>
      <Field k="ETA" v={phase === 'confirmed' ? <span style={{color:'var(--green)'}}>done</span> : '~6 sec'}/>
      <Field k="fee" v={<span>0 <span style={{color:'var(--ink-mute)'}}>USDC</span></span>}/>
      {phase === 'confirmed' && (
        <div style={{gridColumn:'span 2', marginTop:6}}>
          <a href="#" style={{
            display:'flex', alignItems:'center', justifyContent:'space-between',
            padding:'9px 12px', border:'1px solid var(--green-line)',
            background:'var(--green-soft)', borderRadius:6,
            fontFamily:'var(--mono)', fontSize:11, color:'var(--green)',
            letterSpacing:'0.04em',
            textDecoration:'none',
          }}>
            <span>0x4f8c…d2a3 → basescan</span>
            <span>↗</span>
          </a>
        </div>
      )}
    </div>
  );
}

function Field({ k, v }) {
  return (
    <div>
      <div style={{
        fontFamily:'var(--mono)', fontSize:9, color:'var(--ink-mute)',
        letterSpacing:'0.18em', textTransform:'uppercase', marginBottom:3,
      }}>{k}</div>
      <div style={{
        fontFamily:'var(--display)', fontWeight:500, fontSize:15,
        color:'var(--ink)', letterSpacing:'-0.005em',
        fontVariantNumeric:'tabular-nums',
      }}>{v}</div>
    </div>
  );
}

window.ScreenFundingCard = ScreenFundingCard;
