// checkout.jsx — Subscription checkout flow

function getPlanFromUrl() {
  if (typeof window === 'undefined') return null;
  const p = new URLSearchParams(window.location.search);
  const platform = p.get('platform') === 'twitch' ? 'twitch' : 'kick';
  const cycle = p.get('cycle') === 'aio' ? 'aio' : 'views';
  const planId = p.get('plan') || 'pro';
  const data = (window.PLAN_CATALOG || {})[platform];
  if (!data) return null;
  const plan = data[cycle].find((x) => x.id === planId) || data[cycle][data[cycle].length - 1];
  return { platform, cycle, plan };
}

function buildSummary(ctx) {
  const subtotal = ctx.plan.price;
  const fees = +(subtotal * 0.03).toFixed(2);
  const total = +(subtotal + fees).toFixed(2);
  return { ...ctx, subtotal, fees, total };
}

function Checkout() {
  const initial = getPlanFromUrl() || { platform: 'kick', cycle: 'views', plan: { id: 'pro', name: 'Pro Plan', price: 100, period: 'Month', features: [] } };
  const [step, setStep] = React.useState(0);
  const [channel, setChannel] = React.useState('pump_it_up_live');
  const [platform, setPlatform] = React.useState(initial.platform);
  const [paymentMethod, setPaymentMethod] = React.useState('card');
  const [crypto, setCrypto] = React.useState('btc');

  const summary = React.useMemo(() => buildSummary({
    platform, cycle: initial.cycle, plan: initial.plan,
  }), [platform, initial.cycle, initial.plan]);

  const isFree = summary.plan.price === 0;

  return (
    <Stage>
      <div style={{ padding: '24px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
        <div className="vb-row" style={{ marginBottom: 32 }}>
          <a href="index.html" className="vb-row" style={{ gap: 10, textDecoration: 'none', color: 'inherit' }}>
            <span style={{ fontWeight: 600, fontSize: 16, letterSpacing: '-0.015em' }}>Viewbot<span style={{ color: 'var(--vb-fg-3)' }}>.to</span></span>
          </a>
          <span className="vb-spacer"/>
          <Btn variant="ghost" size="sm" icon={<IconLock size={12}/>}>Secured by Stratum</Btn>
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 40 }}>
          {['Channel', 'Review', 'Payment', 'Confirm'].map((label, i) => (
            <div key={label} style={{ flex: 1 }}>
              <div style={{ height: 3, borderRadius: 2, background: i <= step ? 'linear-gradient(90deg, oklch(0.88 0.27 142), oklch(0.62 0.23 295))' : 'rgba(255,255,255,0.06)', marginBottom: 8 }}/>
              <div className="vb-row" style={{ gap: 8 }}>
                <span style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: i < step ? 'oklch(0.88 0.27 142 / 0.2)' : i === step ? '#fff' : 'rgba(255,255,255,0.06)',
                  color: i === step ? '#000' : i < step ? 'oklch(0.88 0.27 142)' : 'var(--vb-fg-3)',
                  fontSize: 11, fontWeight: 600,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: i === step ? 'none' : `1px solid ${i < step ? 'oklch(0.88 0.27 142 / 0.4)' : 'rgba(255,255,255,0.08)'}`,
                }}>{i < step ? <IconCheck size={11}/> : i + 1}</span>
                <span style={{ fontSize: 12, fontWeight: i === step ? 600 : 400, color: i === step ? 'var(--vb-fg-0)' : 'var(--vb-fg-3)' }}>{label}</span>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
          <Glass style={{ padding: 36, borderRadius: 24, minHeight: 520 }}>
            {step === 0 && <ChannelStep channel={channel} setChannel={setChannel} platform={platform} setPlatform={setPlatform}/>}
            {step === 1 && <ReviewStep summary={{ ...summary, channel }}/>}
            {step === 2 && <PaymentStep paymentMethod={paymentMethod} setPaymentMethod={setPaymentMethod} crypto={crypto} setCrypto={setCrypto} summary={summary} isFree={isFree}/>}
            {step === 3 && <ConfirmStep summary={summary} isFree={isFree}/>}

            {step < 3 && (
              <div className="vb-row" style={{ marginTop: 40, paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.06)' }}>
                <Btn variant="ghost" size="sm" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0}>← Back</Btn>
                <span className="vb-spacer"/>
                <Btn variant="primary" size="lg" iconRight={<IconArrow size={16}/>} onClick={() => setStep(step + 1)}>
                  {step === 2 ? (isFree ? 'Activate free trial' : 'Confirm subscription') : 'Continue'}
                </Btn>
              </div>
            )}
          </Glass>

          <div style={{ position: 'sticky', top: 24, alignSelf: 'flex-start' }}>
            <Glass style={{ padding: 28, borderRadius: 24 }}>
              <span className="vb-caption" style={{ display: 'block', marginBottom: 16 }}>Subscription summary</span>

              <div style={{ padding: 16, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.05)', marginBottom: 16 }}>
                <div className="vb-row" style={{ gap: 10, marginBottom: 8 }}>
                  <PlatformPill platform={platform}/>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{summary.plan.name}</span>
                  <span className="vb-spacer"/>
                  <span style={{ fontSize: 11, color: 'var(--vb-fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{summary.cycle}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--vb-fg-2)' }}>{channel} · ${summary.plan.price} / {summary.plan.period}</div>
              </div>

              <div className="vb-col" style={{ gap: 10, marginBottom: 16 }}>
                <LineRow label={`${summary.plan.name} subscription`} amount={summary.plan.price}/>
                {!isFree && <LineRow label="Network fee (3%)" amount={summary.fees} sub/>}
              </div>

              <div className="vb-divider"/>

              <div className="vb-row" style={{ justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{isFree ? 'Trial' : 'Due today'}</span>
                <span className="vb-mono" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>${summary.total.toFixed(2)}</span>
              </div>
              <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>
                {isFree ? `Free for ${summary.plan.period} · No card required` : `Renews monthly · Cancel anytime`}
              </span>
            </Glass>

            <div className="vb-row" style={{ gap: 8, padding: 16, marginTop: 12, color: 'var(--vb-fg-3)', fontSize: 11 }}>
              <IconShield size={14}/>
              <span>256-bit encryption · No 2FA · Cancel anytime</span>
            </div>
          </div>
        </div>
      </div>
    </Stage>
  );
}

function ChannelStep({ channel, setChannel, platform, setPlatform }) {
  return (
    <>
      <span className="vb-caption" style={{ display: 'block', marginBottom: 6 }}>Step 1 of 4</span>
      <h2 className="vb-h1" style={{ marginBottom: 8 }}>Where should we deliver?</h2>
      <p className="vb-body" style={{ marginBottom: 32, color: 'var(--vb-fg-2)' }}>Drop your channel URL or handle. We'll detect the platform automatically.</p>

      <span className="vb-label">Platform</span>
      <Tabs items={[
        { value: 'kick', label: 'Kick.com', icon: <IconKick size={12}/> },
        { value: 'twitch', label: 'Twitch.tv', icon: <IconTwitch size={12}/> },
      ]} value={platform} onChange={setPlatform} style={{ marginBottom: 24 }}/>

      <span className="vb-label">Channel handle</span>
      <div style={{ position: 'relative', marginBottom: 24 }}>
        <span style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)', color: 'var(--vb-fg-3)', fontSize: 14 }}>{platform === 'kick' ? 'kick.com/' : 'twitch.tv/'}</span>
        <input className="vb-input" value={channel} onChange={(e) => setChannel(e.target.value)}
               style={{ paddingLeft: platform === 'kick' ? 95 : 100, height: 56, fontSize: 15, fontFamily: 'var(--vb-font-mono)' }}/>
        <span style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)', color: 'oklch(0.88 0.27 142)' }}><IconCheck size={16}/></span>
      </div>

      <Glass soft style={{ padding: 16, borderRadius: 16 }}>
        <div className="vb-row" style={{ gap: 14 }}>
          <Avatar name="P" size={48} hue={platform === 'kick' ? 142 : 295}/>
          <div className="vb-col" style={{ flex: 1 }}>
            <div className="vb-row" style={{ gap: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>{channel}</span>
              <PlatformPill platform={platform}/>
              <LivePill/>
            </div>
            <span style={{ fontSize: 12, color: 'var(--vb-fg-2)', marginTop: 2 }}>Variety streamer · 18.4K followers · streaming "Just Chatting"</span>
          </div>
          <div className="vb-col" style={{ alignItems: 'flex-end' }}>
            <span className="vb-caption">Current viewers</span>
            <span className="vb-mono" style={{ fontSize: 18, fontWeight: 600 }}><LiveCounter base={487} jitter={8}/></span>
          </div>
        </div>
      </Glass>

      <div style={{ marginTop: 24, padding: 14, borderRadius: 12, background: 'oklch(0.88 0.27 142 / 0.06)', border: '1px solid oklch(0.88 0.27 142 / 0.2)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <span style={{ color: 'oklch(0.88 0.27 142)', marginTop: 1 }}><IconCheck size={14}/></span>
        <span style={{ fontSize: 12, color: 'var(--vb-fg-1)', lineHeight: 1.5 }}>Channel verified. Boost will start immediately when you go live.</span>
      </div>
    </>
  );
}

function ReviewStep({ summary }) {
  return (
    <>
      <span className="vb-caption" style={{ display: 'block', marginBottom: 6 }}>Step 2 of 4</span>
      <h2 className="vb-h1" style={{ marginBottom: 8 }}>Review your plan</h2>
      <p className="vb-body" style={{ marginBottom: 32, color: 'var(--vb-fg-2)' }}>Quick scan before we lock it in.</p>

      <div className="vb-col" style={{ gap: 12 }}>
        <ReviewRow label="Channel" value={`${summary.platform === 'kick' ? 'kick.com/' : 'twitch.tv/'}${summary.channel}`}/>
        <ReviewRow label="Plan" value={`${summary.plan.name} (${summary.cycle.toUpperCase()})`}/>
        <ReviewRow label="Price" value={`$${summary.plan.price} / ${summary.plan.period}`}/>
        <ReviewRow label="Billing" value={summary.plan.price === 0 ? 'Free trial · no card' : 'Renews monthly · cancel anytime'}/>
        <ReviewRow label="Start time" value="Immediately upon activation" accent/>
      </div>

      {summary.plan.features && summary.plan.features.length > 0 && (
        <div style={{ marginTop: 24, padding: 18, borderRadius: 14, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)' }}>
          <span className="vb-caption" style={{ display: 'block', marginBottom: 12 }}>Included in {summary.plan.name}</span>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {summary.plan.features.map((f) => (
              <div key={f} className="vb-row" style={{ gap: 8 }}>
                <span style={{ color: 'oklch(0.88 0.27 142)', flexShrink: 0 }}><IconCheck size={12}/></span>
                <span style={{ fontSize: 12, color: 'var(--vb-fg-1)' }}>{f}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ marginTop: 24, padding: 16, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <div className="vb-row" style={{ gap: 10, marginBottom: 10 }}>
          <input type="checkbox" id="tos" defaultChecked style={{ accentColor: 'oklch(0.88 0.27 142)' }}/>
          <label htmlFor="tos" style={{ fontSize: 12, color: 'var(--vb-fg-1)', lineHeight: 1.5 }}>I understand this service is for entertainment and growth purposes. I agree to the <a href="#" style={{ color: 'var(--vb-fg-0)' }}>Terms of Use</a>.</label>
        </div>
      </div>
    </>
  );
}

function PaymentStep({ paymentMethod, setPaymentMethod, crypto, setCrypto, summary, isFree }) {
  if (isFree) {
    return (
      <>
        <span className="vb-caption" style={{ display: 'block', marginBottom: 6 }}>Step 3 of 4</span>
        <h2 className="vb-h1" style={{ marginBottom: 8 }}>Free trial</h2>
        <p className="vb-body" style={{ marginBottom: 32, color: 'var(--vb-fg-2)' }}>No payment needed for the {summary.plan.period} trial. Add a card later if you want to upgrade.</p>

        <Glass soft style={{ padding: 24, borderRadius: 16 }}>
          <div className="vb-row" style={{ gap: 14, marginBottom: 16 }}>
            <span style={{ width: 44, height: 44, borderRadius: 12, background: 'oklch(0.88 0.27 142 / 0.18)', color: 'oklch(0.88 0.27 142)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IconBolt size={20}/>
            </span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>Activate the {summary.plan.name} trial</div>
              <div style={{ fontSize: 12, color: 'var(--vb-fg-2)' }}>Lasts {summary.plan.period}. Limited features. No card required.</div>
            </div>
          </div>
          <span className="vb-label">Email for receipt</span>
          <input className="vb-input" placeholder="you@email.com" style={{ height: 52 }}/>
        </Glass>
      </>
    );
  }

  const cryptoTotal = (summary.total * 0.94).toFixed(2);
  const btcRate = 100000;
  const btcAmount = (summary.total * 0.94 / btcRate).toFixed(6);
  return (
    <>
      <span className="vb-caption" style={{ display: 'block', marginBottom: 6 }}>Step 3 of 4</span>
      <h2 className="vb-h1" style={{ marginBottom: 8 }}>Payment</h2>
      <p className="vb-body" style={{ marginBottom: 32, color: 'var(--vb-fg-2)' }}>Choose how you'd like to pay. Crypto gets a 6% discount on the first month.</p>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 28 }}>
        <PayMethod active={paymentMethod === 'card'} onClick={() => setPaymentMethod('card')} icon={<IconCard size={18}/>} title="Credit card" desc="Visa, Mastercard, AmEx"/>
        <PayMethod active={paymentMethod === 'crypto'} onClick={() => setPaymentMethod('crypto')} icon={<IconBolt size={18}/>} title="Crypto" desc="6% off first month" discount/>
      </div>

      {paymentMethod === 'card' ? (
        <div className="vb-col" style={{ gap: 16 }}>
          <div>
            <span className="vb-label">Card number</span>
            <input className="vb-input" placeholder="4242 4242 4242 4242" style={{ height: 52, fontFamily: 'var(--vb-font-mono)' }}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            <div><span className="vb-label">Expiry</span><input className="vb-input" placeholder="04 / 28" style={{ height: 52, fontFamily: 'var(--vb-font-mono)' }}/></div>
            <div><span className="vb-label">CVC</span><input className="vb-input" placeholder="•••" style={{ height: 52, fontFamily: 'var(--vb-font-mono)' }}/></div>
            <div><span className="vb-label">ZIP</span><input className="vb-input" placeholder="10001" style={{ height: 52, fontFamily: 'var(--vb-font-mono)' }}/></div>
          </div>
          <div>
            <span className="vb-label">Email for receipt</span>
            <input className="vb-input" placeholder="you@email.com" style={{ height: 52 }}/>
          </div>
        </div>
      ) : (
        <div>
          <Tabs items={[
            { value: 'btc', label: 'Bitcoin' },
            { value: 'eth', label: 'Ethereum' },
            { value: 'usdt', label: 'USDT' },
            { value: 'sol', label: 'Solana' },
          ]} value={crypto} onChange={setCrypto} style={{ marginBottom: 20 }}/>

          <Glass soft style={{ padding: 24, borderRadius: 16, textAlign: 'center' }}>
            <div style={{ width: 160, height: 160, margin: '0 auto 16px', background: '#fff', borderRadius: 12, padding: 12 }}>
              <svg width="100%" height="100%" viewBox="0 0 100 100">
                {Array.from({ length: 16 }).map((_, r) => Array.from({ length: 16 }).map((_, c) => {
                  const v = (r * 7 + c * 13 + r * c) % 5;
                  return v < 2 ? <rect key={`${r}${c}`} x={c*6+2} y={r*6+2} width="5" height="5" fill="#000"/> : null;
                }))}
                <rect x="4" y="4" width="20" height="20" fill="none" stroke="#000" strokeWidth="3"/>
                <rect x="76" y="4" width="20" height="20" fill="none" stroke="#000" strokeWidth="3"/>
                <rect x="4" y="76" width="20" height="20" fill="none" stroke="#000" strokeWidth="3"/>
              </svg>
            </div>
            <span className="vb-caption" style={{ display: 'block', marginBottom: 8 }}>Send exactly</span>
            <div className="vb-mono" style={{ fontSize: 22, fontWeight: 600, marginBottom: 4 }}>{btcAmount} BTC</div>
            <div style={{ fontSize: 12, color: 'var(--vb-fg-3)', marginBottom: 16 }}>${cryptoTotal} USD (after 6% discount)</div>
            <div className="vb-row" style={{ gap: 8, padding: 10, borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.05)' }}>
              <code style={{ fontFamily: 'var(--vb-font-mono)', fontSize: 11, color: 'var(--vb-fg-1)', flex: 1, textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis' }}>bc1q9zxy...4r3vh82lk</code>
              <Btn variant="glass" size="sm" icon={<IconCopy size={12}/>}>Copy</Btn>
            </div>
          </Glass>
        </div>
      )}
    </>
  );
}

function ConfirmStep({ summary, isFree }) {
  return (
    <div style={{ textAlign: 'center', padding: '20px 20px 40px' }}>
      <div style={{ width: 88, height: 88, margin: '40px auto 24px', borderRadius: '50%',
        background: 'linear-gradient(135deg, oklch(0.92 0.27 142), oklch(0.78 0.27 142))',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 0 60px -10px oklch(0.88 0.27 142 / 0.6), 0 1px 0 rgba(255,255,255,0.4) inset',
        position: 'relative',
      }}>
        <IconCheck size={40} style={{ color: '#06140a' }}/>
        <div style={{ position: 'absolute', inset: -20, borderRadius: '50%', border: '1px solid oklch(0.88 0.27 142 / 0.3)', animation: 'vb-ring 2s ease-out infinite' }}/>
      </div>
      <h2 className="vb-display-3" style={{ marginBottom: 12 }}>{isFree ? 'Trial activated.' : `${summary.plan.name} active.`}</h2>
      <p className="vb-body" style={{ fontSize: 15, marginBottom: 32, color: 'var(--vb-fg-2)', maxWidth: 420, margin: '0 auto 32px' }}>
        {isFree
          ? `You can run boosts for the next ${summary.plan.period}. Upgrade anytime to keep going.`
          : 'Your subscription is live. Run as many boosts as you want for the month.'}
      </p>

      <Glass soft style={{ padding: 20, borderRadius: 16, maxWidth: 380, margin: '0 auto 24px', textAlign: 'left' }}>
        <div className="vb-row" style={{ marginBottom: 8 }}>
          <span style={{ fontSize: 12, color: 'var(--vb-fg-3)' }}>Subscription ID</span>
          <span className="vb-spacer"/>
          <span className="vb-mono" style={{ fontSize: 12, fontWeight: 500 }}>VB-2042-8C19</span>
        </div>
        <div className="vb-row">
          <span style={{ fontSize: 12, color: 'var(--vb-fg-3)' }}>Charged today</span>
          <span className="vb-spacer"/>
          <span className="vb-mono" style={{ fontSize: 12, fontWeight: 500 }}>${summary.total.toFixed(2)}</span>
        </div>
      </Glass>

      <div className="vb-row" style={{ gap: 8, justifyContent: 'center' }}>
        <Btn variant="primary" size="lg" iconRight={<IconArrow size={16}/>} href="dashboard.html">Open dashboard</Btn>
        <Btn variant="glass" size="lg" icon={<IconReceipt size={14}/>}>Download receipt</Btn>
      </div>

      <style>{`@keyframes vb-ring{0%{transform:scale(0.8);opacity:1}100%{transform:scale(1.3);opacity:0}}`}</style>
    </div>
  );
}

function PayMethod({ active, onClick, icon, title, desc, discount }) {
  return (
    <button onClick={onClick} style={{
      padding: 18, border: 'none', cursor: 'pointer', textAlign: 'left',
      background: active ? 'rgba(255,255,255,0.08)' : 'rgba(255,255,255,0.02)',
      borderRadius: 14,
      boxShadow: active ? '0 1px 0 rgba(255,255,255,0.18) inset, 0 0 0 1px rgba(255,255,255,0.2)' : '0 0 0 1px rgba(255,255,255,0.06)',
      color: 'inherit', fontFamily: 'inherit',
    }}>
      <div className="vb-row" style={{ gap: 12, marginBottom: 6 }}>
        <span style={{ width: 32, height: 32, borderRadius: 9, background: 'rgba(255,255,255,0.06)', color: 'var(--vb-fg-1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</span>
        <span style={{ fontSize: 14, fontWeight: 600 }}>{title}</span>
        {discount && <span className="vb-badge vb-badge-kick" style={{ marginLeft: 'auto', height: 20 }}>−6%</span>}
      </div>
      <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>{desc}</span>
    </button>
  );
}

function ReviewRow({ label, value, accent }) {
  return (
    <div className="vb-row" style={{ padding: '14px 18px', background: 'rgba(255,255,255,0.02)', borderRadius: 12, border: '1px solid rgba(255,255,255,0.05)' }}>
      <span style={{ fontSize: 13, color: 'var(--vb-fg-2)' }}>{label}</span>
      <span className="vb-spacer"/>
      <span style={{ fontSize: 13, fontWeight: 500, color: accent ? 'oklch(0.85 0.18 142)' : 'var(--vb-fg-0)' }}>{value}</span>
    </div>
  );
}

function LineRow({ label, amount, sub }) {
  return (
    <div className="vb-row" style={{ justifyContent: 'space-between', fontSize: sub ? 12 : 13, color: sub ? 'var(--vb-fg-3)' : 'var(--vb-fg-1)' }}>
      <span>{label}</span>
      <span className="vb-mono">${amount.toFixed(2)}</span>
    </div>
  );
}

Object.assign(window, { Checkout });
