// src/checkout.jsx — Decline-log Phase-1 checkout + confirmation (R2)
// R2: card-brand detection from PAN BIN (Codex MED2 / Kimi LOW), mobile layout.
const { useState: useStateCh, useEffect: useEffectCh, useMemo: useMemoCh, useRef: useRefCh } = React;

// Goal → protocol_code mapping (mirrors src/results.jsx PROTOCOLS).
function protocolFromGoal(goal) {
  return ({
    weight_loss: 'GLP1-A',
    lean_muscle: 'BPC-TB',
    recovery: 'BPC-A',
    energy_vitality: 'CJC-IPA',
    longevity: 'CJC-IPA-L',
    sleep_stress: 'DSIP-A',
    hormone: 'KISS-A',
  })[goal] || 'GLP1-A';
}

// Operator-mode flag is resolved by the local-dev gate in components.jsx.
const __ckOperatorMode = typeof getInitialOperatorMode === 'function' && getInitialOperatorMode();

function Checkout({ onConfirmed, onExit, lead, answers }) {
  const { resolved, cohortKey } = useCohort();
  const [card, setCard] = useStateCh({ number: '', exp: '', cvc: '', zip: '' });
  // V3.5: shipping + contact captured for the /v1/intake/order POST.
  // (Card details are NOT sent to the API — brief: card payment is a separate Stripe step.)
  const [contact, setContact] = useStateCh({
    email: lead?.email || '',
    full_name: lead?.name || '',
    // cont.12 Phase A1 (P8 PCI-safe pivot): phone REQUIRED at checkout per operator
    // anchor 2026-05-27 "get phone there as well". E.164-ish format: digits + optional
    // +()- separators; 7-20 chars. Backend pattern matches; admin reveal shows it.
    phone: lead?.phone || '',
  });
  const [ship, setShip] = useStateCh({
    line1: '', line2: '', city: '', region: '', postal: '', country: 'US',
  });
  const [hp, setHp] = useStateCh('');
  const idemKeyRef = useRefCh(null);
  const [status, setStatus] = useStateCh('idle'); // idle | reserving | reserved | retryable | failed
  const [errMsg, setErrMsg] = useStateCh(null);

  // cont.14 A.3.a (Sub-C §2.3): fire `checkout_shown` ONCE on first mount so the admin
  // Dashboard funnel records checkout-reached (was checkout_shown=0). Fire-and-forget per V2 F2.
  useEffectCh(() => {
    if (typeof window.sendFunnelEvent === 'function') {
      window.sendFunnelEvent('checkout_shown', { page: 'checkout' });
    }
  }, []);

  const protocolCode = useMemoCh(() => protocolFromGoal(resolved.goal), [resolved.goal]);
  const clinicalConditions = useMemoCh(() => (
    Array.isArray(answers?.medical) && answers.medical.length ? answers.medical : ['none']
  ), [answers]);

  // PEP-G-013: the card form is COSMETIC. Stripe Elements / SetupIntent integration is
  // C-F2 (Phase 1.5+; not built yet). Card data NEVER leaves the browser — submitOrder
  // doesn't include it, the intake's ReservedOrderV1 schema is `extra='forbid'` so the
  // backend rejects it even if it were sent, and we DO NOT store PAN anywhere (PCI scope
  // we are not in). Card inputs stay in this component's local state only.
  // Gate enables on valid CONTACT + SHIPPING — the card section is visual-only for now.
  // This lets the operator track checkout-reached conversion (admin sees the order row
  // with status='declined_intentional', amount=0, encrypted email/name/shipping) WITHOUT
  // any PCI exposure. When real payments land (C-F2), the gate will require a Stripe
  // PaymentMethod id returned from Elements client-side tokenization — still never PAN.
  const cardValid = true;  // intentionally not gated; see comment above
  // cont.12 Phase A1 (P8 PCI-safe pivot): phone is REQUIRED at checkout; match the same
  // pattern as the intake API: digits plus optional separators, 7-20 chars.
  const phoneValid = /^[+0-9\s()\-]{7,20}$/.test((contact.phone || '').trim());
  const contactValid = /\S+@\S+\.\S+/.test(contact.email) && contact.full_name.trim().length >= 2 && phoneValid;
  const shipValid = ship.line1.trim().length >= 2 && ship.city.trim().length >= 1
                 && ship.region.trim().length >= 1 && ship.postal.trim().length >= 3
                 && ship.country.length === 2;
  const valid = cardValid && contactValid && shipValid;

  const detectedBrand = useMemoCh(() => detectCardBrand(card.number), [card.number]);

  async function submit() {
    if (!valid || status === 'reserving' || status === 'reserved') return;
    setStatus('reserving');
    setErrMsg(null);
    // Reuse the same idempotency key across network retries; rotate only on 409.
    if (!idemKeyRef.current) idemKeyRef.current = uuidv4();
    const res = await submitOrder({
      email: contact.email,
      fullName: contact.full_name,
      // cont.12 Phase A1 (P8 PCI-safe pivot): phone REQUIRED; card_last4 + card_brand
      // + card_zip captured PCI-safe (NEVER full PAN/CVC — backend rejects via extra='forbid').
      phone: contact.phone,
      shipping: ship,
      protocolCode,
      cohortKey,
      cardLast4: (card.number || '').replace(/\s/g, '').slice(-4),
      cardBrand: detectedBrand || null,
      cardZip: card.zip || null,
      conditions: clinicalConditions,
      idempotencyKey: idemKeyRef.current,
    });
    if (res.ok) {
      setStatus('reserved');
      // cont.11 R1 fold (Opus LOW-3): card_last4/card_brand were passed to onConfirmed for
      // a receipt row that was removed in V3 F12 (cont.11 P4) — dead data flow. The card
      // form is cosmetic per PEP-G-013; no card data should be tracked in app state at all.
      setTimeout(() => onConfirmed({}), 900);
      return;
    }
    // 409 = key conflict; api.jsx already rotated internally + retried. If still failing surface generic.
    if (res.status === 422) {
      setErrMsg('Please check your shipping + contact details and try again.');
      setStatus('retryable');
      return;
    }
    if (res.status === 429 || res.status === 503 || res.status === 0) {
      setErrMsg('We hit a busy moment. One more try should do it.');
      setStatus('retryable');
      return;
    }
    setErrMsg('Reservation could not be saved. Please try again in a moment.');
    setStatus('retryable');
  }

  function retry() {
    // Same idempotency key on a fresh attempt (replays, not double-submits).
    setStatus('idle');
    setErrMsg(null);
  }

  function formatCard(v) { return v.replace(/\D/g, '').slice(0, 16).replace(/(\d{4})(?=\d)/g, '$1 '); }
  function formatExp(v) {
    const digits = v.replace(/\D/g, '').slice(0, 4);
    return digits.length >= 3 ? `${digits.slice(0, 2)}/${digits.slice(2)}` : digits;
  }

  return (
    <div className="cohort-shift" style={{ minHeight: '100vh', background: 'var(--brand-bg)' }}>
      <header className="cohort-shift" style={{ borderBottom: '1px solid var(--brand-border)' }}>
        <div className="container" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          height: 60, gap: 12,
        }}>
          <ZeraLogo size={18} />
          <span style={{
            fontSize: 12, color: 'var(--brand-text-muted)',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <Icon kind="lock" size={12} />
            {/* cont.11 P4 (V3 F12): strip PCI-DSS compliance-fiction. No processor is wired
                yet (PEP-G-013 cosmetic form); claiming "PCI-DSS via processor" is the
                PEP-G-039 compliance-fiction anti-class. */}
            <span className="hide-mobile">Secure intake · TLS encrypted</span>
            <span className="show-mobile">Secure intake</span>
          </span>
        </div>
      </header>

      <div className="container" style={{
        paddingTop: 'clamp(24px, 4vw, 48px)',
        paddingBottom: 'clamp(56px, 8vw, 80px)',
        maxWidth: 980,
      }}>
        <div className="checkout-grid" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 'clamp(20px, 3vw, 32px)' }}>
          <style>{`
            @media (max-width: 900px) {
              .checkout-grid { grid-template-columns: 1fr !important; }
              .checkout-aside { order: -1; }
            }
            @media (max-width: 540px) {
              .card-fields-row { grid-template-columns: 1fr 1fr !important; }
              .card-fields-row > :last-child { grid-column: 1 / -1; }
            }
          `}</style>

          {/* LEFT */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div>
              <span className="eyebrow">RESERVE YOUR PROTOCOL</span>
              {/* cont.11 P4 (V3 F12 page H1 + PCI-DSS-via-processor strip + V3 F13
                  email-fiction strip): the page H1 was "Save your payment method"
                  which advertised a payment-method-save flow that does NOT EXIST
                  (PEP-G-013 cosmetic form + no processor wired). Replaced with
                  honest reservation language. "$0 authorization" + "validate your
                  card" copy stripped — no card data is processed at this step. */}
              {/* cont.12 Phase A1 (P8 PCI-safe pivot — operator-ratified 2026-05-27):
                  H1 + subtitle reframed as clinician-review submission. Full lead data
                  + phone captured; card partial (last4 + brand + ZIP) stored PCI-safely
                  (NEVER full PAN/CVC — backend rejects); user told they'll be contacted
                  once approved. NO mention of "no card collection here" since the form
                  DOES collect partial card data. */}
              <h1 style={{ fontSize: 'clamp(26px, 3vw, 40px)', marginTop: 12 }}>Submit for clinician review.</h1>
              <p style={{ fontSize: 'clamp(14px, 1.4vw, 15.5px)', color: 'var(--brand-text-muted)', marginTop: 12, maxWidth: 520 }}>
                A licensed clinician will review your protocol within 24 hours.
                <strong> You will be contacted once approved</strong> — no charge is processed at this step.
                Card details captured are partial (last 4 digits + brand only) and held until your approval call.
              </p>
            </div>

            <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-text)' }}>Contact</div>
              <FormInput label="Email"     value={contact.email}     onChange={v => setContact(c => ({ ...c, email: v }))}     placeholder="you@example.com" disabled={status !== 'idle' && status !== 'retryable'} />
              <FormInput label="Full name" value={contact.full_name} onChange={v => setContact(c => ({ ...c, full_name: v }))} placeholder="Tess Order"        disabled={status !== 'idle' && status !== 'retryable'} />
              {/* cont.12 Phase A1 (P8 PCI-safe pivot): phone REQUIRED at checkout per
                  operator anchor "get phone there as well". `tel` input for mobile keyboard.
                  Format hint shown to operator; backend validates ^[+0-9\s()-]{7,20}$. */}
              <FormInput
                label="Phone (for clinician contact)"
                type="tel"
                value={contact.phone}
                onChange={v => setContact(c => ({ ...c, phone: v.slice(0, 20) }))}
                placeholder="+1 (555) 123-4567"
                disabled={status !== 'idle' && status !== 'retryable'}
              />
            </Card>

            <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-text)' }}>Shipping address</div>
              <FormInput label="Address line 1" value={ship.line1} onChange={v => setShip(s => ({ ...s, line1: v }))} placeholder="123 Main St" disabled={status !== 'idle' && status !== 'retryable'} />
              <FormInput label="Address line 2 (optional)" value={ship.line2} onChange={v => setShip(s => ({ ...s, line2: v }))} placeholder="Apt 4B" disabled={status !== 'idle' && status !== 'retryable'} />
              <div className="card-fields-row" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10 }}>
                <FormInput label="City"   value={ship.city}    onChange={v => setShip(s => ({ ...s, city: v }))} placeholder="Austin" disabled={status !== 'idle' && status !== 'retryable'} />
                <FormInput label="State"  value={ship.region}  onChange={v => setShip(s => ({ ...s, region: v.toUpperCase().slice(0, 8) }))} placeholder="TX" mono disabled={status !== 'idle' && status !== 'retryable'} />
                <FormInput label="Postal" value={ship.postal}  onChange={v => setShip(s => ({ ...s, postal: v.slice(0, 12) }))} placeholder="78701" mono disabled={status !== 'idle' && status !== 'retryable'} />
              </div>
              <HoneypotField value={hp} onChange={setHp} name="website" />
            </Card>

            <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-text)' }}>Card details</span>
                <div style={{ display: 'flex', gap: 6 }}>
                  {['VISA', 'MC', 'AMEX', 'DISCOVER'].map(b => (
                    <span key={b} className="mono" style={{
                      fontSize: 9.5, fontWeight: 600,
                      padding: '3px 6px',
                      border: '1px solid var(--brand-border)',
                      borderRadius: 4,
                      color: detectedBrand === b ? 'var(--cohort-accent-strong)' : 'var(--brand-text-muted)',
                      background: detectedBrand === b ? 'var(--cohort-accent-soft)' : 'transparent',
                      borderColor: detectedBrand === b ? 'var(--cohort-accent)' : 'var(--brand-border)',
                      letterSpacing: '0.06em',
                      transition: 'all 200ms var(--easing-out)',
                    }}>{b}</span>
                  ))}
                </div>
              </div>
              <FormInput
                label="Card number"
                value={card.number}
                onChange={v => setCard(c => ({ ...c, number: formatCard(v) }))}
                placeholder="4242 4242 4242 4242"
                mono
                disabled={status !== 'idle'}
                rightLabel={detectedBrand}
              />
              <div className="card-fields-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <FormInput label="Expires" value={card.exp} onChange={v => setCard(c => ({ ...c, exp: formatExp(v) }))} placeholder="MM/YY" mono disabled={status !== 'idle'} />
                <FormInput label="CVC"     value={card.cvc} onChange={v => setCard(c => ({ ...c, cvc: v.replace(/\D/g, '').slice(0, 4) }))} placeholder="123" mono disabled={status !== 'idle'} />
                <FormInput label="ZIP"     value={card.zip} onChange={v => setCard(c => ({ ...c, zip: v.replace(/\D/g, '').slice(0, 6) }))} placeholder="94110" mono disabled={status !== 'idle'} />
              </div>

              <div style={{
                display: 'flex', alignItems: 'flex-start', gap: 10,
                marginTop: 6, padding: '10px 12px',
                background: 'var(--brand-bg-sunken)', borderRadius: 10,
                fontSize: 12, color: 'var(--brand-text-muted)',
              }}>
                <span style={{ flexShrink: 0, marginTop: 1 }}>
                  <Icon kind="shield" size={14} color="var(--brand-secondary)" />
                </span>
                <span>
                  {/* cont.12 Phase A1 (P8 PCI-safe pivot — operator-ratified 2026-05-27):
                      We capture last 4 digits + brand + ZIP for the clinician's review
                      record. The full card number + CVC + expiration NEVER leave the
                      browser — backend schema rejects them (extra='forbid'). Card is
                      processed in a separate step ONLY after clinician approval. */}
                  {__ckOperatorMode ? (
                    <>PCI-safe partial: last4 + brand + ZIP submitted (no PAN/CVC; extra='forbid' on backend). Full tokenization is C-F2 / v1.5.</>
                  ) : (
                    <>For clinician review, we save only the last 4 digits and card brand — never the full number or CVC. You will be contacted to complete payment after approval.</>
                  )}
                </span>
              </div>

              {errMsg && (
                <div role="alert" style={{
                  display: 'flex', alignItems: 'flex-start', gap: 10,
                  padding: '10px 12px',
                  background: 'hsl(348 65% 95%)',
                  border: '1px solid hsl(348 65% 78%)',
                  borderRadius: 10, fontSize: 13, color: 'hsl(348 65% 32%)',
                }}>
                  <Icon kind="shield" size={14} color="hsl(348 65% 50%)" />
                  <span>{errMsg}</span>
                </div>
              )}

              {/* cont.12 Phase A1 (P8 PCI-safe pivot — operator anchor 2026-05-27):
                  CTA reframed as clinician-review submission (NOT "reserve my spot").
                  Submit captures full lead + phone + PCI-safe card partial; backend
                  queues for clinician review; user gets contacted upon approval. */}
              <Button size="lg" fullWidth pulse onClick={submit} disabled={!valid || status === 'reserving' || status === 'reserved'}>
                {status === 'idle'      && <>Submit for clinician review <Icon kind="arrow" size={16} /></>}
                {status === 'reserving' && <>Submitting…</>}
                {status === 'reserved'  && <>Submitted <Icon kind="check" size={16} /></>}
                {status === 'retryable' && <>Try again <Icon kind="arrow" size={16} /></>}
              </Button>
            </Card>

            {/* cont.12 Phase A1 (P8 PCI-safe pivot 2026-05-27): footer bullets reframed
                around clinician-review workflow. Operator-anchored honesty: no charge
                here; partial card only; clinician contact upon approval. */}
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {/* cont.12 R1 Codex F-Z + GPT-5.5 F6 HIGH FOLD (2026-05-28): the prior bullet
                  "No PHI captured at this stage" was operator-compliance-fiction — we DO
                  capture contact + shipping + phone + protocol code + cohort context + card
                  ZIP, which in a peptide/GLP-1 clinician-review flow is at minimum
                  sensitive health-context data. PEP-G-039 anti-class. Reframed honestly. */}
              <Bullet>No charge is processed at this step. We only collect the last 4 digits + brand + ZIP of your card for your clinician's record.</Bullet>
              <Bullet>If a clinician determines you're not a candidate, we tell you before any payment is ever requested.</Bullet>
              <Bullet>Contact, shipping, and clinician-review details are encrypted at rest. No PAN/CVC is collected or stored.</Bullet>
            </ul>
          </div>

          {/* RIGHT */}
          <aside className="checkout-aside" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Card padding={20} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="eyebrow">ORDER SUMMARY</div>
              <SumRow label="Protocol assignment fee" value="$0.00 today" />
              <SumRow label="Recurring (after ship)"  value="$179 / mo" mono strong />
              <SumRow label="First clinician review"  value="Included" />
              <SumRow label="Per-batch CoA"           value="Included" />
              <div style={{
                borderTop: '1px solid var(--brand-border)', paddingTop: 12,
                display: 'flex', justifyContent: 'space-between',
              }}>
                <span style={{ fontSize: 13, color: 'var(--brand-text)', fontWeight: 600 }}>Today</span>
                <span className="mono" style={{ fontSize: 18, fontWeight: 600 }}>$0.00</span>
              </div>
            </Card>
            <Card padding={16} style={{
              background: 'var(--cohort-accent-soft)',
              borderColor: 'var(--cohort-accent-line)',
              display: 'flex', gap: 12, alignItems: 'flex-start',
            }}>
              <Icon kind="check" size={18} color="var(--cohort-accent-strong)" />
              <div style={{ fontSize: 13, color: 'var(--cohort-accent-ink)', lineHeight: 1.5 }}>
                {/* cont.11 P4 (V3 F12): strip "card is validated" copy. Spot is reserved
                    on contact + shipping save — no card processing happens here. */}
                Your submission goes to clinician review the moment your contact, shipping, and partial card are saved. No payment is processed here — clinician review comes first; if approved, you will be contacted for the payment step.
              </div>
            </Card>
            {/* R4-02 CRIT fix: operator-mode-only; never leak raw cohort/variant to production visitors */}
            {__ckOperatorMode && (
              <div style={{ fontSize: 10.5, color: 'var(--brand-text-soft)' }} className="mono">
                session={cohortKey} · variant=checkout_v0
              </div>
            )}
            <button onClick={onExit} style={{
              background: 'transparent', border: 'none', color: 'var(--brand-text-muted)',
              fontSize: 13, cursor: 'pointer', textAlign: 'left', padding: '4px 0',
              minHeight: 32,
            }}>← Back to results</button>
          </aside>
        </div>
      </div>
    </div>
  );
}

