// funnel.jsx — Results → PDP → Cart handoff

const { useState, useEffect } = React;

// ════════════════════════════════════════════════════════════════════════════
//  RESULTS PAGE
// ════════════════════════════════════════════════════════════════════════════
function Results({ go, answers }) {
  const rec = recommendFromAnswers(answers || {});
  const product = CATALOG[rec.primary];
  const discount = useDiscount();

  // Doctor-reviewed loader
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const t = setTimeout(() => setLoading(false), 1900);
    return () => clearTimeout(t);
  }, []);

  // Save the quiz session to the Cloudflare Worker so a prescriber can
  // fetch the full context after checkout. Fire once, on results render.
  useEffect(() => {
    if (!answers || Object.keys(answers).length === 0) return;
    // Clear any stale session from a previous quiz run
    clearStoredSessionId();
    saveQuizSession({
      answers,
      recommendation: {
        primary: rec.primary,
        primaryDose: rec.primaryDose,
        alternates: rec.alternates,
        flags: rec.flags,
      },
      discount: discount ? { code: discount.code, amount: discount.amount } : null,
    });
  }, []); // eslint-disable-line

  if (loading) return <ResultsLoading />;

  return (
    <main className="page-enter" style={{ minHeight: '100vh' }}>
      <ResultsHeader go={go} />
      <ResultsHero rec={rec} product={product} answers={answers} go={go} />
      <WhyThisFitsYou rec={rec} answers={answers} />
      <BundleCrossSell rec={rec} go={go} />
      <ResultsAlternates rec={rec} go={go} />
      <ResultsTrust />
      <SiteFooter />
    </main>
  );
}

