/* Aevitan website — Account hub: membership paths, patient signup, dashboards. */
const DSacc = window.AevitanDesignSystem_6a042d;
// The real auth step (free signup / partner registration) lives on the portal (separate origin); the chooser
// stays here on the marketing site (owner-defined). Free -> portal /signup.
const PORTAL_URL_ACC = (typeof location !== 'undefined' && location.hostname === 'localhost')
  ? 'http://localhost:3001'
  : 'https://portal.aevitan.com';

/* ---- File upload field (captures filename, shows status) ---- */
function Upload({ label, hint, value, onFile }) {
  const ref = React.useRef(null);
  return (
    <div className="aevacc-up">
      <div className="aevacc-up__head">
        <span className="aevacc-up__label">{label}</span>
        {value
          ? <span className="aevacc-up__stat is-done">Uploaded</span>
          : <span className="aevacc-up__stat">Required</span>}
      </div>
      <button type="button" className={`aevacc-up__drop ${value ? 'is-done' : ''}`} onClick={() => ref.current && ref.current.click()}>
        {value
          ? <React.Fragment><span className="aevacc-up__file">{value}</span><span className="aevacc-up__replace">Replace</span></React.Fragment>
          : <React.Fragment><span className="aevacc-up__plus">＋</span><span>Choose file</span></React.Fragment>}
      </button>
      {hint && <span className="aevacc-up__hint">{hint}</span>}
      <input ref={ref} type="file" hidden onChange={(e) => { const f = e.target.files[0]; if (f) onFile(f.name); }} />
    </div>
  );
}