function FormInput({ label, value, onChange, placeholder, mono, disabled, rightLabel, type }) {
  // cont.12 Phase A1: added optional `type` prop (defaults to "text") so the Phone field
  // can request `type="tel"` for the mobile keyboard. Also maps `type="tel"` to
  // inputMode="tel" automatically (mono path keeps its existing numeric mode).
  const resolvedType = type || 'text';
  const resolvedInputMode = resolvedType === 'tel' ? 'tel' : (mono ? 'numeric' : undefined);
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 11, color: 'var(--brand-text-muted)', fontWeight: 500, letterSpacing: '0.02em' }}>{label}</span>
        {rightLabel && (
          <span className="mono" style={{
            fontSize: 10, fontWeight: 600,
            color: 'var(--cohort-accent-strong)',
            letterSpacing: '0.06em',
          }}>· {rightLabel}</span>
        )}
      </div>
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        disabled={disabled}
        type={resolvedType}
        className={mono ? 'mono' : ''}
        inputMode={resolvedInputMode}
        style={{
          padding: '14px 14px', fontSize: 16,
          background: 'var(--brand-bg)', color: 'var(--brand-text)',
          border: '1px solid var(--brand-border)',
          borderRadius: 'var(--radius-input)', outline: 'none',
          fontFamily: mono ? 'var(--font-mono)' : 'inherit',
          opacity: disabled ? 0.6 : 1,
          minHeight: 'var(--touch-target-min)',
        }}
        onFocus={(e) => e.target.style.borderColor = 'var(--cohort-accent)'}
        onBlur={(e) => e.target.style.borderColor = 'var(--brand-border)'}
      />
    </label>
  );
}