// ════════════════════════════════════════════════════════════════════════════
//  WhyThisFitsYou — pulls quotes from the user's quiz answers
// ════════════════════════════════════════════════════════════════════════════
function WhyThisFitsYou({ rec, answers }) {
  const a = answers || {};
  const rows = [];

  // Map quiz answers → human readable reasons
  const concernLabel = {
    ed:     'Erectile difficulties',
    pe:     'Premature ejaculation',
    both:   'Both ED and PE',
    desire: 'Low desire / arousal',
  }[a.concern];
  if (concernLabel) {
    rows.push({
      q: 'You told us about',
      a: concernLabel,
      why: rec.primary === 'fits' ? 'FITS covers all three in one tablet.'
         : rec.primary === 'sertraline' ? 'Sertraline is the gold standard for PE.'
         : rec.primary === 'tadalafil' ? 'Tadalafil restores reliable function.'
         : 'Sildenafil restores reliable function on-demand.',
    });
  }

  const lifestyleLabel = {
    planned:     "Planned, 30–60 minutes ahead",
    spontaneous: "Spontaneous — ready anytime",
    both:        "A mix of planned and spontaneous",
  }[a.lifestyle];
  if (lifestyleLabel && (rec.primary === 'sildenafil' || rec.primary === 'tadalafil')) {
    rows.push({
      q: 'Your lifestyle',
      a: lifestyleLabel,
      why: rec.primary === 'tadalafil'
        ? 'Daily tadalafil keeps you ready 24/7 without timing your night.'
        : 'Sildenafil 50–100mg is the most predictable on-demand option.',
    });
  }

  const freqLabel = {
    rarely:    'A handful of times',
    sometimes: 'Once or twice a month',
    often:     'Most weeks',
    always:    'Nearly every time',
  }[a.frequency];
  if (freqLabel) {
    rows.push({
      q: 'How often you feel it',
      a: freqLabel,
      why: rec.primaryDose
        ? `We calibrated this to ${rec.primaryDose}mg based on the frequency and history you shared.`
        : 'The exact dose will be calibrated to match your answers.',
    });
  }

  const histLabel = {
    no:          "Hasn't tried ED meds before",
    yes_worked:  "Tried before — it worked well",
    yes_partial: "Tried before — helped, but not enough",
    yes_didnt:   "Tried before — didn't work",
  }[a.history];
  if (histLabel && a.history && a.history !== 'no') {
    rows.push({
      q: 'Your history',
      a: histLabel,
      why: a.history === 'yes_partial'
        ? 'We bumped your dose up to compensate.'
        : a.history === 'yes_didnt'
        ? "We're starting you on a different molecule entirely."
        : 'We continued the molecule that worked for you.',
    });
  }

  if (!rows.length) return null;

  return (
    <section style={{ padding: '40px 0 30px' }}>
      <div className="container">
        <div style={{
          background: 'var(--surface)',
          border: '1px solid var(--line)',
          borderRadius: 'var(--r-xl)',
          padding: 36,
        }}>
          <Eyebrow>Why this fits you</Eyebrow>
          <h3 style={{ fontSize: 28, marginTop: 12, lineHeight: 1.15 }}>
            We didn't pick this <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>at random</em>.
          </h3>
          <p style={{ marginTop: 6, color: 'var(--ink-dim)', fontSize: 14, maxWidth: 600 }}>
            Here's exactly how each answer you gave shaped our recommendation.
          </p>

          <div style={{ marginTop: 26, display: 'grid', gap: 0 }}>
            {rows.map((r, i) => (
              <div key={i} className="why-fits-row" style={{
                display: 'grid', gridTemplateColumns: '180px 1.3fr 1.4fr', gap: 24,
                padding: '18px 0',
                borderTop: i === 0 ? '1px solid var(--line)' : 'none',
                borderBottom: '1px solid var(--line)',
                alignItems: 'baseline',
              }}>
                <div style={{
                  fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase',
                  color: 'var(--ink-mute)',
                }}>{r.q}</div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 18, fontStyle: 'italic', color: 'var(--ink)' }}>
                  "{r.a}"
                </div>
                <div style={{ fontSize: 13.5, color: 'var(--ink-dim)', lineHeight: 1.55 }}>
                  → {r.why}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ════════════════════════════════════════════════════════════════════════════
//  BundleCrossSell — recommend a complementary product
// ════════════════════════════════════════════════════════════════════════════
function BundleCrossSell({ rec, go }) {
  const bundle = bundleForPrimary(rec.primary);
  if (!bundle) return null;
  const partner = CATALOG[bundle.partner];
  if (!partner) return null;

  return (
    <section style={{ padding: '30px 0 60px' }}>
      <div className="container">
        <div className="bundle-card" style={{
          background: 'linear-gradient(180deg, var(--surface) 0%, var(--surface-2) 100%)',
          border: '1px dashed var(--line-strong)',
          borderRadius: 'var(--r-xl)',
          padding: 32,
          display: 'grid', gridTemplateColumns: '90px 1fr auto', gap: 28,
          alignItems: 'center',
        }}>
          <div style={{ display: 'grid', placeItems: 'center' }}>
            <PillArt kind={partner.pill} size={80} />
          </div>
          <div>
            <div style={{
              fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase',
              color: 'var(--accent)',
            }}>{bundle.eyebrow}</div>
            <h3 style={{ fontSize: 26, marginTop: 6, lineHeight: 1.2 }}>
              {bundle.headline}
            </h3>
            <p style={{ marginTop: 8, color: 'var(--ink-dim)', fontSize: 14.5, lineHeight: 1.55, maxWidth: 540 }}>
              {bundle.body}
            </p>
          </div>
          <button onClick={() => go('pdp', { productId: partner.id })}
                  style={{ ...btn.outline, padding: '12px 18px', whiteSpace: 'nowrap' }}>
            Add {partner.name} →
          </button>
        </div>
      </div>
    </section>
  );
}

function bundleForPrimary(primary) {
  if (primary === 'sildenafil') return {
    partner: 'tadalafil',
    eyebrow: 'Many members add',
    headline: 'Tadalafil daily, for the unplanned nights.',
    body: 'A low-dose tadalafil daily keeps you ready when intimacy isn\'t scheduled — pair it with Sildenafil for the big occasions.',
  };
  if (primary === 'tadalafil') return {
    partner: 'sildenafil',
    eyebrow: 'Many members add',
    headline: 'Sildenafil 100mg, for the big nights.',
    body: 'Even on daily tadalafil, a few sildenafil tablets in the drawer give you extra firmness when it matters most.',
  };
  if (primary === 'fits') return {
    partner: 'sildenafil',
    eyebrow: 'Some members add',
    headline: 'Sildenafil 100mg, as a backup.',
    body: 'FITS handles your day-to-day, but having on-demand sildenafil on hand for those high-stakes moments is wise.',
  };
  if (primary === 'sertraline') return {
    partner: 'fits',
    eyebrow: 'Coming soon — pair with',
    headline: 'FITS 3-in-1, when it drops this week.',
    body: 'Sertraline takes 2–3 weeks to kick in. FITS pairs PE control with ED + arousal in one daily tablet — ready when you are.',
  };
  return null;
}

function ResultsHeader({ go }) {
  return (
    <header style={{
      padding: '24px 0', borderBottom: '1px solid var(--line)',
    }}>
      <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <a href="/" onClick={(e) => { e.preventDefault(); go('landing'); }}
           style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none', color: 'inherit', cursor: 'pointer' }}
           aria-label="HermanRx home">
          <HermanLogo size={22} />
        </a>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '8px 14px', borderRadius: 999,
          background: 'var(--surface)', border: '1px solid var(--line)',
          fontSize: 12.5, color: 'var(--ink-dim)',
        }}>
          <div style={{
            width: 8, height: 8, borderRadius: 8, background: 'var(--good)',
            boxShadow: '0 0 0 4px color-mix(in oklab, var(--good) 22%, transparent)',
          }} />
          Personalized in seconds
        </div>
      </div>
    </header>
  );
}

function ResultsLoading() {
  const steps = [
    'Reading your answers',
    'Matching to our formulary',
    'Checking dose options',
    'Building your recommendation',
  ];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => Math.min(i + 1, steps.length - 1)), 460);
    return () => clearInterval(t);
  }, []);
  return (
    <main style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 24 }}>
      <div style={{ maxWidth: 460, width: '100%' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 56,
            border: '2px solid var(--line)',
            borderTopColor: 'var(--accent)',
            margin: '0 auto',
            animation: 'spin 1s linear infinite',
          }} />
          <h2 style={{ fontFamily: 'var(--serif)', fontSize: 36, marginTop: 30, lineHeight: 1.15 }}>
            Matching you with
            <br/>
            <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>the right treatment.</em>
          </h2>
        </div>
        <div style={{ marginTop: 40, display: 'grid', gap: 14 }}>
          {steps.map((s, i) => (
            <div key={s} style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 18px',
              background: 'var(--surface)',
              border: '1px solid var(--line)',
              borderRadius: 'var(--r-md)',
              opacity: i <= idx ? 1 : 0.4,
              transition: 'opacity .3s ease',
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: 22, flexShrink: 0,
                background: i < idx ? 'var(--accent)' : 'var(--surface-2)',
                border: '1.5px solid',
                borderColor: i <= idx ? 'var(--accent)' : 'var(--line-strong)',
                display: 'grid', placeItems: 'center',
              }}>
                {i < idx && (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--cta-ink)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M4 12l5 5L20 6"/>
                  </svg>
                )}
                {i === idx && (
                  <div style={{ width: 8, height: 8, borderRadius: 8, background: 'var(--accent)', animation: 'pulse 1.2s ease-in-out infinite' }} />
                )}
              </div>
              <div style={{ fontSize: 14, color: 'var(--ink)' }}>{s}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(.5); opacity: .5; } }
      `}</style>
    </main>
  );
}

function ResultsHero({ rec, product, go }) {
  return (
    <section style={{
      padding: '64px 0 80px',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse 600px 320px at 70% 30%, color-mix(in oklab, var(--brand-yellow) 55%, transparent), transparent 70%)',
        pointerEvents: 'none',
      }} />
      <div className="container" style={{ position: 'relative' }}>
        <Eyebrow>Your personalized recommendation</Eyebrow>
        <div className="results-grid" style={{
          marginTop: 24,
          display: 'grid', gridTemplateColumns: '1fr 320px', gap: 56,
          alignItems: 'flex-start',
        }}>
          <div>
            <h1 style={{
              fontSize: 'clamp(40px, 5vw, 64px)', lineHeight: 1.1,
            }}>
              Based on your answers,
              <br/>
              we recommend
              <br/>
              <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>
                {product.name}{rec.primaryDose ? ` ${rec.primaryDose}mg` : ''}
              </em>.
            </h1>
            <p style={{
              marginTop: 24, fontSize: 17, lineHeight: 1.6, color: 'var(--ink-dim)',
              maxWidth: 600,
            }}>
              {rec.reasoning}
            </p>

            {rec.flags?.length > 0 && (
              <div style={{
                marginTop: 24, padding: '14px 18px',
                background: 'color-mix(in oklab, var(--accent) 8%, var(--surface))',
                border: '1px solid color-mix(in oklab, var(--accent) 26%, var(--line))',
                borderRadius: 'var(--r-md)',
                display: 'grid', gap: 8,
              }}>
                <div style={{
                  fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase',
                  color: 'var(--accent)',
                }}>Important to flag</div>
                {rec.flags.map((f, i) => (
                  <div key={i} style={{ fontSize: 13.5, color: 'var(--ink-dim)', lineHeight: 1.5 }}>• {f}</div>
                ))}
              </div>
            )}

            <button onClick={() => go('pdp', { productId: rec.primary, dose: rec.primaryDose })}
                    style={{ ...btn.big, marginTop: 36 }}>
              See your treatment plans
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></svg>
            </button>
            <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--ink-mute)' }}>
              Free 2-day shipping · Reviewed by a U.S. physician · Refunded if not approved
            </div>
          </div>
          <div className="results-card" style={{
            background: 'var(--surface)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-xl)',
            padding: 32,
            display: 'grid', placeItems: 'center',
            boxShadow: 'var(--shadow-lg)',
          }}>
            <div style={{
              fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase',
              color: 'var(--ink-mute)', alignSelf: 'flex-start',
            }}>{product.indication}</div>
            <div style={{ marginTop: 12 }}>
              <PillArt kind={product.pill} size={200} />
            </div>
            <div style={{
              fontFamily: 'var(--serif)', fontSize: 32, marginTop: 16,
              textAlign: 'center',
            }}>
              {product.name}
              {rec.primaryDose && <span style={{ color: 'var(--ink-mute)', fontSize: 22 }}> {rec.primaryDose}mg</span>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ResultsAlternates({ rec, go }) {
  return (
    <section style={{
      padding: '80px 0',
      background: 'var(--bg-elev)',
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
    }}>
      <div className="container">
        <div style={{ marginBottom: 36, maxWidth: 640 }}>
          <Eyebrow>Other options to consider</Eyebrow>
          <h3 style={{ fontSize: 32, marginTop: 12, lineHeight: 1.1 }}>
            Not feeling this one? <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>Here are alternatives.</em>
          </h3>
        </div>
        <div className="alternates-grid" style={{
          display: 'grid', gridTemplateColumns: `repeat(${rec.alternates.length}, 1fr)`, gap: 18,
        }}>
          {rec.alternates.map(id => {
            const p = CATALOG[id];
            if (!p) return null;
            const cheapest = Math.round(fromPricePerMonth(id));
            return (
              <button key={id} onClick={() => go('pdp', { productId: id })}
                      style={{
                        all: 'unset', cursor: 'pointer',
                        display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 20,
                        alignItems: 'center',
                        padding: 22,
                        background: 'var(--surface)',
                        border: '1px solid var(--line)',
                        borderRadius: 'var(--r-lg)',
                        transition: 'border-color .2s ease, transform .2s ease',
                      }}
                      onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--line-strong)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.transform = ''; }}>
                <PillArt kind={p.pill} size={70} />
                <div>
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 22 }}>{p.name}</div>
                  <div style={{ marginTop: 4, fontSize: 12.5, color: 'var(--ink-dim)', lineHeight: 1.5 }}>{p.tagline}</div>
                  <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-mute)', display: 'flex', alignItems: 'center', gap: 6 }}>
                    From <span style={{ color: 'var(--ink)', fontWeight: 500 }}>${cheapest}/mo</span>
                  </div>
                </div>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></svg>
              </button>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function ResultsTrust() {
  return (
    <section style={{ padding: '80px 0' }}>
      <div className="container">
        <div className="results-trust" style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24,
          textAlign: 'center',
        }}>
          {[
            { ic: 'rx',     h: 'FDA-approved generics' },
            { ic: 'doctor', h: 'Free physician consult' },
            { ic: 'box',    h: 'Discreet shipping' },
            { ic: 'lock',   h: 'Cancel any time' },
          ].map(it => (
            <div key={it.h} style={{
              padding: 26, border: '1px solid var(--line)',
              borderRadius: 'var(--r-md)', background: 'var(--surface)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
            }}>
              <TrustIcon name={it.ic} size={24} />
              <div style={{ fontSize: 14, fontWeight: 500 }}>{it.h}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ════════════════════════════════════════════════════════════════════════════
//  PDP — Product Detail Page with pricing tiers
// ════════════════════════════════════════════════════════════════════════════
function PDP({ go, productId, dose, mode: modeInit, qty: qtyInit, duration: durationInit }) {
  const product = CATALOG[productId] || CATALOG.sildenafil;
  const discount = useDiscount();

  const [mode, setMode] = useState(() => {
    if (product.kind !== 'mixed') return null;
    return modeInit || 'daily';
  });
  const modeObj = product.kind === 'mixed' ? product.modes.find(m => m.id === mode) : null;
  const availableDoses = product.kind === 'mixed' ? modeObj.doses : (product.doses || []);
  const availableQtys  = product.kind === 'mixed' ? modeObj.qtys  : (product.qtys  || []);
  const skuTree        = product.kind === 'mixed' ? modeObj.skus  : product.skus;

  const [selectedDose, setSelectedDose] = useState(() => {
    if (dose && availableDoses.find(d => d.mg === dose)) return dose;
    return availableDoses[0]?.mg ?? null;
  });
  const [selectedQty, setSelectedQty] = useState(() => qtyInit || availableQtys[Math.floor(availableQtys.length / 2)] || 30);
  const [selectedDuration, setSelectedDuration] = useState(() => durationInit || 3);

  useEffect(() => {
    if (product.kind === 'mixed' && modeObj) {
      if (!modeObj.doses.find(d => d.mg === selectedDose)) {
        setSelectedDose(modeObj.doses[0].mg);
      }
      if (!modeObj.qtys.includes(selectedQty)) {
        setSelectedQty(modeObj.qtys[Math.floor(modeObj.qtys.length / 2)]);
      }
    }
  }, [mode]);

  const planEntries = product.durations.map(d => {
    let total, sku, url;
    if (product.kind === 'on-demand' || product.kind === 'mixed') {
      const entry = skuTree?.[selectedDose]?.[selectedQty]?.[d];
      total = entry?.total;
      sku   = entry?.sku;
      url   = entry ? CHECKOUT_BASE + entry.id : null;
    } else if (product.kind === 'coming-soon' || product.kind === 'placeholder') {
      const ph = product.placeholderPlans.find(p => p.duration === d);
      total = ph?.total;
    }
    return {
      duration: d,
      label: product.durationLabels[d],
      badge: product.durationBadges[d],
      total,
      perMonth: total ? total / d : null,
      url,
      sku,
    };
  }).filter(p => p.total != null);

  const plan = planEntries.find(p => p.duration === selectedDuration) || planEntries[0];
  const onemonth = planEntries.find(p => p.duration === 1);
  const baseMonth = onemonth?.perMonth ?? plan.perMonth;
  const savePerMo = Math.max(0, baseMonth - plan.perMonth);
  const savingsTotal = Math.round(savePerMo * plan.duration);
  const discountAmount = discount && plan.total > discount.amount ? discount.amount : 0;
  const finalTotal = Math.max(0, plan.total - discountAmount);

  // Find the real sticky.io URL for the current selection
  const checkoutUrl = plan?.url || null;
  const sessionId = useStoredSessionId();

  // Build the in-place redirect target. Append:
  //   - session=<id>             → so sticky.io / prescriber backend can fetch the quiz
  //   - <every-common-coupon-key>=<code> → so sticky.io applies the discount regardless
  //                                        of which URL param key their config expects
  const finalCheckoutUrl = (() => {
    if (!checkoutUrl) return null;
    const params = [];
    if (sessionId) params.push(`session=${encodeURIComponent(sessionId)}`);
    if (discount) params.push(buildCouponSuffix(discount.code));
    return params.length ? `${checkoutUrl}&${params.join('&')}` : checkoutUrl;
  })();

  const goCheckout = () => {
    if (!finalCheckoutUrl) return;
    window.location.href = finalCheckoutUrl;
  };

  const pillsPerMonth = product.kind === 'mixed' || product.kind === 'on-demand'
    ? selectedQty
    : (product.placeholderPlans?.[0]?.pillsPerMonth ?? 30);

  const qtyGridCols = availableQtys && availableQtys.length > 1 ? `repeat(${availableQtys.length}, 1fr)` : '1fr';

  return (
    <main className="page-enter">
      <ResultsHeader go={go} />
      <section style={{ padding: '48px 0 80px' }}>
        <div className="container">
          <button onClick={() => go('results')} style={{ ...btn.ghost, padding: '6px 0', marginBottom: 28 }}>
            ← Back to recommendation
          </button>

          <div className="pdp-grid" style={{
            display: 'grid', gridTemplateColumns: '1fr 1.05fr', gap: 64,
            alignItems: 'flex-start',
          }}>
            <PDPGallery product={product} />

            <div>
              <div style={{
                fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase',
                color: 'var(--accent)',
              }}>{product.indication}</div>
              <h1 style={{ fontSize: 'clamp(40px, 4.8vw, 60px)', marginTop: 12, lineHeight: 1.1 }}>
                {product.name}
              </h1>
              <p style={{
                marginTop: 10, color: 'var(--accent)', fontStyle: 'italic',
                fontFamily: 'var(--serif)', fontSize: 22,
              }}>{product.tagline}</p>
              <p style={{ marginTop: 18, color: 'var(--ink-dim)', fontSize: 15.5, lineHeight: 1.6, maxWidth: 540 }}>
                {product.description}
              </p>

              {product.kind === 'mixed' && (
                <div style={{ marginTop: 28 }}>
                  <Label>How you'll take it</Label>
                  <div style={{
                    display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8,
                    padding: 4, background: 'var(--surface-2)',
                    border: '1px solid var(--line)', borderRadius: 999,
                  }}>
                    {product.modes.map(m => {
                      const sel = mode === m.id;
                      return (
                        <button key={m.id} onClick={() => setMode(m.id)}
                                style={{
                                  all: 'unset', cursor: 'pointer', textAlign: 'center',
                                  padding: '10px 14px',
                                  background: sel ? 'var(--surface)' : 'transparent',
                                  border: '1px solid',
                                  borderColor: sel ? 'var(--line-strong)' : 'transparent',
                                  borderRadius: 999,
                                  fontSize: 13, fontWeight: sel ? 500 : 400,
                                  color: sel ? 'var(--ink)' : 'var(--ink-dim)',
                                  transition: 'all .15s ease',
                                }}>
                          {m.id === 'daily' ? 'Daily low-dose' : 'On-demand (10–20mg)'}
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              {availableDoses?.length > 1 && (
                <div style={{ marginTop: 28 }}>
                  <Label>Dose</Label>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {availableDoses.map(d => (
                      <button key={d.mg} onClick={() => setSelectedDose(d.mg)}
                              style={{
                                flex: 1, padding: '14px 16px',
                                border: '1px solid',
                                borderColor: selectedDose === d.mg ? 'var(--accent)' : 'var(--line)',
                                background: selectedDose === d.mg ? 'color-mix(in oklab, var(--accent) 10%, transparent)' : 'var(--surface)',
                                borderRadius: 'var(--r-md)',
                                color: 'var(--ink)',
                                fontSize: 14, fontWeight: 500,
                                cursor: 'pointer',
                              }}>{d.label}</button>
                    ))}
                  </div>
                </div>
              )}

              {availableQtys && availableQtys.length > 1 && (
                <div style={{ marginTop: 28 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                    <Label>Doses per month</Label>
                    <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>
                      {qtyToFrequency(selectedQty)}
                    </span>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: qtyGridCols, gap: 6 }}>
                    {availableQtys.map(q => {
                      const sel = selectedQty === q;
                      return (
                        <button key={q} onClick={() => setSelectedQty(q)}
                                style={{
                                  all: 'unset', cursor: 'pointer', textAlign: 'center',
                                  padding: '12px 8px',
                                  border: '1px solid',
                                  borderColor: sel ? 'var(--accent)' : 'var(--line)',
                                  background: sel ? 'color-mix(in oklab, var(--accent) 10%, transparent)' : 'var(--surface)',
                                  borderRadius: 'var(--r-md)',
                                  fontSize: 14, fontWeight: 500,
                                }}>
                          {q}
                          <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', marginTop: 2, fontWeight: 400 }}>
                            /mo
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              <div style={{ marginTop: 28 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                  <Label>Supply length</Label>
                  <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>
                    Per-month price drops with longer plans
                  </span>
                </div>
                <div style={{ display: 'grid', gap: 10 }}>
                  {planEntries.map(p => {
                    const sel = p.duration === selectedDuration;
                    const sPerMo = Math.max(0, baseMonth - p.perMonth);
                    return (
                      <button key={p.duration} onClick={() => setSelectedDuration(p.duration)}
                              className="plan-row"
                              style={{
                                all: 'unset', cursor: 'pointer',
                                position: 'relative',
                                display: 'grid', gridTemplateColumns: '24px 1.2fr 1fr auto', gap: 16,
                                alignItems: 'center',
                                padding: '18px 20px',
                                border: '1.5px solid',
                                borderColor: sel ? 'var(--accent)' : 'var(--line)',
                                background: sel ? 'color-mix(in oklab, var(--accent) 8%, transparent)' : 'var(--surface)',
                                borderRadius: 'var(--r-md)',
                                transition: 'all .18s ease',
                              }}>
                        {p.badge && (
                          <div style={{
                            position: 'absolute', top: -10, right: 16,
                            padding: '3px 10px',
                            background: p.badge === 'Best value' ? 'var(--accent)' : 'var(--surface-2)',
                            color: p.badge === 'Best value' ? 'var(--cta-ink)' : 'var(--ink)',
                            border: '1px solid',
                            borderColor: p.badge === 'Best value' ? 'var(--accent)' : 'var(--line-strong)',
                            borderRadius: 999,
                            fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase',
                            fontWeight: 500,
                          }}>{p.badge}</div>
                        )}
                        <div style={{
                          width: 22, height: 22, borderRadius: 22,
                          border: '1.5px solid',
                          borderColor: sel ? 'var(--accent)' : 'var(--line-strong)',
                          display: 'grid', placeItems: 'center',
                        }}>
                          {sel && <div style={{ width: 10, height: 10, borderRadius: 10, background: 'var(--accent)' }} />}
                        </div>
                        <div>
                          <div style={{ fontSize: 16, fontWeight: 500 }}>{p.label}</div>
                          <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>
                            {pillsPerMonth} doses / mo
                          </div>
                        </div>
                        <div className="plan-save" style={{
                          display: 'flex', alignItems: 'baseline', gap: 6,
                          fontSize: 12, color: 'var(--ink-mute)',
                        }}>
                          {sPerMo > 0 && (
                            <span style={{ color: 'var(--good)', fontWeight: 500, fontSize: 12 }}>
                              Save ${Math.round(sPerMo)}/mo
                            </span>
                          )}
                        </div>
                        <div style={{ textAlign: 'right' }}>
                          <div style={{ fontFamily: 'var(--serif)', fontSize: 26, lineHeight: 1 }}>
                            ${Math.round(p.perMonth)}<span style={{ fontSize: 13, color: 'var(--ink-mute)' }}>/mo</span>
                          </div>
                          <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', marginTop: 4 }}>
                            ${fmtMoney(p.total)} billed {p.duration === 1 ? 'monthly' : `every ${p.duration} mo`}
                          </div>
                        </div>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div style={{
                marginTop: 28, padding: 22,
                background: 'var(--surface)',
                border: '1px solid var(--line)',
                borderRadius: 'var(--r-lg)',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', letterSpacing: '.06em', textTransform: 'uppercase' }}>Today</div>
                    <div style={{ fontFamily: 'var(--serif)', fontSize: 38, marginTop: 4, lineHeight: 1 }}>
                      {discountAmount > 0 && (
                        <span style={{ color: 'var(--ink-mute)', textDecoration: 'line-through', fontSize: 20, marginRight: 8 }}>${fmtMoney(plan.total)}</span>
                      )}
                      ${fmtMoney(finalTotal)}
                      <span style={{ fontSize: 14, color: 'var(--ink-mute)', marginLeft: 8 }}>USD</span>
                    </div>
                    {discountAmount > 0 && (
                      <div style={{ marginTop: 6, fontSize: 12, color: 'var(--good)' }}>
                        {discount.code} applied · −${fmtMoney(discountAmount)} off
                      </div>
                    )}
                  </div>
                  {savingsTotal > 0 && (
                    <div style={{
                      padding: '6px 12px', borderRadius: 999,
                      background: 'color-mix(in oklab, var(--good) 18%, transparent)',
                      color: 'var(--good)',
                      fontSize: 12, fontWeight: 500,
                    }}>
                      You save ${savingsTotal} vs. monthly
                    </div>
                  )}
                </div>
                {product.kind === 'coming-soon' ? (
                  <ComingSoonCTA productName={product.name} />
                ) : (
                  <button onClick={goCheckout}
                          disabled={!finalCheckoutUrl}
                          style={{
                            ...btn.big, marginTop: 22, width: '100%',
                            justifyContent: 'center', padding: '18px 22px',
                            opacity: finalCheckoutUrl ? 1 : 0.5,
                            cursor: finalCheckoutUrl ? 'pointer' : 'not-allowed',
                          }}>
                    Continue to secure checkout →
                  </button>
                )}
                <div style={{
                  marginTop: 14, display: 'flex', justifyContent: 'center', gap: 18,
                  fontSize: 11.5, color: 'var(--ink-mute)', flexWrap: 'wrap',
                }}>
                  <span><TrustIcon name="check" size={12} /> Physician reviewed within 24 hours</span>
                  <span><TrustIcon name="lock" size={12} /> Free 2-day shipping</span>
                  <span><TrustIcon name="shield" size={12} /> Refunded if not approved</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <PDPDetails product={product} />
      <PDPFAQ product={product} />
      <SiteFooter />
    </main>
  );
}

function qtyToFrequency(qty) {
  if (qty <= 6)  return '~once a week';
  if (qty <= 8)  return '~twice a week';
  if (qty <= 10) return '~2–3 times / week';
  if (qty <= 12) return '~3 times a week';
  return '~3–4 times / week';
}

function ComingSoonCTA({ productName }) {
  const [email, setEmail] = useState('');
  const [done, setDone] = useState(false);
  const ok = email && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email);
  if (done) {
    return (
      <div style={{ marginTop: 22, padding: 18, textAlign: 'center',
                    background: 'color-mix(in oklab, var(--brand-yellow) 22%, transparent)',
                    border: '1px solid color-mix(in oklab, var(--brand-yellow) 50%, transparent)',
                    borderRadius: 'var(--r-md)' }}>
        <strong>You're on the list.</strong> We'll email you when {productName} drops this week.
      </div>
    );
  }
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <input type="email" value={email} placeholder="you@example.com"
               onChange={(e) => setEmail(e.target.value)}
               style={{
                 all: 'unset', flex: 1, minWidth: 200,
                 padding: '14px 18px',
                 background: 'var(--bg)',
                 border: '1px solid var(--line-strong)',
                 borderRadius: 'var(--r-md)',
                 fontSize: 14, color: 'var(--ink)',
               }} />
        <button disabled={!ok}
                onClick={() => setDone(true)}
                style={{ ...btn.solid, padding: '14px 22px', fontSize: 14,
                         opacity: ok ? 1 : 0.4, cursor: ok ? 'pointer' : 'not-allowed' }}>
          Reserve {productName}
        </button>
      </div>
      <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--ink-mute)' }}>
        {productName} launches this week. We'll let you know.
      </div>
    </div>
  );
}

function PDPGallery({ product }) {
  return (
    <div>
      <div className="pdp-gallery" style={{
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        borderRadius: 'var(--r-xl)',
        padding: 48,
        aspectRatio: '1 / 1',
        display: 'grid', placeItems: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(circle at center, color-mix(in oklab, var(--brand-yellow) 50%, transparent), transparent 60%)',
        }} />
        <div style={{ position: 'relative' }}>
          <PillArt kind={product.pill} size={320} />
        </div>
      </div>
    </div>
  );
}


function Label({ children }) {
  return (
    <div style={{
      fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase',
      color: 'var(--ink-mute)', marginBottom: 10,
    }}>{children}</div>
  );
}

function PDPDetails({ product }) {
  const sections = [
    {
      h: 'What is it',
      body: product.id === 'fits' ? (
        <p>FITS is a HermanRx-formulated 3-in-1 tablet combining a PDE5 inhibitor (vasodilation), a serotonergic agent (ejaculation control), and a centrally-acting arousal compound. Taken as a once-daily tablet, FITS is designed for men who experience overlapping symptoms.</p>
      ) : product.id === 'sertraline' ? (
        <p>Sertraline is an SSRI commonly prescribed off-label at low doses (25mg) for premature ejaculation. Clinical studies show it can significantly extend time to climax with minimal side effects.</p>
      ) : product.id === 'tadalafil' ? (
        <p>Tadalafil is the generic form of Cialis — an FDA-approved PDE5 inhibitor. At low daily doses (2.5–5mg), it keeps you in a state of readiness 24/7 without the need to time intercourse.</p>
      ) : (
        <p>Sildenafil is the generic form of Viagra — an FDA-approved PDE5 inhibitor that increases blood flow to support a firm erection. Most effective when taken 30–60 minutes before intimacy.</p>
      ),
    },
    {
      h: 'How to take it',
      body: product.id === 'sildenafil' ? (
        <ul style={ulS}>
          <li>Take one tablet 30–60 minutes before sex</li>
          <li>Avoid heavy meals and alcohol before dosing</li>
          <li>Effects last 4–6 hours</li>
          <li>Maximum one dose per 24 hours</li>
        </ul>
      ) : product.id === 'sertraline' ? (
        <ul style={ulS}>
          <li>One 25mg tablet at the same time daily</li>
          <li>Allow 2–3 weeks for full effect</li>
          <li>Do not stop abruptly — taper with physician guidance</li>
        </ul>
      ) : (
        <ul style={ulS}>
          <li>One tablet at the same time each day</li>
          <li>Steady-state achieved after ~5 days</li>
          <li>Works whether food is consumed or not</li>
          <li>No need to plan intimacy</li>
        </ul>
      ),
    },
    {
      h: 'Common side effects',
      body: (
        <p>Most men tolerate this medication well. The most commonly reported side effects are headache (~10%), facial flushing, nasal congestion, and mild indigestion. Serious side effects are rare. Stop use and seek medical attention for chest pain, prolonged erection (priapism), or vision changes.</p>
      ),
    },
    {
      h: 'Who shouldn\'t take it',
      body: (
        <ul style={ulS}>
          <li>Anyone taking nitrates or nitric oxide donors</li>
          <li>Men with severe cardiovascular conditions</li>
          <li>Anyone with a history of priapism (prolonged erections)</li>
          <li>Severe liver or kidney impairment without physician guidance</li>
        </ul>
      ),
    },
  ];
  return (
    <section style={{ padding: '80px 0', borderTop: '1px solid var(--line)' }}>
      <div className="container">
        <div style={{ marginBottom: 36 }}>
          <Eyebrow>The details</Eyebrow>
          <h2 style={{ fontSize: 'clamp(32px, 4vw, 48px)', marginTop: 14, lineHeight: 1.05 }}>
            About {product.name}.
          </h2>
        </div>
        <div className="pdp-details-grid" style={{
          display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 32,
        }}>
          {sections.map(s => (
            <div key={s.h} style={{
              padding: 28,
              background: 'var(--surface)',
              border: '1px solid var(--line)',
              borderRadius: 'var(--r-lg)',
            }}>
              <h3 style={{ fontFamily: 'var(--serif)', fontSize: 22, fontStyle: 'italic', color: 'var(--accent)' }}>{s.h}</h3>
              <div style={{ marginTop: 12, color: 'var(--ink-dim)', fontSize: 14.5, lineHeight: 1.6 }}>
                {s.body}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
const ulS = { listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 8 };

function PDPFAQ({ product }) {
  const faqs = [
    { q: 'When will I get my shipment?', a: 'Free 2-day shipping on every order. After checkout, a U.S.-licensed physician reviews your assessment within 24 hours. Once approved, your order ships the same day and arrives in 2 days.' },
    { q: 'What does the package look like?', a: 'Plain brown box, no branding, no mention of medication or condition — even the return address is generic.' },
    { q: 'Can I cancel anytime?', a: 'Yes. Pause, change dose, or cancel any time from your dashboard. No retention calls, no penalties.' },
    { q: 'What happens at refill time?', a: 'For longer plans, we automatically ship your next supply about 5 days before you\'d run out. You can change the date anytime.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section style={{ padding: '80px 0', background: 'var(--bg-elev)', borderTop: '1px solid var(--line)' }}>
      <div className="container" style={{ maxWidth: 880 }}>
        <Eyebrow>Common questions</Eyebrow>
        <h2 style={{ fontSize: 36, marginTop: 14, lineHeight: 1.05 }}>About your order.</h2>
        <div style={{ marginTop: 32, borderTop: '1px solid var(--line)' }}>
          {faqs.map((f, i) => (
            <div key={f.q} style={{ borderBottom: '1px solid var(--line)' }}>
              <button onClick={() => setOpen(open === i ? -1 : i)}
                      style={{
                        all: 'unset', cursor: 'pointer',
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                        width: '100%', padding: '20px 4px', gap: 24,
                      }}>
                <span style={{ fontFamily: 'var(--serif)', fontSize: 20, color: open === i ? 'var(--accent)' : 'var(--ink)' }}>
                  {f.q}
                </span>
                <span style={{
                  width: 18, height: 18, position: 'relative', flexShrink: 0,
                  transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform .25s ease',
                }}>
                  <span style={{ position: 'absolute', inset: 0, margin: 'auto', width: 12, height: 1, background: 'var(--ink-dim)' }} />
                  <span style={{ position: 'absolute', inset: 0, margin: 'auto', width: 1, height: 12, background: 'var(--ink-dim)' }} />
                </span>
              </button>
              <div style={{ maxHeight: open === i ? 200 : 0, overflow: 'hidden', transition: 'max-height .3s ease' }}>
                <p style={{ padding: '0 4px 20px', color: 'var(--ink-dim)', fontSize: 14.5, lineHeight: 1.6 }}>{f.a}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ════════════════════════════════════════════════════════════════════════════
//  CART HANDOFF
// ════════════════════════════════════════════════════════════════════════════
function Cart({ go, productId, mode, dose, qty, duration }) {
  const product = CATALOG[productId] || CATALOG.sildenafil;
  const discount = useDiscount();

  // Look up the sticky.io URL
  const checkout = (productId && dose != null && duration != null)
    ? (() => {
        if (product.kind === 'mixed' && mode) {
          const m = product.modes.find(x => x.id === mode);
          return m?.skus?.[dose]?.[qty]?.[duration] || null;
        }
        if (product.kind === 'on-demand') {
          return product.skus?.[dose]?.[qty]?.[duration] || null;
        }
        return null;
      })()
    : null;

  // Plan total (fall back to placeholder)
  const total = checkout?.total
    ?? product.placeholderPlans?.find(p => p.duration === duration)?.total
    ?? product.placeholderPlans?.[0]?.total;
  const discountAmount = discount && total > discount.amount ? discount.amount : 0;
  const finalTotal = Math.max(0, total - discountAmount);

  const [handingOff, setHandingOff] = useState(false);

  const handoff = () => {
    setHandingOff(true);
    // Open the real sticky.io checkout in a new tab if we have a URL
    if (checkout?.id) {
      try { window.open(CHECKOUT_BASE + checkout.id, '_blank', 'noopener'); } catch {}
    }
    setTimeout(() => go('confirm', { productId, mode, dose, qty, duration }), 1800);
  };

  return (
    <main className="page-enter">
      <ResultsHeader go={go} />
      <section style={{ padding: '60px 0' }}>
        <div className="container" style={{
          display: 'grid', gridTemplateColumns: '1.2fr .9fr', gap: 60,
          alignItems: 'flex-start',
        }}>
          <div>
            <Eyebrow>Checkout · Step 1 of 1</Eyebrow>
            <h1 style={{ fontSize: 'clamp(36px, 4.4vw, 52px)', marginTop: 14, lineHeight: 1.1 }}>
              You're almost there.
            </h1>
            <p style={{ marginTop: 16, color: 'var(--ink-dim)', fontSize: 16, lineHeight: 1.6, maxWidth: 520 }}>
              We'll hand you off to our secure checkout (powered by sticky.io) to confirm shipping and payment.
              <strong style={{ color: 'var(--ink)' }}> After checkout, a U.S.-licensed physician reviews your assessment within 24 hours. If approved, your medication ships free 2-day. If not approved, you're fully refunded.</strong>
            </p>

            {discount && (
              <div style={{
                marginTop: 22, padding: '14px 18px',
                background: 'color-mix(in oklab, var(--brand-yellow) 22%, transparent)',
                border: '1px solid color-mix(in oklab, var(--brand-yellow) 50%, transparent)',
                borderRadius: 'var(--r-md)',
                display: 'flex', alignItems: 'center', gap: 12,
                fontSize: 13.5,
              }}>
                <span style={{
                  fontFamily: 'var(--mono)', padding: '2px 8px',
                  background: 'var(--ink)', color: 'var(--bg)',
                  borderRadius: 4, fontSize: 11, letterSpacing: '.06em',
                }}>{discount.code}</span>
                <span>{discount.label} — applied automatically at checkout</span>
              </div>
            )}

            <div style={{ marginTop: 36, display: 'grid', gap: 14 }}>
              <ShippingMock />
              <PaymentMock />
            </div>

            <button onClick={handoff} disabled={handingOff}
                    style={{
                      ...btn.big, marginTop: 28, padding: '18px 26px',
                      opacity: handingOff ? 0.6 : 1,
                    }}>
              {handingOff ? 'Redirecting to secure checkout\u2026' : 'Submit & continue to secure checkout'}
              {!handingOff && <span>→</span>}
            </button>
            <div style={{
              marginTop: 14, fontSize: 12.5, color: 'var(--ink-mute)',
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <TrustIcon name="lock" size={14} />
              256-bit SSL \u00b7 sticky.io PCI-DSS Level 1 compliant
              {checkout?.sku && <span style={{ marginLeft: 8, fontFamily: 'var(--mono)', fontSize: 10.5, opacity: .7 }}>SKU: {checkout.sku}</span>}
            </div>
          </div>

          <OrderSummaryV2
            product={product}
            mode={mode}
            dose={dose}
            qty={qty}
            duration={duration}
            total={total}
            discount={discount}
            discountAmount={discountAmount}
            finalTotal={finalTotal}
          />
        </div>
      </section>
      <SiteFooter />
    </main>
  );
}

function ShippingMock() {
  return (
    <div style={{
      padding: 22, background: 'var(--surface)',
      border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Label>Shipping address</Label>
        <span style={{ fontSize: 11.5, color: 'var(--accent)' }}>Edit</span>
      </div>
      <div style={{ fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink)' }}>
        <div style={{ fontWeight: 500 }}>From your assessment</div>
        <div style={{ color: 'var(--ink-dim)' }}>You'll confirm address at checkout</div>
      </div>
    </div>
  );
}

function PaymentMock() {
  return (
    <div style={{
      padding: 22, background: 'var(--surface)',
      border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
    }}>
      <Label>Payment</Label>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {['Visa', 'Mastercard', 'Amex', 'Discover'].map(c => (
          <div key={c} style={{
            padding: '4px 9px', border: '1px solid var(--line)',
            borderRadius: 5, fontSize: 10.5,
            fontFamily: 'var(--mono)', color: 'var(--ink-dim)',
            letterSpacing: '.06em',
          }}>{c}</div>
        ))}
        <span style={{ fontSize: 12, color: 'var(--ink-mute)', marginLeft: 'auto' }}>or pay with Affirm</span>
      </div>
    </div>
  );
}

function OrderSummaryV2({ product, mode, dose, qty, duration, total, discount, discountAmount, finalTotal }) {
  const doseLabel = dose ? (
    product.kind === 'mixed' && mode === 'daily' ? `${dose}mg daily` : `${dose}mg`
  ) : '';
  const durationLabel = product.durationLabels?.[duration] || `${duration} months`;
  const perMonth = total / duration;

  return (
    <aside style={{
      position: 'sticky', top: 100,
      padding: 28,
      background: 'var(--surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-xl)',
    }}>
      <Label>Order summary</Label>
      <div style={{
        display: 'grid', gridTemplateColumns: '64px 1fr', gap: 16,
        alignItems: 'center', paddingBottom: 18, borderBottom: '1px solid var(--line)',
      }}>
        <div style={{
          width: 64, height: 64, borderRadius: 'var(--r-md)',
          background: 'var(--surface-2)', display: 'grid', placeItems: 'center',
        }}>
          <PillArt kind={product.pill} size={52} />
        </div>
        <div>
          <div style={{ fontWeight: 500, fontSize: 15 }}>
            {product.name}{doseLabel ? ` · ${doseLabel}` : ''}
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-dim)' }}>
            {durationLabel}{qty ? ` · ${qty} doses / mo` : ''}
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', gap: 10, padding: '18px 0', borderBottom: '1px solid var(--line)' }}>
        <Line label={`${durationLabel} of ${product.name}`} value={`$${fmtMoney(total)}`} />
        {discountAmount > 0 && (
          <Line label={`${discount.code} discount`} value={`−$${fmtMoney(discountAmount)}`} positive />
        )}
        <Line label="Physician consult"    value="Free" muted />
        <Line label="Free 2-day shipping"  value="Free" muted />
        <Line label="Pharmacy dispensing"  value="Included" muted />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 18 }}>
        <div>
          <div style={{ fontSize: 13, color: 'var(--ink-mute)', letterSpacing: '.04em', textTransform: 'uppercase' }}>Total today</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', marginTop: 4 }}>
            ${Math.round(perMonth)}/mo equivalent
          </div>
        </div>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 34, lineHeight: 1 }}>${fmtMoney(finalTotal)}</div>
      </div>
      <div style={{
        marginTop: 20, padding: '12px 14px',
        background: 'color-mix(in oklab, var(--good) 12%, transparent)',
        border: '1px solid color-mix(in oklab, var(--good) 26%, var(--line))',
        borderRadius: 'var(--r-md)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--good)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 2 }}>
          <path d="M12 3l8 3v6c0 4-3 8-8 9-5-1-8-5-8-9V6l8-3z"/>
          <path d="M9 12l2 2 4-4"/>
        </svg>
        <div style={{ fontSize: 12.5, color: 'var(--ink-dim)', lineHeight: 1.5 }}>
          <strong style={{ color: 'var(--ink)' }}>Refund guarantee.</strong> If our medical team determines this treatment isn't safe or right for you, you're fully refunded — no fees.
        </div>
      </div>
    </aside>
  );
}

function OrderSummary({ product, plan, dose }) {
  // Legacy shim — kept for back-compat. Not used by the new flow.
  return null;
}

function Line({ label, value, muted, positive }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
      <span style={{ color: 'var(--ink-dim)' }}>{label}</span>
      <span style={{
        color: positive ? 'var(--good)' : muted ? 'var(--good)' : 'var(--ink)',
        fontVariantNumeric: 'tabular-nums',
        fontWeight: positive ? 500 : 400,
      }}>{value}</span>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
//  CONFIRMATION (after sticky.io handoff)
// ════════════════════════════════════════════════════════════════════════════
function Confirm({ go, productId, mode, dose, qty, duration }) {
  const product = CATALOG[productId] || CATALOG.sildenafil;
  // Clear discount once order is confirmed
  useEffect(() => { clearDiscount(); }, []);
  const durationLabel = product.durationLabels?.[duration] || (duration ? `${duration}-month` : '');
  return (
    <main className="page-enter" style={{ minHeight: '100vh', display: 'grid', gridTemplateRows: 'auto 1fr auto' }}>
      <ResultsHeader go={go} />
      <section style={{ display: 'grid', placeItems: 'center', padding: '80px 24px' }}>
        <div style={{ maxWidth: 640, textAlign: 'center' }}>
          <div style={{
            width: 76, height: 76, borderRadius: 76,
            background: 'color-mix(in oklab, var(--accent) 18%, transparent)',
            border: '1px solid var(--accent)',
            display: 'grid', placeItems: 'center', margin: '0 auto',
          }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M4 12l5 5L20 6"/>
            </svg>
          </div>
          <Eyebrow><span style={{ marginTop: 24, display: 'inline-block' }}>Assessment submitted</span></Eyebrow>
          <h1 style={{ fontSize: 'clamp(40px, 5vw, 64px)', marginTop: 14, lineHeight: 1.02 }}>
            That's it.
            <br/>
            <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>You're in the queue.</em>
          </h1>
          <p style={{ marginTop: 22, fontSize: 17, color: 'var(--ink-dim)', lineHeight: 1.6 }}>
            Your assessment is now with a U.S.-licensed physician. We'll email you within 24 hours with your treatment plan. Approved orders ship free 2-day. If your physician decides this treatment isn't right for you, you'll be fully refunded.
          </p>

          <div style={{
            marginTop: 40, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, textAlign: 'left',
          }}>
            {[
              { n: '01', h: 'Within 24 hours', s: 'Physician reviews your assessment' },
              { n: '02', h: 'Same day ship',   s: 'Pharmacy fills your prescription' },
              { n: '03', h: '2 days later',    s: 'Discreet, free 2-day delivery' },
            ].map(s => (
              <div key={s.n} style={{
                padding: 22,
                background: 'var(--surface)',
                border: '1px solid var(--line)',
                borderRadius: 'var(--r-md)',
              }}>
                <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 28, color: 'var(--accent)', lineHeight: 1 }}>{s.n}</div>
                <div style={{ marginTop: 14, fontSize: 14, fontWeight: 500 }}>{s.h}</div>
                <div style={{ marginTop: 4, fontSize: 12.5, color: 'var(--ink-dim)' }}>{s.s}</div>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 40, padding: 22,
            background: 'var(--surface)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            display: 'grid', gridTemplateColumns: '48px 1fr', gap: 16,
            alignItems: 'center', textAlign: 'left',
          }}>
            <PillArt kind={product.pill} size={48} />
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>
                {product.name}{dose ? ` · ${dose}mg` : ''}{durationLabel ? ` · ${durationLabel} supply` : ''}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-dim)' }}>Confirmation sent to your email · Order #HRX-{Math.floor(Math.random() * 90000) + 10000}</div>
            </div>
          </div>

          <button onClick={() => go('landing')} style={{ ...btn.outline, marginTop: 32 }}>
            Back to home
          </button>
        </div>
      </section>
      <SiteFooter />
    </main>
  );
}

Object.assign(window, { Results, PDP, Cart, Confirm });
