// rd-onboard.jsx — splash → welcome → how-it-works steps → verify (passport, selfie, bank) → done

function RdSplash({ live = true, onNext }) {
  React.useEffect(() => {
    if (!live) return;
    const t = setTimeout(() => onNext && onNext(), 2600);
    return () => clearTimeout(t);
  }, []);
  return (
    <RdScreen label="Splash" onClick={onNext}>
      <div onClick={onNext} style={{ height: '100%', display: 'flex', flexDirection: 'column', cursor: 'pointer', position: 'relative' }}>
        {/* soft teal sun behind the shaka */}
        <div style={{ position: 'absolute', top: '16%', left: '50%', width: 380, height: 380, marginLeft: -190, borderRadius: '50%', background: 'radial-gradient(circle, rgba(0,212,170,0.20) 0%, rgba(0,212,170,0) 66%)', animation: live ? 'rd-burst 700ms ease both' : 'none' }}></div>

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 26, position: 'relative', zIndex: 2 }}>
          <div style={{ animation: live ? 'rd-pop 360ms ease both' : 'none' }}>
            <div style={{ animation: live ? 'rd-rock-soft 2.2s ease-in-out 700ms infinite' : 'none' }}>
              <RdLogo size={128} />
            </div>
          </div>
          <img src="assets/gringo-wordmark-dark.svg" alt="GrinGo Pay" style={{ width: 232, height: 'auto', animation: live ? 'rd-rise 260ms 200ms ease both' : 'none' }} />
          <div className="rd-h1" style={{ fontSize: 21, color: RD.ink2, marginTop: -6, animation: live ? 'rd-rise 260ms 420ms ease both' : 'none' }}>Pay like a local, anywhere</div>
        </div>

        {/* markets roll past while the app warms up */}
        <div style={{ paddingBottom: 62, position: 'relative', zIndex: 2, animation: live ? 'rd-fade 500ms 650ms ease both' : 'none' }}>
          <div className="rd-label" style={{ textAlign: 'center', color: RD.ink3, marginBottom: 14 }}>Brazil now · Latin America next</div>
          <RdChipMarquee bleed={0} duration={20}>
            <RdMarketChips />
          </RdChipMarquee>
        </div>
      </div>
    </RdScreen>
  );
}

function RdWelcome({ grain = true, live = true, onStart, onSignIn }) {
  return (
    <RdScreen label="Welcome" grain={grain}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '76px 26px 42px' }}>
        {/* full wordmark at the top */}
        <img src="assets/gringo-wordmark-dark.svg" alt="GrinGo Pay" style={{ height: 34, width: 'auto', alignSelf: 'flex-start' }} />

        <div className="rd-display" style={{ fontSize: 39, color: RD.ink, marginTop: 36, whiteSpace: 'nowrap' }}>Pay like a local.</div>
        <div className="rd-body" style={{ fontSize: 18.5, color: RD.ink2, marginTop: 16, maxWidth: 344 }}>
          Scan-to-pay on Brazil's PIX today, more of Latin America next. No local bank account, no CPF, no card fees hiding in the exchange rate.
        </div>

        {/* markets — auto-scrolling, loops so the coming-soon countries all get seen */}
        <RdChipMarquee bleed={26} duration={20} style={{ marginTop: 28 }}>
          <RdMarketChips />
        </RdChipMarquee>

        <div style={{ flex: 1 }}></div>
        <RdButton kind="primary" onClick={onStart} style={{ minHeight: 70 }}>Get started</RdButton>
        <RdButton kind="ghost" onClick={onSignIn} style={{ marginTop: 6 }}>I already have an account</RdButton>
      </div>
    </RdScreen>
  );
}

// ── mini QR for the how-it-works scan step ──
function RdIntroQr({ s = 100 }) {
  const cells = [];
  for (let y = 0; y < 11; y++) for (let x = 0; x < 11; x++) {
    const finder = (x < 4 && y < 4) || (x > 6 && y < 4) || (x < 4 && y > 6);
    if (!finder && ((x * 13 + y * 29 + x * y * 7) % 5) < 2) cells.push([x, y]);
  }
  return (
    <svg width={s} height={s} viewBox="0 0 11 11" style={{ display: 'block' }}>
      {cells.map(([x, y], i) => <rect key={i} x={x + 0.08} y={y + 0.08} width="0.84" height="0.84" rx="0.18" fill="var(--ink)" />)}
      {[[0, 0], [7, 0], [0, 7]].map(([x, y], i) => (
        <g key={'f' + i}>
          <rect x={x + 0.35} y={y + 0.35} width="3.3" height="3.3" rx="0.5" fill="none" stroke="var(--ink)" strokeWidth="0.55" />
          <rect x={x + 1.3} y={y + 1.3} width="1.4" height="1.4" rx="0.25" fill="var(--ink)" />
        </g>
      ))}
    </svg>
  );
}