/* ---- Path chooser ---- */
function PathChooser({ pick, go }) {
  const { Kicker } = DSacc;
  // Membership has one common entry. Club standing and the professional curation reports grow from there,
  // not separate onboarding products.
  const paths = [
    { id: 'join', who: 'How to belong', name: 'One free membership', cost: 'Patients · HCPs · Clinics · Resellers',
      desc: 'Every eligible member starts with the same Longevity Club account. Choose your member type during signup and complete additional information only when it becomes relevant.',
      list: ['Common L1 signup', 'Persona-specific profile', 'Separate member declarations where applicable'], cta: 'Join the Club' },
    { id: 'tiers', who: 'Member perk', name: 'Club standing', cost: 'Earned through Club activity',
      desc: 'Club standing reflects sustained activity within the Longevity Club and is reassessed continuously.',
      list: ['Reassessed automatically', 'May qualify you for preferential pricing', 'Visible in your private area'] },
    { id: 'reports', who: 'The member benefit', name: 'Professional curation reports', cost: 'Included \u00b7 earned through standing', feature: true,
      desc: 'Every member reads the board\u2019s opinion on each product. The professional report adds the full evaluation, the batch certificate of analysis and the manufacturer\u2019s package insert.',
      list: ['Scope, evidence, mechanism, quality, risk-reward', 'Third-party certificate of analysis', 'Manufacturer package insert, attributed'] },
  ];
  return (
    <section className="aevsite-band aevsite-band--top">
      <div className="aevsite-wrap aevsite-reveal">
        <Kicker>Aevitan Longevity Club</Kicker>
        <h1 className="aevsite-h1">One way into the Club.</h1>
        <p className="aevsite-lead" style={{ maxWidth: '58ch' }}>Membership is common and free. Your member type shapes the information and declarations relevant to you; Club standing and the professional curation reports grow from there.</p>
        <div className="aevpath" style={{ marginTop: 40 }}>
          {paths.map((p) => (
            <div key={p.id} className={`aevpath__card ${p.feature ? 'aevpath__card--feature' : ''}`}>
              <div className="aevpath__who">{p.who}</div>
              <div className="aevpath__name">{p.name}</div>
              <div className="aevpath__cost">{p.cost}</div>
              <p className="aevpath__desc">{p.desc}</p>
              <ul className="aevpath__list">{p.list.map((x) => <li key={x}>{x}</li>)}</ul>
              {p.cta ? <div className="aevpath__cta">
                <button className="aevacc-pick is-gold" onClick={() => pick(p.id)}>{p.cta} →</button>
              </div> : null}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- Free patient signup ---- */
function FreeSignup({ onDone, back }) {
  const { Kicker, Card, Input, Select, Button } = DSacc;
  const [f, setF] = React.useState({ name: '', email: '', country: 'United States', goal: 'Healthy aging' });
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const countries = window.AEV_LC.get().countries.map((c) => c.name);
  return (
    <section className="aevsite-band aevsite-band--top">
      <div className="aevsite-wrap aevsite-narrow aevsite-reveal">
        <button className="aevacc-back" onClick={back}>← All membership options</button>
        <Kicker>Free membership · Individuals</Kicker>
        <h1 className="aevsite-h1" style={{ fontSize: 44 }}>Guidance, and a professional who fits you.</h1>
        <p className="muted" style={{ maxWidth: '54ch', marginTop: 10 }}>Membership is free. Tell us a little about yourself and we will share product-use guidance and connect you with a health professional inside the Longevity Club.</p>
        <div className="aevsite-form" style={{ marginTop: 26 }}>
          <Card>
            <div className="aevsite-form__title">Create your free account</div>
            <div className="aevsite-form__grid">
              <Input label="Full name" placeholder="Your name" value={f.name} onChange={set('name')} />
              <Input label="Email" type="email" placeholder="you@email.com" value={f.email} onChange={set('email')} />
              <Select label="Country" options={countries} value={f.country} onChange={set('country')} />
              <Select label="Primary goal" options={['Healthy aging', 'Energy & metabolism', 'Recovery & performance', 'Skin & longevity', 'Other']} value={f.goal} onChange={set('goal')} />
            </div>
            <Button variant="primary" block style={{ marginTop: 18 }}
              onClick={() => onDone({ name: f.name || 'New Member', email: f.email, country: f.country, goal: f.goal, tier: 'free', category: 'Free · Individual' })}>
              Join free
            </Button>
            <p className="muted aevsite-form__fine">Free membership is educational. Product use is always guided by your matched health professional.</p>
          </Card>
        </div>
      </div>
    </section>
  );
}

/* ---- Subscription signup wizard ---- */
// B33: real subscription cadence copy ("$X monthly", never "/mo").
const CADENCE_WORD = { monthly: 'monthly', quarterly: 'quarterly', yearly: 'yearly' };
const AEV_NAV_BTN = { flex: '0 0 auto', width: 34, height: 34, borderRadius: 999, border: '1px solid rgba(12,26,51,.15)', background: '#fff', color: '#0c1a33', cursor: 'pointer', fontSize: 20, lineHeight: 1 };

// B33: horizontal plan carousel — native scroll + boundary-aware chevrons (both hidden when all fit) +
// keyboard (Arrow keys). Boundaries recompute on scroll, data change and resize (ResizeObserver + px tol).
function PlanCarousel({ plans, selectedId, onSelect }) {
  const scroller = React.useRef(null);
  const [atStart, setAtStart] = React.useState(true);
  const [atEnd, setAtEnd] = React.useState(true);
  const update = React.useCallback(() => {
    const el = scroller.current;
    if (!el) return;
    const tol = 4;
    const fits = el.scrollWidth <= el.clientWidth + tol;
    setAtStart(fits || el.scrollLeft <= tol);
    setAtEnd(fits || el.scrollLeft >= el.scrollWidth - el.clientWidth - tol);
  }, []);
  React.useEffect(() => {
    const el = scroller.current;
    if (!el) return undefined;
    update();
    el.addEventListener('scroll', update, { passive: true });
    let ro;
    if (typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(update); ro.observe(el); }
    window.addEventListener('resize', update);
    return () => { el.removeEventListener('scroll', update); if (ro) ro.disconnect(); window.removeEventListener('resize', update); };
  }, [update, plans]);
  const nudge = (dir) => {
    const el = scroller.current;
    if (!el) return;
    const first = el.querySelector('.aevacc-plan');
    const w = first ? (first.nextElementSibling ? first.nextElementSibling.offsetLeft - first.offsetLeft : first.offsetWidth) : 260;
    el.scrollBy({ left: dir * w, behavior: 'smooth' });
  };
  return (
    <div className="aevacc-plan-carousel">
      <button type="button" className="aevacc-plan-nav" aria-label="Previous plans" disabled={atStart} onClick={() => nudge(-1)} style={{ ...AEV_NAV_BTN, visibility: atStart ? 'hidden' : 'visible' }}>‹</button>
      <div className="aevacc-plans" ref={scroller} role="listbox" aria-label="Subscription plans"
           style={{ display: 'flex', gap: 16, overflowX: 'auto', scrollSnapType: 'x mandatory', flex: 1, paddingBottom: 6 }}
           onKeyDown={(e) => { if (e.key === 'ArrowRight') { e.preventDefault(); nudge(1); } else if (e.key === 'ArrowLeft') { e.preventDefault(); nudge(-1); } }}>
        {plans.map((p) => {
          const on = selectedId === p.id;
          return (
            <button key={p.id} type="button" role="option" aria-selected={on}
                    className={`aevacc-plan ${on ? 'is-on' : ''}`}
                    style={{ flex: '0 0 260px', scrollSnapAlign: 'start' }}
                    onClick={() => onSelect(p.id)}>
              <div className="aevacc-plan__name">{p.name}</div>
              <div className="aevacc-plan__price">${Math.round(p.price_cents / 100).toLocaleString('en-US')}<span>{CADENCE_WORD[p.cadence] || p.cadence}</span></div>
              <div className="aevacc-plan__meta">{p.bundle_qty} products · every {p.ship_every_weeks} weeks</div>
            </button>
          );
        })}
      </div>
      <button type="button" className="aevacc-plan-nav" aria-label="More plans" disabled={atEnd} onClick={() => nudge(1)} style={{ ...AEV_NAV_BTN, visibility: atEnd ? 'hidden' : 'visible' }}>›</button>
    </div>
  );
}

function SubSignup({ onDone, back }) {
  const { Kicker, Card, Input, Select, Button } = DSacc;
  const [f, setF] = React.useState({
    name: '', email: '', countryCode: '', city: '', address: '', postal: '',
    plan: null, docPresc: '', docAddr: '', docId: '',
  });
  const [stepKey, setStepKey] = React.useState('address');
  // Fetched feeds: null = loading, 'error' = failed/retryable, array = resolved.
  const [plans, setPlans] = React.useState(null);
  const [countries, setCountries] = React.useState(null);
  const [plansNonce, setPlansNonce] = React.useState(0);
  const [countriesNonce, setCountriesNonce] = React.useState(0);
  React.useEffect(() => {
    const ac = new AbortController();
    setPlans(null);
    fetch('/api/plans', { signal: ac.signal })
      .then((r) => { if (!r.ok) throw new Error('plans'); return r.json(); })
      .then((d) => setPlans(Array.isArray(d.plans) ? d.plans : 'error'))
      .catch((e) => { if (e.name !== 'AbortError') setPlans('error'); });
    return () => ac.abort();
  }, [plansNonce]);
  React.useEffect(() => {
    const ac = new AbortController();
    setCountries(null);
    fetch('/api/countries', { signal: ac.signal })
      .then((r) => { if (!r.ok) throw new Error('countries'); return r.json(); })
      .then((d) => setCountries(Array.isArray(d.countries) ? d.countries : 'error'))
      .catch((e) => { if (e.name !== 'AbortError') setCountries('error'); });
    return () => ac.abort();
  }, [countriesNonce]);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const plansReady = Array.isArray(plans);
  const countriesReady = Array.isArray(countries);
  // B34 M5: the address step must not advance on emptiness — country alone (with its default)
  // used to satisfy Continue. Region-less countries exist, so only these five gate.
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
  const addressDone =
    f.name.trim() && EMAIL_RE.test(f.email.trim()) && f.address.trim() && f.city.trim() && f.postal.trim();
  // Auto-select the first plan only AFTER a non-empty list resolves (never dereference before — no mount crash).
  React.useEffect(() => {
    if (plansReady && plans.length > 0 && !f.plan) setF((s) => ({ ...s, plan: plans[0].id }));
  }, [plansReady, plans, f.plan]);
  const selPlan = plansReady ? plans.find((p) => p.id === f.plan) || null : null;
  const selCountry = countriesReady ? countries.find((c) => c.code === f.countryCode) : undefined;
  // Fail-SAFE: an unresolved/unmatched country requires ALL three documents.
  const req = selCountry
    ? { presc: !!selCountry.require_prescription, addr: !!selCountry.require_address_proof, id: !!selCountry.require_id }
    : { presc: true, addr: true, id: true };
  const reqCount = (req.presc ? 1 : 0) + (req.addr ? 1 : 0) + (req.id ? 1 : 0);
  const hasDocs = reqCount > 0;
  const docsDone = (!req.presc || f.docPresc) && (!req.addr || f.docAddr) && (!req.id || f.docId);
  const countryName = selCountry ? selCountry.name : '';
  const stepDefs = [{ key: 'address', label: 'Address' }, { key: 'plan', label: 'Plan' }]
    .concat(hasDocs ? [{ key: 'documents', label: 'Documents' }] : [])
    .concat([{ key: 'confirm', label: 'Confirm' }]);
  // Clamp: if the current step disappeared (country change removed Documents), fall back to Confirm.
  React.useEffect(() => {
    if (!stepDefs.some((s) => s.key === stepKey)) setStepKey('confirm');
  }, [hasDocs, stepKey]);
  const idx = Math.max(0, stepDefs.findIndex((s) => s.key === stepKey));
  const goNext = () => { const n = stepDefs[idx + 1]; if (n) setStepKey(n.key); };
  const goPrev = () => { const p = stepDefs[idx - 1]; if (p) setStepKey(p.key); };
  // Country change resets uploads + re-derives requirements (never carry a prior country's docs).
  const onCountry = (e) => setF((s) => ({ ...s, countryCode: e.target.value, docPresc: '', docAddr: '', docId: '' }));
  const countryOptions = [{ value: '', label: countries === null ? 'Loading regions…' : countries === 'error' ? 'Could not load regions' : 'Select your country' }]
    .concat(countriesReady ? countries.map((c) => ({ value: c.code, label: c.name })) : []);

  return (
    <section className="aevsite-band aevsite-band--top">
      <div className="aevsite-wrap aevsite-narrow aevsite-reveal">
        <button className="aevacc-back" onClick={back}>← All membership options</button>
        <Kicker>Patient subscription</Kicker>
        <h1 className="aevsite-h1" style={{ fontSize: 44 }}>Treatments, delivered to your door.</h1>

        <div className="aevacc-steps">
          {stepDefs.map((s, i) => (
            <div key={s.key} className={`aevacc-step ${i === idx ? 'is-on' : ''} ${i < idx ? 'is-done' : ''}`}>
              <span className="aevacc-step__n">{i < idx ? '✓' : i + 1}</span><span>{s.label}</span>
            </div>
          ))}
        </div>

        <div className="aevsite-form" style={{ marginTop: 8 }}>
          <Card>
            {stepKey === 'address' && (
              <React.Fragment>
                <div className="aevsite-form__title">Where should we deliver?</div>
                <p className="muted sm" style={{ margin: '0 0 16px' }}>We confirm availability by region before anything else, because personal-import rules differ by country.</p>
                <div className="aevsite-form__grid">
                  <Input label="Full name" placeholder="Your name" value={f.name} onChange={set('name')} />
                  <Input label="Email" type="email" placeholder="you@email.com" value={f.email} onChange={set('email')} />
                  <Select label="Country" options={countryOptions} value={f.countryCode} onChange={onCountry} disabled={!countriesReady} />
                  <Input label="City" placeholder="City" value={f.city} onChange={set('city')} />
                  <Input label="Address" placeholder="Street and number" value={f.address} onChange={set('address')} />
                  <Input label="Postal code" placeholder="ZIP / Postal" value={f.postal} onChange={set('postal')} />
                </div>
                {countries === 'error' && (
                  <div className="aevacc-avail is-no">
                    <b>We couldn't load the serviceable regions.</b>
                    <span>Please try again.</span>
                    <div className="aevacc-avail__wl"><Button variant="ghost" size="sm" onClick={() => setCountriesNonce((n) => n + 1)}>Retry</Button></div>
                  </div>
                )}
                {countriesReady && countries.length === 0 && (
                  <div className="aevacc-avail is-no">
                    <b>Subscriptions are not open in any region yet.</b>
                    <span>Leave your email and we will reach out the moment service becomes active.</span>
                  </div>
                )}
                {selCountry && (
                  <div className="aevacc-avail is-ok">
                    <b>✓ We deliver to {countryName}.</b>
                    <span>Personal import is supported here. You can continue to choose your plan.</span>
                  </div>
                )}
                <div className="aevacc-nav">
                  <Button variant="primary" disabled={!selCountry || !addressDone} onClick={goNext}>Continue</Button>
                </div>
                {selCountry && !addressDone && (
                  <p className="muted sm" style={{ marginTop: 8 }}>Complete your delivery address to continue.</p>
                )}
              </React.Fragment>
            )}

            {stepKey === 'plan' && (
              <React.Fragment>
                <div className="aevsite-form__title">Choose your plan</div>
                {plans === null && (
                  <div className="aevacc-plans" style={{ display: 'flex', gap: 16 }}>
                    {[0, 1, 2].map((i) => (
                      <div key={i} className="aevacc-plan" aria-hidden="true" style={{ flex: '0 0 260px', opacity: 0.5 }}>
                        <div className="aevacc-plan__name">Loading…</div>
                        <div className="aevacc-plan__price">&nbsp;</div>
                        <div className="aevacc-plan__meta">&nbsp;</div>
                      </div>
                    ))}
                  </div>
                )}
                {plans === 'error' && (
                  <div className="aevacc-avail is-no">
                    <b>We couldn't load the plans.</b>
                    <div className="aevacc-avail__wl"><Button variant="ghost" size="sm" onClick={() => setPlansNonce((n) => n + 1)}>Retry</Button></div>
                  </div>
                )}
                {plansReady && plans.length === 0 && (
                  <p className="muted sm">No plans are available right now. Please check back soon.</p>
                )}
                {plansReady && plans.length > 0 && (
                  <PlanCarousel plans={plans} selectedId={f.plan} onSelect={(id) => setF((s) => ({ ...s, plan: id }))} />
                )}
                <p className="muted sm" style={{ marginTop: 14 }}>Shipping, customs-clearance support and documentation are included in every plan. You can change cadence or pause anytime from your dashboard.</p>
                <div className="aevacc-nav">
                  <Button variant="ghost" onClick={goPrev}>Back</Button>
                  <Button variant="primary" disabled={!selPlan} onClick={goNext}>Continue</Button>
                </div>
              </React.Fragment>
            )}

            {stepKey === 'documents' && (
              <React.Fragment>
                <div className="aevsite-form__title">Upload your documents</div>
                <p className="muted sm" style={{ margin: '0 0 18px' }}>{countryName ? `Required for delivery to ${countryName}. ` : ''}These let us prepare the regulatory paperwork and clear customs. Reviewed by our team, never shared beyond what clearance requires.</p>
                <div className="aevacc-uploads">
                  {req.presc && <Upload label="Medical prescription or report" hint="PDF or image, from your prescribing professional" value={f.docPresc} onFile={(n) => setF((s) => ({ ...s, docPresc: n }))} />}
                  {req.addr && <Upload label="Proof of address" hint="Utility bill or statement, last 3 months" value={f.docAddr} onFile={(n) => setF((s) => ({ ...s, docAddr: n }))} />}
                  {req.id && <Upload label="Personal identification" hint="Passport or government ID" value={f.docId} onFile={(n) => setF((s) => ({ ...s, docId: n }))} />}
                </div>
                <div className="aevacc-nav">
                  <Button variant="ghost" onClick={goPrev}>Back</Button>
                  <Button variant="primary" disabled={!docsDone} onClick={goNext}>Continue</Button>
                </div>
                {!docsDone && (
                  <p className="muted sm" style={{ marginTop: 8 }}>Attach the required documents above to continue.</p>
                )}
              </React.Fragment>
            )}

            {stepKey === 'confirm' && (
              <React.Fragment>
                <div className="aevsite-form__title">Confirm your subscription</div>
                <div className="aevacc-review">
                  <div className="aevacc-review__row"><span>Plan</span><b>{selPlan ? `${selPlan.name} · $${Math.round(selPlan.price_cents / 100).toLocaleString('en-US')} ${CADENCE_WORD[selPlan.cadence] || selPlan.cadence}` : '—'}</b></div>
                  <div className="aevacc-review__row"><span>Bundle</span><b>{selPlan ? `${selPlan.bundle_qty} products · every ${selPlan.ship_every_weeks} weeks` : '—'}</b></div>
                  <div className="aevacc-review__row"><span>Deliver to</span><b>{f.city || 'Your city'}, {countryName}</b></div>
                  <div className="aevacc-review__row"><span>Documents</span><b>{hasDocs ? `${reqCount} required · pending review` : `No documents required for ${countryName}`}</b></div>
                </div>
                <p className="muted sm" style={{ marginTop: 14 }}>By subscribing you authorize Aevitan to prepare import documentation on your behalf. Clearance is coordinated with licensed partners in your country.</p>
                <div className="aevacc-nav">
                  <Button variant="ghost" onClick={goPrev}>Back</Button>
                  <Button variant="gold" disabled={!selPlan} onClick={() => onDone({
                    name: f.name || 'New Member', email: f.email, country: countryName, city: f.city,
                    tier: 'sub', category: 'Subscription · ' + (selPlan ? selPlan.name : ''),
                    plan: selPlan ? { name: selPlan.name, items: selPlan.bundle_qty, price: Math.round(selPlan.price_cents / 100), cadence: 'every ' + selPlan.ship_every_weeks + ' weeks' } : null,
                    docs: { presc: f.docPresc, addr: f.docAddr, id: f.docId },
                  })}>Confirm subscription</Button>
                </div>
              </React.Fragment>
            )}
          </Card>
        </div>
      </div>
    </section>
  );
}

/* ---- Patient dashboard ---- */
function Dashboard({ member, go, reset }) {
  const { Kicker, Card, Button, Badge } = DSacc;
  const isSub = member.tier === 'sub';
  const first = (member.name || 'Member').split(' ')[0];
  return (
    <section className="aevsite-band aevsite-band--top">
      <div className="aevsite-wrap aevsite-reveal">
        <div className="aevacc-dash__head">
          <div>
            <Kicker>Your Longevity Club</Kicker>
            <h1 className="aevsite-h1" style={{ fontSize: 46 }}>Welcome, {first}.</h1>
          </div>
          <div className="aevacc-dash__badge"><Badge variant="seal">{member.category}</Badge></div>
        </div>

        {isSub ? (
          <div className="aevacc-grid">
            <Card className="aevacc-card aevacc-card--wide">
              <div className="aevacc-card__k">Next shipment</div>
              <div className="aevacc-ship">
                <div className="aevacc-ship__date"><span>Ships</span><b>Jul 14, 2026</b></div>
                <div className="aevacc-ship__plan"><span>{member.category.replace('Subscription · ', '')}</span><b>{member.plan ? member.plan.items : 4} products · {member.plan ? member.plan.cadence.toLowerCase() : 'every 8 weeks'}</b></div>
              </div>
              <div className="aevacc-track">
                {['Order prepared', 'Documents filed', 'In customs clearance', 'Out for delivery'].map((s, i) => (
                  <div key={s} className={`aevacc-track__step ${i <= 1 ? 'is-done' : ''} ${i === 1 ? 'is-cur' : ''}`}><span /><label>{s}</label></div>
                ))}
              </div>
              <div className="aevacc-actions">
                <Button variant="ghost" size="sm">Adjust bundle</Button>
                <Button variant="ghost" size="sm">Change cadence</Button>
                <Button variant="ghost" size="sm">Skip / pause</Button>
              </div>
            </Card>

            <Card className="aevacc-card">
              <div className="aevacc-card__k">Documents</div>
              {[['Prescription / report', member.docs && member.docs.presc], ['Proof of address', member.docs && member.docs.addr], ['Identification', member.docs && member.docs.id]].map(([label, val]) => (
                <div key={label} className="aevacc-doc">
                  <span>{label}</span>
                  <span className={`aevacc-doc__s ${val ? 'is-ok' : ''}`}>{val ? 'In review' : 'Missing'}</span>
                </div>
              ))}
              <button className="aevacc-link">Manage documents →</button>
            </Card>

            <Card className="aevacc-card">
              <div className="aevacc-card__k">Your professional</div>
              <div className="aevacc-pro">
                <div className="aevacc-pro__av">SB</div>
                <div><b>Dr. Saulo Bento</b><span className="muted">Medical-scientific director</span></div>
              </div>
              <p className="muted sm">Your protocol is reviewed by a Club professional. Message them with any question about use or dosing.</p>
              <button className="aevacc-link">Message →</button>
            </Card>
          </div>
        ) : (
          <div className="aevacc-grid">
            <Card className="aevacc-card aevacc-card--wide">
              <div className="aevacc-card__k">Your matched professional</div>
              <div className="aevacc-pro">
                <div className="aevacc-pro__av">SB</div>
                <div><b>Dr. Saulo Bento</b><span className="muted">Medical-scientific director · Longevity Club</span></div>
              </div>
              <p className="muted">We have matched you with a health professional inside the Club. They will guide product use and can take you further if you choose to begin a protocol.</p>
              <div className="aevacc-actions">
                <Button variant="primary" size="sm">Book an intro</Button>
                <Button variant="gold" size="sm" onClick={() => go('club')}>Explore subscription</Button>
              </div>
            </Card>

            <Card className="aevacc-card">
              <div className="aevacc-card__k">Your guidance</div>
              {['How to use NAD+ strips', 'Building a daily longevity base', 'Reading a Certificate of Analysis'].map((t) => (
                <div key={t} className="aevacc-doc"><span>{t}</span><span className="aevacc-doc__s is-ok">Open</span></div>
              ))}
            </Card>

            <Card className="aevacc-card">
              <div className="aevacc-card__k">Goal</div>
              <p className="aevacc-goal">{member.goal || 'Healthy aging'}</p>
              <p className="muted sm">Educational updates will arrive as the curated portfolio grows around your goal.</p>
            </Card>
          </div>
        )}

        <button className="aevacc-back" style={{ marginTop: 34 }} onClick={reset}>← Sign out of demo account</button>
      </div>
    </section>
  );
}

/* ---- Account hub ---- */
function Account({ go }) {
  // Every member type enters through the same authenticated portal signup. Historical demo forms remain
  // defined above for source compatibility but are intentionally unreachable from the live account hub.
  React.useEffect(() => {
    try { sessionStorage.removeItem('aev-account-view'); } catch (e) {}
  }, []);
  const choose = (id) => {
    if (id === 'join') { window.location.href = PORTAL_URL_ACC + '/signup'; return; }
  };
  return <PathChooser pick={choose} go={go} />;
}

window.Account = Account;
