/* My Vital Cell — Checkout */
function Checkout({ onNav }) {
  const { Button, Input, Select, Eyebrow, Badge } = window.VitalCellDesignSystem_fbb4ec;

  const [items, setItems] = React.useState(() => window.VC_CART.get());
  React.useEffect(() => {
    const h = () => setItems(window.VC_CART.get());
    window.addEventListener('vc-cart-change', h);
    return () => window.removeEventListener('vc-cart-change', h);
  }, []);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const [step, setStep] = React.useState(1); // 1 contact, 2 shipping, 3 payment, 4 review, 5 confirm
  const [orderId, setOrderId] = React.useState('');
  const [placing, setPlacing] = React.useState(false);
  const [payError, setPayError] = React.useState('');


  const [form, setForm] = React.useState({
    email: '', firstName: '', lastName: '', organization: '',
    address1: '', address2: '', city: '', region: '', postal: '', country: 'United States',
    shipMethod: 'standard',
    cardName: '', cardNumber: '', cardExp: '', cardCvc: '',
    researchAck: false, termsAck: false, fdaAck: false,
  });
  const upd = (k) => (e) => setForm((f) => ({ ...f, [k]: e && e.target ? (e.target.type === 'checkbox' ? e.target.checked : e.target.value) : e }));

  const subtotal = items.reduce((s, it) => s + (it.price || 0) * (it.qty || 1), 0);
  const shipRates = { standard: 18, standard: 34, express: 62 };
  const shipping = items.length ? shipRates[form.shipMethod] : 0;
  const tax = Math.round(subtotal * 0.0725 * 100) / 100;
  const total = subtotal + shipping + tax;
  const fmt = (n) => '$' + n.toFixed(2);

  const stepValid = {
    1: /.+@.+\..+/.test(form.email) && form.firstName && form.lastName,
    2: form.address1 && form.city && form.region && form.postal,
    3: form.cardName && form.cardNumber.replace(/\s/g, '').length >= 13 && /^\d{2}\/\d{2}$/.test(form.cardExp) && form.cardCvc.length >= 3,
    4: form.researchAck && form.termsAck && form.fdaAck,
  };

  const next = () => setStep((s) => Math.min(4, s + 1));
  const back = () => setStep((s) => Math.max(1, s - 1));

  const placeOrder = async () => {
    setPlacing(true);
    setPayError('');
    try {
      const stripe = await window.VC_STRIPE.getStripe();
      const { clientSecret } = await window.VC_STRIPE.createPaymentIntent({
        amount: Math.round(total * 100),
        currency: 'usd',
        items: items.map((it) => ({ name: it.name, qty: it.qty || 1, price: it.price })),
        email: form.email,
      });
      const [expMonth, expYear] = form.cardExp.split('/');
      const result = await stripe.confirmCardPayment(clientSecret, {
        payment_method: {
          card: {
            number: form.cardNumber.replace(/\s/g, ''),
            exp_month: parseInt(expMonth, 10),
            exp_year: parseInt('20' + expYear, 10),
            cvc: form.cardCvc,
          },
          billing_details: {
            name: form.cardName,
            email: form.email,
            address: { line1: form.address1, line2: form.address2, city: form.city, state: form.region, postal_code: form.postal, country: form.country },
          },
        },
        __amount: Math.round(total * 100),
      });
      if (result.error) {
        setPayError(result.error.message || 'Payment could not be processed.');
        setStep(3);
        setPlacing(false);
        return;
      }
      const pi = result.paymentIntent;
      const id = 'MVC-' + (pi.id.slice(-8) || Math.random().toString(36).slice(2, 7)).toUpperCase() + '-' + Date.now().toString().slice(-4);
      setOrderId(id);
      window.VC_CART.clear();
      setStep(5);
      setPlacing(false);
      window.scrollTo({ top: 0, behavior: 'instant' });
    } catch (err) {
      setPayError((err && err.message) || 'Something went wrong. Please try again.');
      setPlacing(false);
    }
  };


  // Empty state
  if (items.length === 0 && step !== 5) {
    return (
      <section style={{ maxWidth: 780, margin: '0 auto', padding: 'clamp(80px,10vw,140px) clamp(20px,4vw,56px)', textAlign: 'center' }}>
        <Eyebrow>Checkout</Eyebrow>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 300, textTransform: 'uppercase', letterSpacing: '0.03em', fontSize: 'clamp(2rem,4vw,3rem)', color: 'var(--color-ink-strong)', margin: '18px 0 14px' }}>Your cart is empty</h1>
        <p style={{ color: 'var(--color-text)', fontSize: 15, lineHeight: 1.7, marginBottom: 32 }}>Add research compounds to your cart to begin checkout. Every order is CoA-matched and shipped under shipping integrity.</p>
        <div style={{ display: 'inline-flex', gap: 12 }}>
          <Button variant="primary" onClick={() => onNav('compounds')}>Browse compounds</Button>
          <Button variant="secondary" onClick={() => onNav('home')}>Back home</Button>
        </div>
      </section>
    );
  }

  // Confirmation
  if (step === 5) {
    return (
      <section style={{ maxWidth: 820, margin: '0 auto', padding: 'clamp(64px,8vw,110px) clamp(20px,4vw,56px)' }}>
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', padding: 'clamp(36px,5vw,64px)', textAlign: 'center', boxShadow: 'var(--shadow-sm)' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 72, height: 72, borderRadius: '50%', background: 'var(--color-accent-soft, #FBEEF1)', color: 'var(--color-accent)', margin: '0 auto 24px' }}>
            <i data-lucide="check" style={{ width: 32, height: 32 }}></i>
          </div>
          <div style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase', color: 'var(--color-accent)', marginBottom: 10 }}>Order confirmed</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 300, textTransform: 'uppercase', letterSpacing: '0.03em', fontSize: 'clamp(2rem,4vw,2.8rem)', color: 'var(--color-ink-strong)', margin: '0 0 12px' }}>Thank you, {form.firstName || 'researcher'}.</h1>
          <p style={{ color: 'var(--color-text)', fontSize: 15, lineHeight: 1.7, maxWidth: 56 + 'ch', margin: '0 auto 22px' }}>Your order is queued for our team. A confirmation with CoAs (available on request), shipping manifest and tracking will arrive at <b>{form.email}</b> within one business day.</p>
          <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 6, padding: '18px 26px', border: '1px dashed var(--color-border)', borderRadius: 4, fontFamily: 'var(--font-mono, monospace)', fontSize: 12, color: 'var(--color-ink-strong)', marginBottom: 28 }}>
            <span style={{ color: 'var(--color-text-muted)', letterSpacing: '0.16em', textTransform: 'uppercase', fontSize: 10 }}>Order reference</span>
            <span style={{ fontSize: 18, letterSpacing: '0.06em' }}>{orderId}</span>
          </div>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            <Button variant="primary" onClick={() => onNav('compounds')}>Continue researching</Button>
            <Button variant="secondary" onClick={() => onNav('home')}>Return home</Button>
          </div>
        </div>
      </section>
    );
  }

  const stepLabels = ['Contact', 'Shipping', 'Payment', 'Review'];

  return (
    <section style={{ maxWidth: 1240, margin: '0 auto', padding: 'clamp(40px,5vw,72px) clamp(20px,4vw,56px)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', marginBottom: 28 }}>
        <div>
          <Eyebrow>Secure checkout</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 300, textTransform: 'uppercase', letterSpacing: '0.03em', fontSize: 'clamp(2rem,4vw,2.8rem)', color: 'var(--color-ink-strong)', margin: '12px 0 0' }}>Complete your order</h1>
        </div>
        <button onClick={() => onNav('compounds')} style={{ appearance: 'none', background: 'transparent', border: 0, color: 'var(--color-text-muted)', fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <i data-lucide="arrow-left" style={{ width: 14, height: 14 }}></i> Keep shopping
        </button>
      </div>

      {/* Stepper */}
      <ol style={{ listStyle: 'none', margin: '0 0 34px', padding: 0, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {stepLabels.map((label, i) => {
          const n = i + 1;
          const done = step > n;
          const active = step === n;
          return (
            <li key={label} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', border: '1px solid ' + (active ? 'var(--color-ink-strong)' : 'var(--color-border)'), background: active ? 'var(--color-ink-strong)' : (done ? 'var(--color-accent-soft, #FBEEF1)' : 'transparent'), color: active ? 'var(--color-on-ink,#fff)' : (done ? 'var(--color-accent)' : 'var(--color-text-muted)'), borderRadius: 4 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 22, height: 22, borderRadius: '50%', background: active ? 'rgba(255,255,255,0.14)' : (done ? 'var(--color-accent)' : 'transparent'), border: (active || done) ? '0' : '1px solid var(--color-border)', color: done ? '#fff' : 'inherit', fontFamily: 'var(--font-mono, monospace)', fontSize: 11, fontWeight: 700 }}>
                {done ? <i data-lucide="check" style={{ width: 12, height: 12 }}></i> : n}
              </span>
              <span style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase' }}>{label}</span>
            </li>
          );
        })}
      </ol>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 'clamp(24px,3vw,40px)', alignItems: 'start' }}>
        {/* LEFT: form */}
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', padding: 'clamp(24px,3vw,40px)', boxShadow: 'var(--shadow-sm)' }}>
          {step === 1 && (
            <div>
              <SectionTitle n="01" title="Contact information" hint="Where your CoA and tracking updates will be sent." />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 22 }}>
                <div style={{ gridColumn: '1 / -1' }}><Input label="Email" type="email" value={form.email} onChange={upd('email')} placeholder="you@email.com" /></div>
                <Input label="First name" value={form.firstName} onChange={upd('firstName')} placeholder="Jane" />
                <Input label="Last name" value={form.lastName} onChange={upd('lastName')} placeholder="Doe" />
                <div style={{ gridColumn: '1 / -1' }}><Input label="Organization (optional)" value={form.organization} onChange={upd('organization')} placeholder="Company, clinic or group" /></div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <SectionTitle n="02" title="Shipping address" hint="We ship under documented care to research addresses only." />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 22 }}>
                <div style={{ gridColumn: '1 / -1' }}><Input label="Street address" value={form.address1} onChange={upd('address1')} placeholder="1200 Research Parkway" /></div>
                <div style={{ gridColumn: '1 / -1' }}><Input label="Suite / building (optional)" value={form.address2} onChange={upd('address2')} placeholder="Suite 4B" /></div>
                <Input label="City" value={form.city} onChange={upd('city')} placeholder="Cambridge" />
                <Input label="State / Region" value={form.region} onChange={upd('region')} placeholder="MA" />
                <Input label="Postal code" value={form.postal} onChange={upd('postal')} placeholder="02139" />
                <Select label="Country" value={form.country} onChange={upd('country')}>
                  <option>United States</option><option>Canada</option><option>United Kingdom</option><option>Germany</option><option>Switzerland</option><option>Australia</option>
                </Select>
              </div>

              <div style={{ marginTop: 32 }}>
                <SectionTitle n="03" title="Shipping method" hint="Standard shipping is used for all orders." />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18 }}>
                  {[
                    { id: 'standard', name: 'Standard ambient', eta: '5–7 business days', price: 18, note: 'For non-sensitive supplies only.' },
                    { id: 'standard', name: 'Standard shipping', eta: '2–3 business days', price: 34, note: 'Protective packaging with tracked delivery.' },
                    { id: 'express', name: 'Express shipping', eta: 'Next business day', price: 62, note: 'Priority overnight with signature required.' },
                  ].map((o) => {
                    const sel = form.shipMethod === o.id;
                    return (
                      <label key={o.id} style={{ display: 'grid', gridTemplateColumns: '22px 1fr auto', gap: 14, padding: '16px 18px', border: '1px solid ' + (sel ? 'var(--color-ink-strong)' : 'var(--color-border)'), borderRadius: 4, cursor: 'pointer', background: sel ? 'var(--color-surface-haze)' : 'transparent' }}>
                        <span style={{ marginTop: 3, width: 16, height: 16, borderRadius: '50%', border: '2px solid ' + (sel ? 'var(--color-accent)' : 'var(--color-border)'), background: sel ? 'var(--color-accent)' : 'transparent', boxShadow: sel ? 'inset 0 0 0 3px #fff' : 'none' }} />
                        <div>
                          <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--color-ink-strong)' }}>{o.name}</div>
                          <div style={{ fontSize: 12, color: 'var(--color-text-muted)', marginTop: 2 }}>{o.eta} · {o.note}</div>
                        </div>
                        <div style={{ fontFamily: 'var(--font-mono, monospace)', fontWeight: 600, color: 'var(--color-ink-strong)' }}>{fmt(o.price)}</div>
                        <input type="radio" name="ship" checked={sel} onChange={() => setForm((f) => ({ ...f, shipMethod: o.id }))} style={{ display: 'none' }} />
                      </label>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <SectionTitle n="04" title="Payment" hint="Card payments are processed by Stripe over TLS. We also accept Zelle to (602) 471-2152 — include your order number in the memo." />

              {/* Test-mode banner */}
              {!(window.VC_STRIPE && window.VC_STRIPE.isLive) && (
                <div style={{ marginTop: 16, marginBottom: 6, padding: '10px 14px', border: '1px solid #f4c430', background: '#fff8dd', borderRadius: 4, fontSize: 12, color: '#6b4a00', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <i data-lucide="flask-conical" style={{ width: 14, height: 14 }}></i>
                  <span><b>Stripe test mode.</b> No card is charged. Use <span style={{ fontFamily: 'var(--font-mono, monospace)' }}>4242 4242 4242 4242</span> to succeed, <span style={{ fontFamily: 'var(--font-mono, monospace)' }}>4000 0000 0000 0002</span> to trigger a decline.</span>
                </div>
              )}

              {/* Express checkout row */}
              <div style={{ marginTop: 20 }}>
                <div style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--color-text-muted)', textAlign: 'center', marginBottom: 12 }}>Express checkout</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                  {[
                    { id: 'apple', label: '\uf179  Pay', bg: '#000', fg: '#fff' },
                    { id: 'google', label: 'G Pay', bg: '#fff', fg: '#3c4043', border: '1px solid #dadce0' },
                    { id: 'link', label: 'Link', bg: '#00d66f', fg: '#0a2540' },
                  ].map((b) => (
                    <button key={b.id} type="button" onClick={() => setPayError('Express wallets appear on live domains once your Stripe account is connected.')} style={{ appearance: 'none', border: b.border || '1px solid transparent', background: b.bg, color: b.fg, padding: '12px 0', borderRadius: 6, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, letterSpacing: '0.02em', cursor: 'pointer' }}>{b.label}</button>
                  ))}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '22px 0 18px', color: 'var(--color-text-muted)', fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.22em' }}>
                  <span style={{ flex: 1, height: 1, background: 'var(--color-border)' }} />
                  OR PAY WITH CARD
                  <span style={{ flex: 1, height: 1, background: 'var(--color-border)' }} />
                </div>
              </div>

              {/* Card fields — Stripe Payment Element look */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
                <div style={{ gridColumn: '1 / -1' }}><Input label="Name on card" value={form.cardName} onChange={upd('cardName')} placeholder="Dr. Jane Doe" /></div>
                <div style={{ gridColumn: '1 / -1', position: 'relative' }}>
                  <Input label="Card number" value={form.cardNumber} onChange={(e) => setForm((f) => ({ ...f, cardNumber: e.target.value.replace(/[^\d]/g, '').slice(0, 19).replace(/(\d{4})(?=\d)/g, '$1 ') }))} placeholder="4242 4242 4242 4242" inputMode="numeric" />
                  <div style={{ position: 'absolute', right: 12, top: 34, display: 'flex', gap: 6, alignItems: 'center', pointerEvents: 'none' }}>
                    {['#1a1f71', '#eb001b', '#0071ce', '#2a2a2a'].map((c, i) => (
                      <span key={i} style={{ width: 26, height: 16, borderRadius: 3, background: c, opacity: 0.75 }} />
                    ))}
                  </div>
                </div>
                <Input label="Expiration (MM/YY)" value={form.cardExp} onChange={(e) => { let v = e.target.value.replace(/[^\d]/g, '').slice(0, 4); if (v.length >= 3) v = v.slice(0, 2) + '/' + v.slice(2); setForm((f) => ({ ...f, cardExp: v })); }} placeholder="12/28" inputMode="numeric" />
                <Input label="CVC" value={form.cardCvc} onChange={(e) => setForm((f) => ({ ...f, cardCvc: e.target.value.replace(/[^\d]/g, '').slice(0, 4) }))} placeholder="123" inputMode="numeric" />
              </div>

              {payError && (
                <div style={{ marginTop: 16, padding: '12px 14px', background: '#fdecee', border: '1px solid #f5b5bd', borderRadius: 4, color: '#9a0e26', fontSize: 13, display: 'flex', gap: 10, alignItems: 'center' }}>
                  <i data-lucide="alert-circle" style={{ width: 16, height: 16, flex: '0 0 auto' }}></i>
                  <span>{payError}</span>
                </div>
              )}

              <div style={{ marginTop: 22, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, fontSize: 11, color: 'var(--color-text-muted)', letterSpacing: '0.08em' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-mono, monospace)' }}>
                  <i data-lucide="lock" style={{ width: 12, height: 12, color: 'var(--color-accent)' }}></i>
                  256-BIT TLS · PCI-DSS SAQ-A
                </span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-body)' }}>
                  Powered by <b style={{ color: '#635bff', letterSpacing: '-0.01em', fontSize: 13 }}>stripe</b>
                </span>
              </div>
            </div>
          )}


          {step === 4 && (
            <div>
              <SectionTitle n="05" title="Review & confirm" hint="A final look before we route the order to our team." />
              <div style={{ marginTop: 22, display: 'grid', gap: 14 }}>
                <ReviewRow label="Contact" onEdit={() => setStep(1)}>
                  <div>{form.firstName} {form.lastName}</div>
                  <div style={{ color: 'var(--color-text-muted)' }}>{form.email}</div>
                  {form.organization && <div style={{ color: 'var(--color-text-muted)' }}>{form.organization}</div>}
                </ReviewRow>
                <ReviewRow label="Ship to" onEdit={() => setStep(2)}>
                  <div>{form.address1}{form.address2 ? ', ' + form.address2 : ''}</div>
                  <div style={{ color: 'var(--color-text-muted)' }}>{form.city}, {form.region} {form.postal} · {form.country}</div>
                </ReviewRow>
                <ReviewRow label="Shipping" onEdit={() => setStep(2)}>
                  <div style={{ textTransform: 'capitalize' }}>{form.shipMethod === 'standard' ? 'Standard (2–3 days)' : form.shipMethod === 'express' ? 'Express shipping (next day)' : 'Standard ambient (5–7 days)'}</div>
                </ReviewRow>
                <ReviewRow label="Payment" onEdit={() => setStep(3)}>
                  <div>Card ending in {form.cardNumber.replace(/\s/g, '').slice(-4) || '····'}</div>
                  <div style={{ color: 'var(--color-text-muted)' }}>Exp {form.cardExp || '··/··'}</div>
                </ReviewRow>
              </div>

              <div style={{ marginTop: 26, display: 'grid', gap: 12 }}>
                <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, lineHeight: 1.6, color: 'var(--color-ink-strong)', cursor: 'pointer', padding: '14px 16px', border: '1px solid var(--color-accent)', background: 'var(--color-accent-soft, #FBEEF1)', borderRadius: 4, fontWeight: 600 }}>
                  <input type="checkbox" checked={form.fdaAck} onChange={upd('fdaAck')} style={{ marginTop: 3 }} />
                  <span>I understand these compounds are not FDA approved and for research purposes only.</span>
                </label>
                <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, lineHeight: 1.6, color: 'var(--color-text)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={form.researchAck} onChange={upd('researchAck')} style={{ marginTop: 3 }} />
                  <span>I confirm these compounds are being purchased for scientific research only, and will not be administered to humans or animals.</span>
                </label>
                <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, lineHeight: 1.6, color: 'var(--color-text)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={form.termsAck} onChange={upd('termsAck')} style={{ marginTop: 3 }} />
                  <span>I have read and agree to the Terms of Sale, Research Use Policy and Privacy Notice.</span>
                </label>
              </div>
            </div>
          )}

          {/* Nav */}
          <div style={{ marginTop: 32, display: 'flex', justifyContent: 'space-between', gap: 12, borderTop: '1px solid var(--color-border)', paddingTop: 22 }}>
            <button onClick={step === 1 ? () => onNav('compounds') : back} style={{ appearance: 'none', background: 'transparent', border: '1px solid var(--color-border)', color: 'var(--color-ink)', padding: '12px 22px', borderRadius: 4, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer' }}>
              {step === 1 ? '← Cart' : '← Back'}
            </button>
            {step < 4 ? (
              <button disabled={!stepValid[step]} onClick={next} style={{ appearance: 'none', border: '1px solid var(--color-ink-strong)', background: 'var(--color-ink-strong)', color: 'var(--color-on-ink,#fff)', padding: '12px 26px', borderRadius: 4, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: stepValid[step] ? 'pointer' : 'not-allowed', opacity: stepValid[step] ? 1 : 0.45 }}>
                Continue →
              </button>
            ) : (
              <button disabled={!stepValid[4] || placing} onClick={() => window.VC_ORDER && window.VC_ORDER.open()} style={{ appearance: 'none', border: '1px solid var(--color-accent)', background: 'var(--color-accent)', color: '#fff', padding: '12px 26px', borderRadius: 4, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: stepValid[4] && !placing ? 'pointer' : 'not-allowed', opacity: stepValid[4] && !placing ? 1 : 0.55, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                Ready to order
              </button>
            )}
          </div>
        </div>

        {/* RIGHT: order summary */}
        <aside style={{ position: 'sticky', top: 24, background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
          <header style={{ padding: '20px 22px 14px', borderBottom: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--color-accent)', marginBottom: 4 }}>Order summary</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--color-ink-strong)' }}>{items.length} {items.length === 1 ? 'item' : 'items'}</div>
            </div>
            <Badge tone="teal">Secure</Badge>
          </header>

          <div style={{ maxHeight: 340, overflowY: 'auto', padding: '4px 6px' }}>
            {items.map((it) => (
              <div key={it.name} style={{ display: 'grid', gridTemplateColumns: '46px 1fr auto', gap: 12, alignItems: 'center', padding: '12px 14px' }}>
                <div style={{ position: 'relative', width: 46, height: 46, borderRadius: 6, background: 'var(--color-surface-haze)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  <img src="../../assets/vitalcell-mark.svg" width="22" height="22" alt="" style={{ opacity: 0.72 }} />
                  <span style={{ position: 'absolute', top: -6, right: -6, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 999, background: 'var(--color-ink-strong)', color: '#fff', fontFamily: 'var(--font-mono, monospace)', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', border: '2px solid var(--color-surface)' }}>{it.qty || 1}</span>
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-ink-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.name}</div>
                  {it.catLabel && <div style={{ fontSize: 10.5, color: 'var(--color-text-muted)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 2 }}>{it.catLabel}</div>}
                </div>
                <div style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 13, fontWeight: 600, color: 'var(--color-ink-strong)' }}>{fmt((it.price || 0) * (it.qty || 1))}</div>
              </div>
            ))}
          </div>

          <div style={{ padding: '16px 22px', borderTop: '1px solid var(--color-border)', display: 'grid', gap: 6, fontSize: 13, color: 'var(--color-text)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Subtotal</span><span style={{ fontFamily: 'var(--font-mono, monospace)' }}>{fmt(subtotal)}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Shipping</span><span style={{ fontFamily: 'var(--font-mono, monospace)' }}>{fmt(shipping)}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Estimated tax</span><span style={{ fontFamily: 'var(--font-mono, monospace)' }}>{fmt(tax)}</span></div>
          </div>
          <div style={{ padding: '18px 22px 22px', borderTop: '1px solid var(--color-border)', background: 'var(--color-surface-haze)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: 'var(--color-ink-strong)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Total</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, color: 'var(--color-ink-strong)' }}>{fmt(total)}</div>
          </div>

          <div style={{ padding: '16px 22px 22px', display: 'grid', gap: 10, fontSize: 12, color: 'var(--color-text-muted)', lineHeight: 1.55 }}>
            <TrustLine icon="shield-check">CoA & lot manifest included with every shipment</TrustLine>
            <TrustLine icon="snowflake">Careful packaging with 72-hour thermal buffer</TrustLine>
            <TrustLine icon="rotate-ccw">Damaged or broken items replaced</TrustLine>
          </div>
        </aside>
      </div>
    </section>
  );
}

function SectionTitle({ n, title, hint }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.24em', color: 'var(--color-accent)' }}>{n}</span>
        <span style={{ flex: 1, height: 1, background: 'var(--color-border)' }} />
      </div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, textTransform: 'uppercase', letterSpacing: '0.03em', fontSize: 22, color: 'var(--color-ink-strong)', margin: '10px 0 4px' }}>{title}</h2>
      {hint && <p style={{ fontSize: 13, color: 'var(--color-text-muted)', margin: 0, lineHeight: 1.6 }}>{hint}</p>}
    </div>
  );
}

function ReviewRow({ label, children, onEdit }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '110px 1fr auto', gap: 14, alignItems: 'start', padding: '14px 16px', border: '1px solid var(--color-border)', borderRadius: 4 }}>
      <div style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--color-text-muted)', paddingTop: 2 }}>{label}</div>
      <div style={{ fontSize: 13.5, color: 'var(--color-ink-strong)', lineHeight: 1.55 }}>{children}</div>
      <button onClick={onEdit} style={{ appearance: 'none', background: 'transparent', border: 0, color: 'var(--color-accent)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer', fontWeight: 600 }}>Edit</button>
    </div>
  );
}

function TrustLine({ icon, children }) {
  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
      <i data-lucide={icon} style={{ width: 14, height: 14, color: 'var(--color-accent)', flex: '0 0 auto' }}></i>
      <span>{children}</span>
    </div>
  );
}

Object.assign(window, { Checkout });