// ── how it works — 3 steps: sign-up, scan, slide-to-pay at the real rate ──
function RdIntro({ grain = true, live = true, staticStep, onDone, onBack }) {
  const [step, setStep] = React.useState(staticStep ?? 0);
  const [paid, setPaid] = React.useState(false);

  const signupRows = [
    { Icon: IcCamera, t: 'Scan your passport' },
    { Icon: IcUser, t: 'Quick selfie' },
    { Icon: IcBank, t: 'Link your home bank' },
  ];

  const visuals = [
    // 0 — sign-up
    <div style={{ padding: '2px 2px' }}>
      {signupRows.map((r, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '12px 0', borderBottom: i < 2 ? `1.5px solid ${RD.hairline}` : 'none' }}>
          <div style={{ width: 40, height: 40, borderRadius: 'var(--r-chip)', background: RD.paper, border: `1.5px solid ${RD.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: RD.ink, flexShrink: 0 }}>
            <r.Icon size={19} />
          </div>
          <span className="rd-h3" style={{ fontSize: 15.5, color: RD.ink, flex: 1 }}>{r.t}</span>
          <IcCheck size={18} color={RD.tealDeep} />
        </div>
      ))}
    </div>,
    // 1 — scan
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, padding: '14px 0 12px' }}>
      <div style={{ position: 'relative', padding: 16 }}>
        {[
          { top: 0, left: 0, borderWidth: '3px 0 0 3px', borderRadius: '6px 0 0 0' },
          { top: 0, right: 0, borderWidth: '3px 3px 0 0', borderRadius: '0 6px 0 0' },
          { bottom: 0, left: 0, borderWidth: '0 0 3px 3px', borderRadius: '0 0 0 6px' },
          { bottom: 0, right: 0, borderWidth: '0 3px 3px 0', borderRadius: '0 0 6px 0' },
        ].map((c, i) => (
          <div key={i} style={{ position: 'absolute', width: 24, height: 24, borderStyle: 'solid', borderColor: RD.tealDeep, ...c }}></div>
        ))}
        <RdIntroQr s={104} />
      </div>
      <RdRailSlot market="br" h={14} />
    </div>,
    // 2 — slide to pay, live demo
    <div style={{ padding: '4px 2px 2px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
        <span className="rd-h3" style={{ fontSize: 15, color: RD.ink }}>Quiosque do Mar</span>
        <span className="rd-display rd-num" style={{ fontSize: 24, color: RD.ink }}>R$ 12,00</span>
      </div>
      <div className="rd-num" style={{ fontFamily: RD.ui, fontSize: 13.5, fontWeight: 600, color: RD.ink2, marginTop: 7 }}>£1.70 from your balance</div>
      <div className="rd-num" style={{ fontFamily: RD.ui, fontSize: 13.5, fontWeight: 600, color: RD.ink2, marginTop: 4, whiteSpace: 'nowrap' }}>
        Rate locked: £1 = R$7.05 · GrinGo rate · <span style={{ color: RD.tealDeep }}>fee £0.00</span>
      </div>
      <div style={{ marginTop: 14 }}>
        {paid ? (
          <div style={{ height: 72, borderRadius: 'var(--r-btn)', background: RD.teal, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, fontFamily: RD.disp, fontWeight: 800, fontSize: 23, color: RD.tealInk, animation: 'rd-stamp 320ms ease both' }}>
            <IcCheck size={24} color={RD.tealInk} />Pago
          </div>
        ) : (
          <RdSlidePay label="Slide to pay" onComplete={() => setPaid(true)} />
        )}
      </div>
      <div className="rd-body" style={{ fontSize: 12.5, color: RD.ink3, marginTop: 10, textAlign: 'center' }}>
        {paid ? 'That\u2019s it. Rate locked, confirmed in about a second' : 'Go on, try it'}
      </div>
    </div>,
  ];

  const steps = [
    { title: 'Sign up in minutes.', body: 'Passport and a selfie. That\u2019s the whole check. No CPF, no Brazilian bank account, no paperwork.' },
    { title: 'Scan any PIX code.', body: 'Menus, tills, street vendors, machines. If it takes PIX, and in Brazil everything does, it just works.' },
    { title: 'Slide to pay the fair rate.', body: 'You always get the fair GrinGo rate, converted the moment you slide to pay. Nothing converts before that.' },
  ];

  return (
    <RdScreen label="How it works" grain={grain}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '66px 24px 42px' }}>
        <RdTopBar title="How it works" onBack={step === 0 ? onBack : () => setStep(step - 1)}
          right={<span className="rd-num" style={{ fontFamily: RD.ui, fontWeight: 600, fontSize: 13.5, color: RD.ink3 }}>{step + 1} of 3</span>} />
        <div style={{ display: 'flex', gap: 5, marginTop: 20 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{ flex: 1, height: 5, borderRadius: 3, background: i <= step ? RD.teal : 'rgba(10,43,34,0.12)', transition: 'background 150ms' }}></div>
          ))}
        </div>

        <div key={step} style={{ animation: live ? 'rd-rise 220ms ease both' : 'none' }}>
          <div style={{ marginTop: 30, background: RD.paperHi, border: `1.5px solid ${RD.hairline}`, borderRadius: 'var(--r-card)', padding: '14px 18px' }}>
            {visuals[step]}
          </div>
          <div className="rd-display" style={{ fontSize: 35, color: RD.ink, marginTop: 26, letterSpacing: '-0.02em' }}>{steps[step].title}</div>
          <div className="rd-body" style={{ fontSize: 16.5, color: RD.ink2, marginTop: 12, maxWidth: 336 }}>{steps[step].body}</div>
        </div>

        <div style={{ flex: 1 }}></div>
        <RdButton kind="primary" onClick={() => (step < 2 ? setStep(step + 1) : onDone())} style={{ minHeight: 68 }}>
          {step < 2 ? 'Next' : 'Create my account'}
        </RdButton>
        <RdButton kind="ghost" onClick={onDone} style={{ marginTop: 6 }}>Skip</RdButton>
      </div>
    </RdScreen>
  );
}

// ── verify: 3 steps, each simulated with one tap ──
function RdKyc({ grain = true, live = true, staticStep, onDone, onBack }) {
  const [step, setStep] = React.useState(staticStep ?? 0); // 0 passport, 1 selfie, 2 bank, 3 done
  const [busy, setBusy] = React.useState(false);
  const [bank, setBank] = React.useState('Monzo');
  const timer = React.useRef(null);
  React.useEffect(() => () => clearTimeout(timer.current), []);

  const advance = () => {
    if (!live) return;
    setBusy(true);
    timer.current = setTimeout(() => { setBusy(false); setStep(s => s + 1); }, 900);
  };

  const steps = [
    { Icon: IcCamera, title: 'Scan your passport', body: 'That\u2019s the whole ID check. No CPF, no local paperwork. Takes about 20 seconds.', cta: busy ? 'Reading chip…' : 'Scan passport' },
    { Icon: IcUser, title: 'Quick selfie', body: 'Just to match you to your passport. Never shown to vendors.', cta: busy ? 'Checking…' : 'Take selfie' },
    { Icon: IcBank, title: 'Add a way to load money', body: 'Link your bank with Open Banking. Load in seconds, withdraw back whenever you like.', cta: busy ? 'Connecting…' : 'Link ' + bank },
  ];

  if (step >= 3) {
    return (
      <RdScreen label="Verified" grain={grain}>
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '110px 26px 42px' }}>
          <div style={{ width: 74, height: 74, borderRadius: '50%', background: RD.teal, display: 'flex', alignItems: 'center', justifyContent: 'center', animation: live ? 'rd-pop 300ms ease both' : 'none' }}>
            <IcCheck size={40} color={RD.tealInk} />
          </div>
          <div className="rd-display" style={{ fontSize: 44, color: RD.ink, marginTop: 26 }}>You're set.</div>
          <div className="rd-body" style={{ fontSize: 16.5, color: RD.ink2, marginTop: 12, maxWidth: 310 }}>
            Passport verified and {bank} linked. We're switching on PIX for you now. We'll notify you the moment it's approved.
          </div>
          <div style={{ flex: 1 }}></div>
          <RdButton kind="primary" onClick={() => onDone('load')} style={{ minHeight: 68 }} icon={<IcPlus size={20} color={RD.tealInk} />}>Top up your balance</RdButton>
          <RdButton kind="ghost" onClick={() => onDone('home')} style={{ marginTop: 6 }}>Skip for now</RdButton>
        </div>
      </RdScreen>
    );
  }

  const s = steps[step];
  return (
    <RdScreen label="Verify" grain={grain}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '66px 24px 42px' }}>
        <RdTopBar title="Set up" onBack={step === 0 ? onBack : () => setStep(step - 1)}
          right={<span className="rd-num" style={{ fontFamily: RD.ui, fontWeight: 600, fontSize: 13.5, color: RD.ink3 }}>{step + 1} of 3</span>} />
        {/* progress — teal fill, hard-left shaka cut */}
        <div style={{ display: 'flex', gap: 5, marginTop: 20 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{ flex: 1, height: 5, borderRadius: 3, background: i <= step ? RD.teal : 'rgba(10,43,34,0.12)', transition: 'background 150ms' }}></div>
          ))}
        </div>

        <div style={{ width: 70, height: 70, borderRadius: 'var(--r-card)', background: RD.paperHi, border: `1.5px solid ${RD.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: RD.ink, marginTop: 44 }}>
          <s.Icon size={32} />
        </div>
        <div className="rd-display" style={{ fontSize: 38, color: RD.ink, marginTop: 22, letterSpacing: '-0.02em' }}>{s.title}</div>
        <div className="rd-body" style={{ fontSize: 16, color: RD.ink2, marginTop: 12, maxWidth: 320 }}>{s.body}</div>

        {step === 2 && (
          <div style={{ marginTop: 22 }}>
            {/* active method: bank via Open Banking */}
            <div style={{ padding: '14px 16px', background: RD.paperHi, border: `1.5px solid ${RD.ink}`, borderRadius: 'var(--r-card)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <IcBank size={20} color={RD.ink} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="rd-h3" style={{ fontSize: 15, color: RD.ink }}>UK bank transfer</div>
                  <div className="rd-body" style={{ fontSize: 12.5, color: RD.ink3 }}>Open Banking · instant · no card fees</div>
                </div>
                <span style={{ display: 'inline-flex', width: 20, height: 20, borderRadius: '50%', background: RD.teal, alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <IcCheck size={12} color={RD.tealInk} />
                </span>
              </div>
              <div style={{ display: 'flex', gap: 7, marginTop: 12, flexWrap: 'wrap' }}>
                {['Monzo', 'Revolut', 'Barclays', 'Chase'].map(b => (
                  <button key={b} onClick={() => setBank(b)} style={{
                    padding: '8px 13px', borderRadius: 'var(--r-chip)', cursor: 'pointer',
                    border: `1.5px solid ${b === bank ? RD.ink : RD.hairline}`,
                    background: b === bank ? RD.ink : RD.paper, color: b === bank ? RD.paper : RD.ink,
                    fontFamily: RD.ui, fontWeight: 600, fontSize: 13.5,
                  }}>{b}</button>
                ))}
              </div>
            </div>
            {/* coming soon methods */}
            {[
              { t: 'Apple Pay', s: 'Top up with a tap', icon: (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={RD.ink3} strokeWidth="2.2" strokeLinecap="round">
                  <path d="M7 9.5a4.5 4.5 0 0 1 0 5" /><path d="M10.5 8a7.5 7.5 0 0 1 0 8" /><path d="M14 6.5a10.5 10.5 0 0 1 0 11" />
                </svg>
              ) },
              { t: 'Debit card', s: 'Instant top-up, small fee applies', icon: (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={RD.ink3} strokeWidth="2.2" strokeLinecap="round">
                  <rect x="3" y="6" width="18" height="13" rx="2" /><path d="M3 10.5h18" />
                </svg>
              ) },
            ].map((mth, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', marginTop: 8, background: RD.paperHi, border: `1.5px solid ${RD.hairline}`, borderRadius: 'var(--r-card)' }}>
                {mth.icon}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="rd-h3" style={{ fontSize: 15, color: RD.ink2 }}>{mth.t}</div>
                  <div className="rd-body" style={{ fontSize: 12.5, color: RD.ink3 }}>{mth.s}</div>
                </div>
                <span className="rd-label" style={{ fontSize: 10, color: RD.sunset, letterSpacing: '0.07em' }}>Coming soon</span>
              </div>
            ))}
          </div>
        )}

        <div style={{ flex: 1 }}></div>
        <RdButton kind="primary" onClick={advance} style={{ minHeight: 68, opacity: busy ? 0.7 : 1 }}
          icon={!busy && <s.Icon size={21} color={RD.tealInk} />}>{s.cta}</RdButton>
        <div className="rd-body" style={{ fontSize: 13, color: RD.ink3, textAlign: 'center', marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <IcShield size={15} color={RD.ink3} />Encrypted · deleted if you close your account
        </div>
      </div>
    </RdScreen>
  );
}

Object.assign(window, { RdSplash, RdWelcome, RdIntro, RdIntroQr, RdKyc });
