// Checkout page — final step before payment handoff.

function CheckoutPage({ p }) {
  const [email, setEmail] = React.useState('');
  const [country, setCountry] = React.useState('US');
  const [agree, setAgree] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    try { const s = localStorage.getItem('pellex.email'); if (s) setEmail(s); } catch (e) {}
  }, []);

  const goStripe = async () => {
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      setErr('We need a valid email to deliver your kit.');
      return;
    }
    if (!agree) {
      setErr('You\'ll need to accept the refund + delivery terms.');
      return;
    }
    setErr('');
    setLoading(true);
    try { localStorage.setItem('pellex.email', email); } catch (e) {}
    try {
      const response = await fetch('https://pellex-email-intake.kevin-yuen.workers.dev/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, country }),
      });
      let body = {};
      try { body = await response.json(); } catch (e) {}
      if (!response.ok || !body.url) {
        throw new Error(body.error || 'Stripe checkout is unavailable right now. Please try again.');
      }
      window.location.href = body.url;
    } catch (error) {
      setErr(error && error.message ? error.message : 'Stripe checkout is unavailable right now. Please try again.');
      setLoading(false);
    }
  };

  return (
    <>
      
      <SubHeader p={p} kicker="Step 1 of 2 · Secure checkout" title="Checkout"/>

      <div className="checkout-desktop-grid">
        <section style={{ padding: '24px 22px 0' }}>
          {/* Order summary */}
          <Reveal>
            <div style={{
              padding: 18, borderRadius: 16,
              background: p.bgElev, border: `1px solid ${p.border}`,
              display: 'flex', flexDirection: 'column', gap: 12,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ color: p.textMute, fontSize: 11, fontFamily: PELLEX_FONTS.mono, letterSpacing: 0.4, textTransform: 'uppercase' }}>
                  Your order
                </span>
                <button onClick={() => window.pellexNav('kit')} style={{
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  color: p.accent, fontSize: 12, fontFamily: PELLEX_FONTS.body, fontWeight: 600,
                }}>Edit</button>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{
                  width: 46, height: 46, borderRadius: 10,
                  background: p.accent, color: p.accentInk,
                  display: 'grid', placeItems: 'center', flexShrink: 0,
                  fontFamily: PELLEX_FONTS.display, fontSize: 22, fontWeight: 700, lineHeight: 1,
                }}>P</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ color: p.text, fontSize: 14, fontWeight: 700 }}>AI Side Business Starter Kit</div>
                  <div style={{ color: p.textMute, fontSize: 12 }}>Lifetime access · instant delivery</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ color: p.textDim, fontSize: 12, textDecoration: 'line-through' }}>$49</div>
                  <div style={{ color: p.text, fontSize: 18, fontWeight: 700, fontFamily: PELLEX_FONTS.display }}>$9</div>
                </div>
              </div>
              <div style={{ borderTop: `1px dashed ${p.border}`, paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <Row p={p} k="Subtotal" v="$9.00"/>
                <Row p={p} k="Tax" v="calculated next"/>
                <Row p={p} k="Total" v="$9.00" bold/>
              </div>
            </div>
          </Reveal>
        </section>

        <section style={{ padding: '18px 22px 0' }}>
          <Reveal>
            <div style={{
              padding: 18, borderRadius: 16,
              background: p.bgElev, border: `1px solid ${p.border}`,
              display: 'flex', flexDirection: 'column', gap: 14,
            }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <label style={{ color: p.textMute, fontSize: 11, fontFamily: PELLEX_FONTS.mono, letterSpacing: 0.4, textTransform: 'uppercase' }}>
                  Email for delivery
                </label>
                <input type="email" value={email} onChange={e => { setEmail(e.target.value); setErr(''); }}
                  placeholder="you@example.com"
                  style={{
                    appearance: 'none', border: `1px solid ${err ? p.danger : p.border}`,
                    background: p.bgCard, color: p.text,
                    padding: '14px 14px', borderRadius: 12,
                    fontSize: 16, fontFamily: PELLEX_FONTS.body, outline: 'none',
                  }}/>
                <div style={{ color: p.textDim, fontSize: 11, fontFamily: PELLEX_FONTS.mono }}>
                  Receipt + download link sent here in ~10 seconds.
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <label style={{ color: p.textMute, fontSize: 11, fontFamily: PELLEX_FONTS.mono, letterSpacing: 0.4, textTransform: 'uppercase' }}>
                  Country
                </label>
                <select value={country} onChange={e => setCountry(e.target.value)} style={{
                  appearance: 'none', border: `1px solid ${p.border}`,
                  background: p.bgCard, color: p.text,
                  padding: '13px 14px', borderRadius: 12,
                  fontSize: 15, fontFamily: PELLEX_FONTS.body, outline: 'none',
                }}>
                  {['US','UK','CA','AU','TW','HK','SG','DE','FR','JP','Other'].map(c =>
                    <option key={c} value={c} style={{ background: p.bgCard, color: p.text }}>{c}</option>
                  )}
                </select>
              </div>

              <label style={{
                display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer',
                padding: 10, borderRadius: 10, background: p.bgCard, border: `1px solid ${p.border}`,
              }}>
                <input type="checkbox" checked={agree} onChange={e => { setAgree(e.target.checked); setErr(''); }}
                  style={{ marginTop: 2, accentColor: p.accent }}/>
                <span style={{ color: p.textMute, fontSize: 12.5, lineHeight: 1.45 }}>
                  Instant digital delivery. 14-day refund if it doesn't help you ship.
                  I've read the <span style={{ color: p.accent }}>terms</span> and <span style={{ color: p.accent }}>refund policy</span>.
                </span>
              </label>

              {err && <div style={{ color: p.danger, fontSize: 12, fontFamily: PELLEX_FONTS.mono }}>{err}</div>}

              <PrimaryCTA p={p} full sub="Stripe · Apple Pay · Card · iDEAL"
                onClick={goStripe}>
                {loading ? 'Connecting to Stripe…' : 'Continue to secure payment'}
              </PrimaryCTA>

              <div style={{
                display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8,
                color: p.textDim, fontSize: 11, fontFamily: PELLEX_FONTS.mono, letterSpacing: 0.3,
              }}>
                <LockIcon color={p.textDim}/>
                Encrypted payment by Stripe · we never see your card
              </div>
            </div>
          </Reveal>
        </section>
      </div>

      <section style={{ padding: '16px 22px 0' }}>
        <div style={{
          display: 'flex', justifyContent: 'center', gap: 14, padding: '14px 0',
          color: p.textDim, fontSize: 11, fontFamily: PELLEX_FONTS.mono, letterSpacing: 0.3,
        }}>
          <span>VISA</span><span>·</span><span>MC</span><span>·</span><span>AMEX</span><span>·</span><span>Apple Pay</span>
        </div>
      </section>

      <PageFooter p={p}/>
    </>
  );
}

function Row({ p, k, v, bold }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
      <span style={{ color: bold ? p.text : p.textMute, fontSize: bold ? 14 : 13, fontWeight: bold ? 700 : 400 }}>{k}</span>
      <span style={{ color: bold ? p.text : p.textMute, fontSize: bold ? 16 : 13, fontWeight: bold ? 700 : 500, fontFamily: bold ? PELLEX_FONTS.display : PELLEX_FONTS.body }}>{v}</span>
    </div>
  );
}

function LockIcon({ color }) {
  return (
    <svg width="11" height="13" viewBox="0 0 11 13" fill="none">
      <rect x="1" y="5" width="9" height="7" rx="1.5" stroke={color} strokeWidth="1.2"/>
      <path d="M3 5V3.5a2.5 2.5 0 015 0V5" stroke={color} strokeWidth="1.2"/>
    </svg>
  );
}

window.CheckoutPage = CheckoutPage;