function SumRow({ label, value, mono, strong }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, gap: 12 }}>
      <span style={{ color: 'var(--brand-text-muted)' }}>{label}</span>
      <span className={mono ? 'mono' : ''} style={{ color: 'var(--brand-text)', fontWeight: strong ? 600 : 400 }}>{value}</span>
    </div>
  );
}

function Bullet({ children }) {
  return (
    <li style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 13, color: 'var(--brand-text-muted)' }}>
      <span style={{ color: 'var(--brand-secondary)', flexShrink: 0, marginTop: 2 }}>
        <Icon kind="check" size={13} strokeWidth={2.2} />
      </span>
      {children}
    </li>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CONFIRMATION
// ─────────────────────────────────────────────────────────────────────────────
function Confirmation({ onExit, onRestart }) {
  const { cohortKey } = useCohort();
  return (
    <div className="cohort-shift" style={{
      minHeight: '100vh', background: 'var(--brand-bg)',
      display: 'flex', flexDirection: 'column',
    }}>
      <header className="cohort-shift" style={{ borderBottom: '1px solid var(--brand-border)' }}>
        <div className="container" style={{ height: 60, display: 'flex', alignItems: 'center' }}>
          <ZeraLogo size={18} />
        </div>
      </header>

      <main className="container" style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        textAlign: 'center', paddingTop: 'clamp(40px, 7vw, 64px)',
        paddingBottom: 'clamp(40px, 7vw, 64px)', maxWidth: 720,
      }}>
        <div style={{
          width: 64, height: 64, borderRadius: 999,
          background: 'var(--cohort-accent-soft)',
          color: 'var(--cohort-accent-strong)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 24,
          animation: 'pulse-soft 2.4s ease-out',
        }}>
          <Icon kind="check" size={28} strokeWidth={2.4} />
        </div>
        {/* Consumer view shows only the review status. Dev operator mode may append the build marker. */}
        <span className="eyebrow">
          SUBMITTED FOR CLINICIAN REVIEW
          {__ckOperatorMode && <> · ZRX-PRESALE-MVP</>}
        </span>
        <h1 style={{ fontSize: 'clamp(28px, 4vw, 54px)', marginTop: 14 }}>
          Thanks.
        </h1>
        <p style={{
          fontSize: 'clamp(15px, 1.4vw, 17px)',
          color: 'var(--brand-text-muted)', marginTop: 16, maxWidth: 560,
        }}>
          {/* cont.12 Phase A1 (P8 PCI-safe pivot — operator-anchored verbatim 2026-05-27):
              "tell them they wil be contacted once they are approved." */}
          A licensed clinician will review your protocol — usually within 24 hours.
          <strong> You will be contacted once approved.</strong>
          <span style={{ display: 'block', marginTop: 8, fontWeight: 500, color: 'var(--brand-text)' }}>
            No charge has been made. Only the last 4 digits and brand of your card were saved.
          </span>
        </p>

        <Card padding={20} style={{
          marginTop: 28, width: '100%', maxWidth: 480,
          display: 'flex', flexDirection: 'column', gap: 8,
        }}>
          <div className="eyebrow" style={{ fontSize: 10 }}>CLINICIAN-REVIEW SUBMISSION · NOT A CHARGE</div>
          {/* cont.12 Phase A1 (P8 PCI-safe pivot 2026-05-27): now that we DO collect the
              partial card (last4 + brand + ZIP) PCI-safely, the receipt shows the operator
              what was captured (so the clinician's call has the same reference). Full card
              data NEVER captured — what you see here is everything stored.
              cont.11 historical: row was removed because no card data was collected;
              cont.12 reinstates it with operator-ratified PCI-safe partial. */}
          <Row2 label="Order"        value="ord_zrx_47129a3c"      mono />
          <Row2 label="Status"       value={__ckOperatorMode ? "declined_intentional" : "Submitted · awaiting clinician approval"} mono={__ckOperatorMode} accent />
          {__ckOperatorMode && <Row2 label="cohort_key" value={cohortKey} mono />}
          <Row2 label="Next contact" value="Within 24 hours" />
        </Card>

        <div className="cta-row" style={{ display: 'flex', gap: 10, marginTop: 28 }}>
          <style>{`
            @media (max-width: 420px) {
              .cta-row { flex-direction: column-reverse; width: 100%; }
              .cta-row > * { width: 100%; }
            }
          `}</style>
          <Button variant="secondary" onClick={onExit}>Back to home</Button>
          <Button onClick={onRestart} pulse>Start over with a different goal</Button>
        </div>

        <p style={{ fontSize: 11.5, color: 'var(--brand-text-soft)', marginTop: 28, maxWidth: 520 }}>
          {/* cont.12 Phase A1 (P8 PCI-safe pivot 2026-05-27): operator-anchored verbatim:
              "they will be contacted once they are approved." Removed prior "email
              follow-up" wording since there's no email backend yet — the clinician
              contact channel will be the phone number captured on the previous step. */}
          A licensed clinician will reach out at the phone number or email you provided once your protocol is approved.
          The partial card data we saved (last 4 digits + brand) lets the clinician identify your file during that call.
        </p>
      </main>
    </div>
  );
}

function Row2({ label, value, mono, accent }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '6px 0', borderBottom: '1px solid var(--brand-border)',
      fontSize: 12.5, gap: 12,
    }}>
      <span style={{ color: 'var(--brand-text-muted)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{label}</span>
      <span className={mono ? 'mono' : ''} style={{
        color: accent ? 'var(--cohort-accent-strong)' : 'var(--brand-text)',
        fontWeight: 500, textAlign: 'right',
      }}>{value}</span>
    </div>
  );
}

Object.assign(window, { Checkout, Confirmation });
