function Checkout({ go, onPaid, plan = 'yearly' }) {
  const wide = useWide();
  const [step, setStep] = React.useState('select'); // select | pay | success
  const [coin, setCoin] = React.useState('USDC');
  const [copied, setCopied] = React.useState(false);
  const [countdown, setCountdown] = React.useState(14 * 60); // 14 minutes

  React.useEffect(() => {
    if (step !== 'pay') return;
    const id = setInterval(() => setCountdown(c => c > 0 ? c - 1 : 0), 1000);
    return () => clearInterval(id);
  }, [step]);

  const price = plan === 'yearly' ? 800 : 99;
  const total = price + 1.20;
  const coins = [
    { sym: 'BTC', name: 'Bitcoin', amt: plan === 'yearly' ? '0.01124' : '0.00139', net: 'Bitcoin' },
    { sym: 'ETH', name: 'Ethereum', amt: plan === 'yearly' ? '0.2178' : '0.02697', net: 'Ethereum' },
    { sym: 'USDC', name: 'USD Coin', amt: total.toFixed(2), net: 'Any supported chain' },
    { sym: 'SOL', name: 'Solana', amt: plan === 'yearly' ? '4.235' : '0.524', net: 'Solana' },
    { sym: 'USDT', name: 'Tether', amt: total.toFixed(2), net: 'Ethereum · Tron · Solana' },
  ];
  const sel = coins.find(c => c.sym === coin);
  const addr = 'bc1q8nx5m7t3v9q2p4r6s8u0w1y3z5a7c9e1g3i5k7m9o1q3s5u7w9y1a3c5e7';

  const copy = () => { navigator.clipboard?.writeText(addr); setCopied(true); setTimeout(() => setCopied(false), 1500); };
  const mm = Math.floor(countdown / 60).toString().padStart(2,'0');
  const ss = (countdown % 60).toString().padStart(2,'0');

  if (step === 'success') {
    return (
      <div style={{ background: TH.bg, color: TH.ink, fontFamily: TH.serif, minHeight: 'calc(100vh - 57px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
        <div style={{ maxWidth: 520, textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, margin: '0 auto 24px', border: `2px solid ${TH.accent}`, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={TH.accent} strokeWidth="2.5" strokeLinecap="round"><path d="M5 12l5 5L20 7"/></svg>
          </div>
          <div style={{ fontFamily: TH.mono, fontSize: 11, color: TH.accent, letterSpacing: 2, marginBottom: 12 }}>PAYMENT CONFIRMED ON-CHAIN</div>
          <div style={{ fontSize: wide ? 48 : 34, letterSpacing: -1.2, marginBottom: 16, lineHeight: 1.1 }}>
            Welcome to the <span style={{ fontStyle: 'italic', color: TH.accent }}>desk.</span>
          </div>
          <div style={{ fontFamily: TH.serif, fontSize: 16, color: TH.inkSoft, lineHeight: 1.6, marginBottom: 28 }}>
            Your membership is active. A receipt is on its way to your email. Let's get you into the tools.
          </div>
          <Btn primary onClick={() => { onPaid(plan); go('home'); }} style={{ padding: '14px 24px' }}>Enter dashboard →</Btn>
        </div>
      </div>
    );
  }

  return (
    <div style={{ background: TH.bg, color: TH.ink, fontFamily: TH.serif, minHeight: 'calc(100vh - 57px)' }}>
      {/* Whop-style faux header */}
      <div style={{ background: TH.panel, borderBottom: `1px solid ${TH.rule}`, padding: '12px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: TH.mono, fontSize: 11, color: TH.inkSoft, letterSpacing: 1 }}>
          <div style={{ width: 22, height: 22, background: TH.accent, color: TH.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>W</div>
          SECURE CHECKOUT BY WHOP
        </div>
        <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1 }}>🔒 TLS · RATE LOCKED</div>
      </div>

      <div style={{ maxWidth: 980, margin: '0 auto', padding: wide ? '40px 32px' : '24px 16px', display: 'grid', gridTemplateColumns: wide ? '1.2fr 1fr' : '1fr', gap: 20 }}>
        {/* Left: payment */}
        <div style={{ background: TH.panel, border: `1px solid ${TH.rule}`, padding: wide ? 32 : 20 }}>
          {step === 'select' ? (
            <>
              <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.accent, letterSpacing: 2, marginBottom: 14 }}>STEP 1 OF 2 · CHOOSE ASSET</div>
              <div style={{ fontFamily: TH.serif, fontSize: 26, marginBottom: 20 }}>Pay with crypto</div>
              {coins.map(c => (
                <div key={c.sym} onClick={() => setCoin(c.sym)} style={{
                  display: 'flex', alignItems: 'center', gap: 14, padding: '14px',
                  border: `1px solid ${coin === c.sym ? TH.accent : TH.rule}`,
                  background: coin === c.sym ? TH.panelHi : 'transparent',
                  marginBottom: 8, cursor: 'pointer',
                }}>
                  <div style={{ width: 34, height: 34, borderRadius: '50%', background: TH.bg, border: `1px solid ${TH.rule}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: TH.mono, fontSize: 10, fontWeight: 700, color: TH.accent }}>{c.sym}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: TH.sans, fontSize: 14, fontWeight: 500, color: TH.ink }}>{c.name}</div>
                    <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 0.5 }}>{c.net}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: TH.mono, fontSize: 13, color: TH.ink }}>{c.amt} {c.sym}</div>
                    <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted }}>${total.toFixed(2)}</div>
                  </div>
                </div>
              ))}
              <Btn primary onClick={() => setStep('pay')} style={{ width: '100%', padding: 14, marginTop: 14 }}>Continue with {coin} →</Btn>
            </>
          ) : (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.accent, letterSpacing: 2 }}>STEP 2 OF 2 · SEND PAYMENT</div>
                <div style={{ fontFamily: TH.mono, fontSize: 11, color: countdown < 120 ? TH.red : TH.inkSoft }}>⏱ {mm}:{ss}</div>
              </div>
              <div style={{ fontFamily: TH.serif, fontSize: 24, marginBottom: 18 }}>Send exactly <span style={{ color: TH.accent }}>{sel.amt} {sel.sym}</span></div>

              <div style={{ background: TH.bg, border: `1px solid ${TH.rule}`, padding: 20, display: 'grid', gridTemplateColumns: wide ? '140px 1fr' : '1fr', gap: 20, alignItems: 'center', marginBottom: 16 }}>
                {/* Faux QR */}
                <div style={{ width: 140, height: 140, background: TH.ink, padding: 8, margin: wide ? 0 : '0 auto' }}>
                  <svg viewBox="0 0 21 21" width="124" height="124" shapeRendering="crispEdges">
                    {Array.from({length: 21*21}).map((_, i) => {
                      const x = i % 21, y = Math.floor(i / 21);
                      const corner = (x < 7 && y < 7) || (x > 13 && y < 7) || (x < 7 && y > 13);
                      const cornerInner = (x >= 2 && x <= 4 && y >= 2 && y <= 4) || (x >= 16 && x <= 18 && y >= 2 && y <= 4) || (x >= 2 && x <= 4 && y >= 16 && y <= 18);
                      if (corner && !(x === 0 || x === 6 || x === 14 || x === 20 || y === 0 || y === 6 || y === 14 || y === 20)) {
                        return cornerInner ? <rect key={i} x={x} y={y} width="1" height="1" fill={TH.bg}/> : null;
                      }
                      const on = ((x * 7 + y * 13 + (x^y)) % 3) === 0;
                      return on ? <rect key={i} x={x} y={y} width="1" height="1" fill={TH.bg}/> : null;
                    })}
                    {/* Corner squares */}
                    {[[0,0],[14,0],[0,14]].map(([x,y],i) => (
                      <g key={i}>
                        <rect x={x} y={y} width="7" height="1" fill={TH.bg}/>
                        <rect x={x} y={y+6} width="7" height="1" fill={TH.bg}/>
                        <rect x={x} y={y} width="1" height="7" fill={TH.bg}/>
                        <rect x={x+6} y={y} width="1" height="7" fill={TH.bg}/>
                        <rect x={x+2} y={y+2} width="3" height="3" fill={TH.bg}/>
                      </g>
                    ))}
                  </svg>
                </div>
                <div>
                  <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1.5, marginBottom: 6 }}>{sel.name.toUpperCase()} ADDRESS</div>
                  <div style={{ fontFamily: TH.mono, fontSize: 12, color: TH.ink, wordBreak: 'break-all', lineHeight: 1.5, marginBottom: 10 }}>{addr}</div>
                  <Btn small ghost onClick={copy}>{copied ? '✓ Copied' : '⎘ Copy address'}</Btn>
                </div>
              </div>

              <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1, lineHeight: 1.7, marginBottom: 18 }}>
                ⚠ SEND ONLY {sel.sym} ON THE {sel.net.toUpperCase()} NETWORK<br/>
                ⚠ AMOUNT MUST MATCH EXACTLY — WHOP AUTO-CONFIRMS ON 1 BLOCK
              </div>

              <Btn primary onClick={() => setStep('success')} style={{ width: '100%', padding: 14 }}>
                I've sent the payment — verify →
              </Btn>
              <div onClick={() => setStep('select')} style={{ textAlign: 'center', fontFamily: TH.mono, fontSize: 11, color: TH.inkSoft, marginTop: 12, cursor: 'pointer', letterSpacing: 1 }}>← CHANGE ASSET</div>
            </>
          )}
        </div>

        {/* Right: order summary */}
        <div>
          <div style={{ background: TH.panelHi, border: `1px solid ${TH.rule}`, padding: 24 }}>
            <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 2, marginBottom: 16 }}>ORDER</div>
            <div style={{ display: 'flex', gap: 14, marginBottom: 16, paddingBottom: 16, borderBottom: `1px solid ${TH.rule}` }}>
              <div style={{ width: 46, height: 46, background: TH.panel, border: `1px solid ${TH.accent}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Logo size={24}/>
              </div>
              <div>
                <div style={{ fontFamily: TH.serif, fontSize: 17, color: TH.ink }}>Walkforward Membership</div>
                <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1, marginTop: 4 }}>{plan.toUpperCase()} · AUTO-RENEW</div>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: TH.sans, fontSize: 13, color: TH.inkSoft, padding: '6px 0' }}>
              <span>{plan === 'yearly' ? 'Yearly plan' : 'Monthly plan'}</span><span>${price}.00</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: TH.sans, fontSize: 13, color: TH.inkSoft, padding: '6px 0' }}>
              <span>Network fee</span><span>$1.20</span>
            </div>
            <div style={{ height: 1, background: TH.rule, margin: '10px 0' }}/>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: TH.serif, fontSize: 20 }}>
              <span>Total</span><span style={{ color: TH.accent }}>${total.toFixed(2)}</span>
            </div>
            <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, marginTop: 18, lineHeight: 1.7, letterSpacing: 0.5 }}>
              ✓ 30-DAY REFUND VIA WHOP<br/>
              ✓ CANCEL ANY TIME<br/>
              ✓ INSTANT ACCESS ON CONFIRMATION
            </div>
          </div>
          <div onClick={() => go('pricing')} style={{ fontFamily: TH.mono, fontSize: 11, color: TH.inkSoft, marginTop: 14, cursor: 'pointer', letterSpacing: 1, textAlign: 'center' }}>
            ← BACK TO PRICING
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Checkout });
