// Main sections: Nav, Hero, Programs rotator, Process, Science, Team, Testimonials, FAQ, Final CTA, Footer

const { useState, useEffect, useRef } = React;

// Parallax band — full-bleed image panel with pull-quote, sits between sections
const ParallaxBand = ({ src, eyebrow, children, speed = 0.35, height = '65vh' }) => (
  <section className="parallax-band" style={{ height }}>
    <ParallaxImage src={src} speed={speed} scale={1.25} overlay={0.72} />
    <div className="parallax-band-text reveal">
      {eyebrow && <div className="parallax-band-eyebrow">{eyebrow}</div>}
      <div className="parallax-band-title">{children}</div>
    </div>
  </section>
);

// ───────────────────── Nav ─────────────────────
// `home` prefix: empty string when on homepage, "index.html" when on Resources or other top-level pages.
// This lets hash links work both as in-page scroll AND cross-page navigation.
const Nav = ({ ctaLabel, onQuiz, home = '' }) => {
  const [menuOpen, setMenuOpen] = useState(false);
  // Lock body scroll when menu open + escape key to close
  useEffect(() => {
    if (menuOpen) {
      document.body.classList.add('nav-menu-open');
      const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
      window.addEventListener('keydown', onKey);
      return () => {
        document.body.classList.remove('nav-menu-open');
        window.removeEventListener('keydown', onKey);
      };
    } else {
      document.body.classList.remove('nav-menu-open');
    }
  }, [menuOpen]);
  const closeMenu = () => setMenuOpen(false);
  const navLink = (label, hash, isResources) => (
    <a
      href={isResources ? 'Resources.html' : `${home}${hash}`}
      className="nav-link"
      onClick={closeMenu}
    >{label}</a>
  );
  return (
    <nav className="nav">
      <a href={home || '#top'} className="nav-logo" aria-label="Eden Wellness — home" onClick={closeMenu}>
        <EdenLogoMark size={56} />
      </a>
      <div className="nav-links">
        {navLink('Programs', '#programs')}
        {navLink('Our Work', '#process')}
        {navLink('Team', '#team')}
        {navLink('Find My Path', '#quiz')}
        {navLink('FAQ', '#faq')}
        {navLink('Resources', '', true)}
      </div>
      <div className="nav-cta">
        <a
          href={`${home}#quiz`}
          className="btn btn-primary nav-cta-btn"
          style={{ padding: '10px 18px', fontSize: 12 }}
          onClick={(e) => { if (!home) { e.preventDefault(); onQuiz(); } closeMenu(); }}
        >
          {ctaLabel}
          <span className="btn-arrow"><ArrowRight /></span>
        </a>
        <button
          type="button"
          className={`nav-hamburger ${menuOpen ? 'is-open' : ''}`}
          aria-label={menuOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}
        >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>
      <div
        className={`nav-mobile-panel ${menuOpen ? 'is-open' : ''}`}
        aria-hidden={!menuOpen}
        role="region"
        aria-label="Site navigation"
      >
        <div className="nav-mobile-inner">
          <div className="nav-mobile-eyebrow">Menu</div>
          <div className="nav-mobile-links">
            {navLink('Programs', '#programs')}
            {navLink('Our Work', '#process')}
            {navLink('Team', '#team')}
            {navLink('Find My Path', '#quiz')}
            {navLink('FAQ', '#faq')}
            {navLink('Resources', '', true)}
          </div>
          <a
            href={`${home}#quiz`}
            className="btn btn-primary"
            onClick={(e) => { if (!home) { e.preventDefault(); onQuiz(); } closeMenu(); }}
          >
            {ctaLabel}
          <span className="btn-arrow"><ArrowRight /></span>
        </a>
        </div>
      </div>
    </nav>
  );
};

// ───────────────────── Hero ─────────────────────
const Hero = ({ variant, ctaLabel, onQuiz, season = 'summer' }) => {
  const seasonData = (window.SEASONS && window.SEASONS[season]) || null;
  const heroVisualRef = React.useRef(null);
  // Variant: 'split' | 'centered' | 'editorial'
  if (variant === 'centered') {
    return (
      <section className="hero" id="top">
        <div className="container" style={{ textAlign: 'center', maxWidth: 1000 }}>
          <div className="eyebrow eyebrow-dot" style={{ justifyContent: 'center' }}>
            NATIONWIDE · VIRTUAL · ROOTED IN NH
          </div>
          <h1 className="hero-title display" style={{ textAlign: 'center' }}>
            Where medicine<br/>meets <em>the wild.</em>
          </h1>
          <p className="hero-lede" style={{ margin: '0 auto 40px' }}>
            Six precision programs. Thirty-plus specialty labs. An intentionally limited practice built around you — not a billing code.
          </p>
          <div className="hero-actions" style={{ justifyContent: 'center' }}>
            <a href="#quiz" className="btn btn-primary" onClick={(e) => { e.preventDefault(); onQuiz(); }}>
              {ctaLabel}
              <span className="btn-arrow"><ArrowRight /></span>
            </a>
          </div>
        </div>
      </section>
    );
  }

  if (variant === 'editorial') {
    return (
      <section className="hero" id="top" style={{ padding: '120px 0 40px' }}>
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 48, flexWrap: 'wrap', gap: 16 }}>
            <div className="eyebrow">VOL. VII · SPRING 2026 EDITION</div>
            <div className="mono" style={{ color: 'var(--eden-muted)' }}>NATIONWIDE TELEHEALTH · LITTLETON, NH</div>
          </div>
          <h1 className="hero-title display" style={{ fontSize: 'clamp(72px, 12vw, 180px)', textAlign: 'center', lineHeight: 0.9 }}>
            Healthcare,<br/><em>reimagined.</em>
          </h1>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 48, marginTop: 64, alignItems: 'end' }}>
            <p className="hero-lede">Precision cellular medicine, peptide therapy, and longevity science — delivered virtually with personalized plans and continuous support.</p>
            <div style={{ aspectRatio: '3/4', border: '1px solid var(--eden-hairline)', borderRadius: 4, position: 'relative', overflow: 'hidden' }}>
              <BotanicalPlaceholder label="HERO · WHITE MOUNTAINS" seed={42} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'flex-start' }}>
              <a href="#quiz" className="btn btn-primary" onClick={(e) => { e.preventDefault(); onQuiz(); }}>
                {ctaLabel}
                <span className="btn-arrow"><ArrowRight /></span>
              </a>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // Default: split — now full-bleed cinematic video, no right photo card
  return (
    <section className="hero hero-fullbleed" id="top">
      {seasonData && seasonData.heroVideo && window.HeroVideo ? (
        <window.HeroVideo src={seasonData.heroVideo} poster={seasonData.heroPoster} opacity={0.62} />
      ) : seasonData && seasonData.heroPoster ? (
        <KenBurnsImage src={seasonData.heroPoster} opacity={0.72} />
      ) : (
        <KenBurnsImage src={IMAGERY.hero} opacity={0.55} />
      )}
      <div className="hero-scrim hero-scrim-deep" />
      <DriftingParticles count={22} />
      <div className="container">
        <div className="hero-centered reveal-stagger" ref={heroVisualRef}>
          <div className="eyebrow eyebrow-dot">{seasonData ? seasonData.heroEyebrow : 'LITTLETON, NH · VIRTUAL FIRST'}</div>
          <h1 className="hero-title display hero-title-xl">
            Healthcare,<br/><em>reimagined.</em>
          </h1>
          <p className="hero-lede hero-lede-wide">
            Precision cellular medicine, peptide therapy, and longevity science — delivered with personalized plans and continuous support.
          </p>
          <div className="hero-actions">
            <a href="#quiz" className="btn btn-primary" onClick={(e) => { e.preventDefault(); onQuiz(); }}>
              {ctaLabel}
              <span className="btn-arrow"><ArrowRight /></span>
            </a>
            <div className="hero-cta-hint mono">
              <span aria-hidden="true">↓</span> 3-minute assessment, right on this page
            </div>
          </div>
          <div className="hero-states">
            <span className="hero-states-label">Virtual visits, currently licensed in</span>
            <span className="hero-states-list">
              <span className="state">NH</span>
              <span className="state">VT</span>
              <span className="state">MA</span>
              <span className="state">CT</span>
              <span className="state">NE</span>
              <span className="state">NY</span>
              <span className="state">MD</span>
            </span>
          </div>
        </div>
      </div>
      <div className="scroll-indicator" aria-hidden="true">
        <span className="mono">SCROLL</span>
        <span className="scroll-line" />
      </div>
    </section>
  );
};

// ───────────────────── Programs rotator ─────────────────────
const Programs = () => {
  const [active, setActive] = useState(0);
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(max-width: 768px)').matches
  );
  useEffect(() => {
    const mq = window.matchMedia('(max-width: 768px)');
    const onChange = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener('change', onChange) : mq.addListener(onChange);
    return () => mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener(onChange);
  }, []);
  const program = PROGRAMS[active];

  if (isMobile) {
    return (
      <section className="programs" id="programs">
        <div className="container">
          <div className="section-header reveal">
            <div>
              <div className="eyebrow">/ 01 · PROGRAMS</div>
              <h2 className="display" style={{ marginTop: 24 }}>
                Six paths, <em>one biology.</em>
              </h2>
            </div>
            <p className="section-header-aside">
              Every program is grounded in the same methodology: measure deeply, intervene precisely, support continuously.
            </p>
          </div>

          <div className="program-accordion reveal">
            {PROGRAMS.map((p, i) => {
              const isOpen = i === active;
              return (
                <div key={p.id} className={`program-acc-item ${isOpen ? 'open' : ''}`}>
                  <button
                    className="program-acc-header"
                    onClick={() => setActive(isOpen ? -1 : i)}
                    aria-expanded={isOpen}
                  >
                    <span className="program-acc-num">{p.num}</span>
                    <span className="program-acc-name">{p.short}</span>
                    <span className="program-acc-chevron" aria-hidden="true">{isOpen ? '–' : '+'}</span>
                  </button>
                  {isOpen && (
                    <div className="program-acc-body">
                      <div
                        className="program-acc-img"
                        style={{ backgroundImage: `url(${IMAGERY.programBg[p.id] || IMAGERY.programs})` }}
                        aria-hidden="true"
                      />
                      <div className="program-tag" style={{ marginTop: 24 }}>{p.tag}</div>
                      <h3 className="program-acc-title">{p.title}</h3>
                      <p className="program-desc">{p.desc}</p>
                      <ul className="program-pillars">
                        {p.pillars.map((pillar, j) => <li key={j}>{pillar}</li>)}
                      </ul>
                      <div className="program-cta-row">
                        <a href="#quiz" className="btn btn-primary" style={{ padding: '12px 22px', fontSize: 13 }}>
                          Take the assessment
                          <span className="btn-arrow"><ArrowRight /></span>
                        </a>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="programs" id="programs">
      <div className="container">
        <div className="section-header reveal">
          <div>
            <div className="eyebrow">/ 01 · PROGRAMS</div>
            <h2 className="display" style={{ marginTop: 24 }}>
              Six paths, <em>one biology.</em>
            </h2>
          </div>
          <p className="section-header-aside">
            Every program is grounded in the same methodology: measure deeply, intervene precisely, support continuously.
          </p>
        </div>

        <div className="program-viewer reveal">
          <div className="program-list" role="tablist">
            {PROGRAMS.map((p, i) => (
              <button
                key={p.id}
                className={`program-list-item ${i === active ? 'active' : ''}`}
                onClick={() => setActive(i)}
                role="tab"
                aria-selected={i === active}
              >
                <span className="program-list-num">{p.num}</span>
                <span className="program-list-name">{p.short}</span>
              </button>
            ))}
          </div>
          <div className="program-detail">
            <div className="program-content fade-in" key={program.id}>
              <div className="program-tag">{program.tag}</div>
              <h3 className="program-title">{program.title}</h3>
              <p className="program-desc">{program.desc}</p>
              <ul className="program-pillars">
                {program.pillars.map((p, i) => <li key={i}>{p}</li>)}
              </ul>
              <div className="program-cta-row">
                <a href="#quiz" className="btn btn-primary" style={{ padding: '12px 22px', fontSize: 13 }}>
                  Take the assessment
                  <span className="btn-arrow"><ArrowRight /></span>
                </a>
              </div>
            </div>
            <div className="program-visual fade-in" key={`v-${program.id}`}>
              <div
                className="program-bg-img"
                style={{ backgroundImage: `url(${IMAGERY.programBg[program.id] || IMAGERY.programs})` }}
              />
              <div className="program-visual-label">{`PROGRAM · ${program.short.toUpperCase()}`}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ───────────────────── Process ─────────────────────
const Process = () => (
  <section className="process" id="process">
    <div className="container">
      <div className="section-header reveal">
        <div>
          <div className="eyebrow">/ 02 · OUR WORK</div>
          <h2 className="display" style={{ marginTop: 24 }}>
            How care <em>actually</em> works here.
          </h2>
        </div>
        <p className="section-header-aside">
          Four steps, no 15-minute appointments, no billing-code gymnastics. Just time, precision, and a plan that evolves with you.
        </p>
      </div>
      <div className="process-steps reveal-stagger">
        {PROCESS_STEPS.map((step, i) => (
          <div key={i} className="process-step">
            <div className="process-step-num">{step.num}</div>
            <h3 className="process-step-title display">{step.title}</h3>
            <p className="process-step-desc">{step.desc}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ───────────────────── Quiz ─────────────────────
// Native in-page quiz: scores answers, collects contact info, submits to Eden.
// Submission uses FormSubmit.co (no backend needed) — change CLINIC_EMAIL below.
const CLINIC_EMAIL = "hello@edenwellnessclinic.com";
// FormSubmit hashed endpoint (activated). The hash hides the email from page source
// while still routing to CLINIC_EMAIL on the backend.
const FORM_ENDPOINT = `https://formsubmit.co/ajax/68dad4f212a63cac6c1e6f8f409d1b51`;

const Quiz = React.forwardRef((props, ref) => {
  // steps: 0..N-1 = questions, N = contact form, N+1 = success
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [contact, setContact] = useState({ name: '', email: '', phone: '', notes: '' });
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const total = QUIZ_QUESTIONS.length;
  const contactStep = total;
  const doneStep = total + 1;
  const isContact = step === contactStep;
  const isDone = step === doneStep;

  // Which questions allow multi-select. Per product spec: every question except the
  // financial / budget question accepts up to two answers.
  const isMulti = (q) => q && q.field !== 'budget';
  const MAX_MULTI = 2;

  // Normalize an answers[i] value to an array of options (legacy single-select answers
  // were stored as a single object; we coerce on read so the rest of the math stays uniform).
  const optsFor = (i) => {
    const a = answers[i];
    if (!a) return [];
    return Array.isArray(a) ? a : [a];
  };

  // ── Compute the program match (only score-kind questions matter for ranking)
  const computeMatch = () => {
    const scores = {};
    PROGRAMS.forEach(p => { scores[p.id] = 0; });
    QUIZ_QUESTIONS.forEach((q, i) => {
      optsFor(i).forEach(opt => {
        if (!opt || !opt.weight) return;
        Object.entries(opt.weight).forEach(([k, v]) => { scores[k] = (scores[k] || 0) + v; });
      });
    });
    const ranked = Object.entries(scores).sort((a, b) => b[1] - a[1]);
    const best = PROGRAMS.find(p => p.id === ranked[0][0]) || PROGRAMS[0];
    const second = PROGRAMS.find(p => p.id === ranked[1][0]);
    return { best, second, scores: ranked };
  };

  // ── Compute the *outcome* of the quiz (qualified, waitlist, low-budget, consult)
  const computeOutcome = () => {
    let stateOpts = [], budgetOpt = null, expectOpts = [];
    QUIZ_QUESTIONS.forEach((q, i) => {
      const opts = optsFor(i);
      if (q.field === 'state') stateOpts = opts;
      if (q.field === 'budget') budgetOpt = opts[0]; // single-select
      if (q.field === 'expectations') expectOpts = opts;
    });

    if (stateOpts.some(o => o.qualified === 'waitlist')) return 'waitlist_state';
    if (budgetOpt && budgetOpt.qualified === 'low_budget') return 'low_budget';
    if (budgetOpt && budgetOpt.qualified === 'consult') return 'consult';
    if (expectOpts.some(o => o.commitment === 'low') && (!budgetOpt || budgetOpt.qualified !== true)) return 'consult';
    return 'qualified';
  };

  const match = computeMatch();
  const outcome = computeOutcome();

  const select = (opt) => {
    const q = QUIZ_QUESTIONS[step];
    if (!isMulti(q)) {
      // Single-select (budget): set + auto-advance.
      setAnswers({ ...answers, [step]: [opt] });
      setTimeout(() => setStep(s => Math.min(s + 1, contactStep)), 220);
      return;
    }
    // Multi-select: toggle, cap at MAX_MULTI (drop oldest when over).
    const current = optsFor(step);
    const idx = current.findIndex(o => o.label === opt.label);
    let next;
    if (idx >= 0) {
      next = current.filter(o => o.label !== opt.label);
    } else if (current.length >= MAX_MULTI) {
      next = [...current.slice(1), opt];
    } else {
      next = [...current, opt];
    }
    setAnswers({ ...answers, [step]: next });
  };

  const advance = () => {
    if (optsFor(step).length === 0) return;
    setStep(s => Math.min(s + 1, contactStep));
  };

  const reset = () => {
    setStep(0);
    setAnswers({});
    setContact({ name: '', email: '', phone: '', notes: '' });
    setSubmitError(null);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!contact.name || !contact.email) return;
    setSubmitting(true);
    setSubmitError(null);

    const answersSummary = QUIZ_QUESTIONS.map((q, i) => {
      const opts = optsFor(i);
      const labels = opts.length ? opts.map(o => o.label).join('  +  ') : '(no answer)';
      return `Q${i + 1} [${q.section || ''}] ${q.q}\n   → ${labels}`;
    }).join('\n\n');

    const scoreSummary = match.scores
      .map(([id, score]) => {
        const prog = PROGRAMS.find(p => p.id === id);
        return `   ${prog?.short}: ${score}`;
      }).join('\n');

    const outcomeLabels = {
      qualified: '✓ QUALIFIED — ready to book',
      consult: '⚠ NEEDS FIT CONVERSATION — budget or expectations gap',
      low_budget: '✗ UNDER-BUDGET — newsletter / library follow-up',
      waitlist_state: '◷ OUT-OF-STATE WAITLIST — licensure pending',
    };

    const payload = {
      _subject: `Eden Lead [${outcomeLabels[outcome]}] — ${contact.name} → ${match.best.short}`,
      _template: "table",
      _captcha: "false",
      Outcome: outcomeLabels[outcome],
      Name: contact.name,
      Email: contact.email,
      Phone: contact.phone || '(not provided)',
      "Best-Fit Program": match.best.short,
      "Secondary Match": match.second?.short || '',
      "Program Scores": scoreSummary,
      "Quiz Answers": answersSummary,
      "Additional Notes": contact.notes || '(none)',
      "Submitted": new Date().toLocaleString(),
    };

    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error(`Submission failed (${res.status})`);
      setStep(doneStep);
    } catch (err) {
      setSubmitError(err.message || "Something went wrong. Please try again or call us directly.");
    } finally {
      setSubmitting(false);
    }
  };

  const pct = isDone ? 100 : isContact ? 92 : Math.round(((step) / (total + 1)) * 92);

  // Has the previous question changed section?
  const currentQ = !isContact && !isDone ? QUIZ_QUESTIONS[step] : null;
  const prevQ = step > 0 ? QUIZ_QUESTIONS[step - 1] : null;
  const showSectionHeader = currentQ && (!prevQ || prevQ.section !== currentQ.section);

  return (
    <section className="quiz-section" id="quiz" ref={ref}>
      <div className="container">
        <div className="quiz-wrap">
          <div className="quiz-intro">
            <div className="eyebrow">/ 03 · FIND YOUR PATH</div>
            <h2>
              Begin with the <em>assessment.</em>
            </h2>
            <p>
              Every Eden patient starts here. This is how we make sure we're the right fit before either of us spends a dollar — and how we get a real picture of what you actually need.
            </p>
            <ul className="quiz-intro-list">
              <li><span className="quiz-intro-list-num">01</span><span>Three sections, about 3 minutes</span></li>
              <li><span className="quiz-intro-list-num">02</span><span>Reviewed personally by the Eden Wellness team</span></li>
              <li><span className="quiz-intro-list-num">03</span><span>Personal follow-up within 1 business day</span></li>
              <li><span className="quiz-intro-list-num">04</span><span>Booking only opens after we confirm fit</span></li>
            </ul>
          </div>

          <div className="quiz-card">
            <div className="quiz-progress">
              <span>
                {isDone ? 'COMPLETE' : isContact ? 'YOUR DETAILS' : `Question ${step + 1} / ${total}`}
              </span>
              <div className="quiz-progress-bar">
                <div className="quiz-progress-fill" style={{ width: `${pct}%` }} />
              </div>
              <span>{pct}%</span>
            </div>

            {/* Questions */}
            {!isContact && !isDone && (
              <React.Fragment key={step}>
                {currentQ.section && (
                  <div className="quiz-section-tag">
                    <span className="quiz-section-tag-num">SECTION {['WHAT BRINGS YOU HERE','A LITTLE ABOUT YOU','INVESTMENT & FIT'].indexOf(currentQ.section) + 1} / 3</span>
                    <span className="quiz-section-tag-name">{currentQ.section}</span>
                  </div>
                )}
                <h3 className="quiz-question display">{currentQ.q}</h3>
                <p className="quiz-sub">
                  {currentQ.sub}
                  {isMulti(currentQ) && (
                    <span className="quiz-sub-multi"> Pick up to two.</span>
                  )}
                </p>
                <div className="quiz-options">
                  {currentQ.options.map((opt, i) => {
                    const selected = optsFor(step).some(o => o.label === opt.label);
                    return (
                      <button
                        key={i}
                        className={`quiz-option ${selected ? 'selected' : ''}`}
                        onClick={() => select(opt)}
                      >
                        <span className="quiz-option-check"><CheckIcon /></span>
                        <span>{opt.label}</span>
                      </button>
                    );
                  })}
                </div>
                <div className="quiz-nav">
                  <button
                    className="btn btn-ghost"
                    disabled={step === 0}
                    onClick={() => setStep(s => Math.max(s - 1, 0))}
                    style={{ opacity: step === 0 ? 0.3 : 1, padding: '12px 22px', fontSize: 13 }}
                  >
                    ← Back
                  </button>
                  {isMulti(currentQ) ? (
                    <button
                      className="btn btn-primary"
                      onClick={advance}
                      disabled={optsFor(step).length === 0}
                      style={{ padding: '12px 22px', fontSize: 13, opacity: optsFor(step).length === 0 ? 0.4 : 1 }}
                    >
                      Continue
                      <span className="btn-arrow"><ArrowRight /></span>
                    </button>
                  ) : (
                    <div className="mono" style={{ color: 'var(--eden-muted)', alignSelf: 'center' }}>
                      Choose an option to continue
                    </div>
                  )}
                </div>
              </React.Fragment>
            )}

            {/* Contact form */}
            {isContact && (
              <form onSubmit={submit} className="fade-in" style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
                <div className="quiz-result-tag">FINAL STEP · YOUR DETAILS</div>
                <h3 className="quiz-result-title" style={{ fontSize: 32 }}>Where should we send your match?</h3>
                <p className="quiz-sub" style={{ marginBottom: 28 }}>
                  Our team personally reviews every assessment. We'll be in touch within one business day with your match summary and the right next step.
                </p>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 20 }}>
                  <input
                    className="quiz-input"
                    type="text"
                    placeholder="Full name *"
                    required
                    value={contact.name}
                    onChange={e => setContact({ ...contact, name: e.target.value })}
                  />
                  <input
                    className="quiz-input"
                    type="email"
                    placeholder="Email address *"
                    required
                    value={contact.email}
                    onChange={e => setContact({ ...contact, email: e.target.value })}
                  />
                  <input
                    className="quiz-input"
                    type="tel"
                    placeholder="Phone (optional)"
                    value={contact.phone}
                    onChange={e => setContact({ ...contact, phone: e.target.value })}
                  />
                  <textarea
                    className="quiz-input"
                    placeholder="Anything else we should know? Medical history, current meds, specific concerns… (optional)"
                    rows={3}
                    value={contact.notes}
                    onChange={e => setContact({ ...contact, notes: e.target.value })}
                  />
                </div>

                {submitError && (
                  <div style={{ color: '#E8A5A5', fontSize: 13, marginBottom: 16, fontFamily: 'JetBrains Mono, monospace' }}>
                    {submitError}
                  </div>
                )}

                <div className="quiz-result-actions">
                  <button
                    type="submit"
                    className="btn btn-primary"
                    disabled={submitting || !contact.name || !contact.email}
                    style={{ opacity: submitting ? 0.6 : 1 }}
                  >
                    {submitting ? 'Sending…' : 'Send my assessment'}
                    <span className="btn-arrow"><ArrowRight /></span>
                  </button>
                  <button type="button" className="btn btn-ghost" onClick={() => setStep(s => s - 1)}>← Back</button>
                </div>
                <div className="mono" style={{ color: 'var(--eden-muted)', fontSize: 11, marginTop: 20 }}>
                  Your responses are sent directly to {CLINIC_EMAIL}. We never share your information.
                </div>
              </form>
            )}

            {/* Outcome screens */}
            {isDone && outcome === 'qualified' && (
              <div className="quiz-result fade-in">
                <div className="quiz-result-tag" style={{ color: 'var(--eden-phosphor)' }}>✓ ASSESSMENT RECEIVED</div>
                <h3 className="quiz-result-title">Thank you, <em>{contact.name.split(' ')[0]}.</em></h3>
                <p className="quiz-result-desc">
                  Your assessment is in front of our team. Based on your answers, the program that looks like the closest fit is <strong style={{ color: 'var(--eden-phosphor)' }}>{match.best.short}</strong> — but we won't make any recommendations until a clinician has reviewed your responses in full.
                </p>
                <div className="quiz-next-steps">
                  <div className="quiz-next-steps-label">What happens next</div>
                  <ol className="quiz-next-steps-list">
                    <li>
                      <span className="quiz-next-step-num">01</span>
                      <div>
                        <strong>Clinical review.</strong> A member of the Eden Wellness team reviews your assessment, your goals, and any flags you noted.
                      </div>
                    </li>
                    <li>
                      <span className="quiz-next-step-num">02</span>
                      <div>
                        <strong>Personal outreach within one business day.</strong> We'll reach out by phone or email — whichever you prefer — to discuss what we saw and confirm whether {match.best.short} is the right starting point.
                      </div>
                    </li>
                    <li>
                      <span className="quiz-next-step-num">03</span>
                      <div>
                        <strong>If we're a fit, we'll schedule your Discovery visit together.</strong> Booking happens during that conversation, not before.
                      </div>
                    </li>
                  </ol>
                </div>
                <div className="quiz-result-actions">
                  <a href="Resources.html" className="btn btn-primary">
                    Read the Library while you wait
                    <span className="btn-arrow"><ArrowRight /></span>
                  </a>
                  <button className="btn btn-ghost" onClick={reset}>Start over</button>
                </div>
              </div>
            )}

            {isDone && outcome === 'consult' && (
              <div className="quiz-result fade-in">
                <div className="quiz-result-tag" style={{ color: 'var(--eden-amber)' }}>✓ ASSESSMENT RECEIVED</div>
                <h3 className="quiz-result-title">Thank you, <em>{contact.name.split(' ')[0]}.</em></h3>
                <p className="quiz-result-desc">
                  Your assessment is in front of our team. There are real, meaningful ways we can help you get started — and we'd like to talk through them with you so you land in the right place from day one.
                </p>
                <p className="quiz-result-desc" style={{ marginTop: -6 }}>
                  Many of our patients begin with a focused, lower-investment starting point and build from there as their results compound. A short conversation is the best way to map out what makes sense for you.
                </p>
                <div className="program-pillars" style={{ marginBottom: 32, marginTop: 24 }}>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-amber)', marginTop: 10, flexShrink: 0 }}/>
                    We'll reach out within one business day to schedule a complimentary 15-minute call.
                  </li>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-amber)', marginTop: 10, flexShrink: 0 }}/>
                    We'll walk you through the most effective entry points and help you choose the one that fits.
                  </li>
                </div>
                <div className="quiz-result-actions">
                  <a href="Resources.html" className="btn btn-primary">
                    Read the Library while you wait
                    <span className="btn-arrow"><ArrowRight /></span>
                  </a>
                  <button className="btn btn-ghost" onClick={reset}>Start over</button>
                </div>
              </div>
            )}

            {isDone && outcome === 'low_budget' && (
              <div className="quiz-result fade-in">
                <div className="quiz-result-tag" style={{ color: 'var(--eden-bone-dim)' }}>✓ THANKS FOR REACHING OUT</div>
                <h3 className="quiz-result-title">We hear you, <em>{contact.name.split(' ')[0]}.</em></h3>
                <p className="quiz-result-desc">
                  Concierge functional medicine is a meaningful financial commitment. Right now, the work we do isn't a fit for every budget — and we'd rather be honest about that than have you over-extend.
                </p>
                <p className="quiz-result-desc" style={{ marginTop: -6 }}>
                  What we can offer: free, in-depth, clinician-written articles on the same science we practice. No fluff, no upsell — the same things we'd tell our own patients.
                </p>
                <div className="program-pillars" style={{ marginBottom: 32, marginTop: 24 }}>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-moss)', marginTop: 10, flexShrink: 0 }}/>
                    We'll add you to our list — no spam, no automated funnels.
                  </li>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-moss)', marginTop: 10, flexShrink: 0 }}/>
                    If your situation changes, the door is always open.
                  </li>
                </div>
                <div className="quiz-result-actions">
                  <a href="Resources.html" className="btn btn-primary">
                    Open the Library
                    <span className="btn-arrow"><ArrowRight /></span>
                  </a>
                  <button className="btn btn-ghost" onClick={reset}>Start over</button>
                </div>
              </div>
            )}

            {isDone && outcome === 'waitlist_state' && (
              <div className="quiz-result fade-in">
                <div className="quiz-result-tag" style={{ color: 'var(--eden-amber)' }}>◷ ON THE WAITLIST</div>
                <h3 className="quiz-result-title">Almost, <em>{contact.name.split(' ')[0]}.</em></h3>
                <p className="quiz-result-desc">
                  We can't legally treat you in your state yet — telehealth licensure is a real thing, and we're not going to bend it. But your assessment is on file.
                </p>
                <p className="quiz-result-desc" style={{ marginTop: -6 }}>
                  We're actively expanding into more states. The moment we can take you on, you'll be the first to know.
                </p>
                <div className="program-pillars" style={{ marginBottom: 32, marginTop: 24 }}>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-amber)', marginTop: 10, flexShrink: 0 }}/>
                    Currently licensed: NH, VT, MA, CT, NE, NY, MD
                  </li>
                  <li style={{ listStyle: 'none', display: 'flex', alignItems: 'flex-start', gap: 14, fontSize: 14, color: 'var(--eden-bone-dim)', padding: '6px 0' }}>
                    <span style={{ width: 14, height: 1, background: 'var(--eden-amber)', marginTop: 10, flexShrink: 0 }}/>
                    Your matched program is <strong style={{ color: 'var(--eden-phosphor)' }}>{match.best.short}</strong> — we'll keep you posted as we expand.
                  </li>
                </div>
                <div className="quiz-result-actions">
                  <a href="Resources.html" className="btn btn-primary">
                    Read the Library while you wait
                    <span className="btn-arrow"><ArrowRight /></span>
                  </a>
                  <button className="btn btn-ghost" onClick={reset}>Start over</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
});

// ───────────────────── Science ─────────────────────
const Science = () => (
  <section className="science" id="science">
    <div className="container">
      <div className="section-header reveal">
        <div>
          <div className="eyebrow">/ 04 · THE SCIENCE</div>
          <h2 className="display" style={{ marginTop: 24 }}>
            Functional medicine, <em>precise and personal.</em>
          </h2>
        </div>
        <p className="section-header-aside">
          Our methods are credentialed, our labs are world-class, and our protocols follow the same evidence base used by top longevity practitioners globally.
        </p>
      </div>
      <div className="science-grid reveal-stagger">
        {SCIENCE.map((s, i) => (
          <div key={i} className="science-card">
            <div className="science-card-icon">
              {i === 0 && <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.2"/><circle cx="9" cy="9" r="2" fill="currentColor"/></svg>}
              {i === 1 && <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M4 4 L 4 14 M 9 2 L 9 16 M 14 6 L 14 12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>}
              {i === 2 && <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 9 L 6 9 L 7.5 5 L 10.5 13 L 12 9 L 15 9" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </div>
            <h3>{s.title}</h3>
            <p>{s.desc}</p>
            <div className="science-card-ref">{s.ref}</div>
          </div>
        ))}
      </div>
      <div className="lab-strip">
        <div className="lab-strip-label">CLINICAL PARTNERS</div>
        <div className="lab-strip-items">
          <span>Dutch</span>
          <span>GI-MAP</span>
          <span>Cleveland HeartLab</span>
          <span>TruDiagnostic</span>
          <span>Genova</span>
          <span>Boston Heart</span>
          <span>Quicksilver</span>
          <span>ZRT</span>
        </div>
      </div>
    </div>
  </section>
);

// ───────────────────── Team ─────────────────────
// Photo with graceful fallback. We HEAD-check the image first so a missing file
// never triggers a console resource error from a broken <img> tag.
const TeamPhoto = ({ src, name, seed }) => {
  const [status, setStatus] = React.useState(src ? 'checking' : 'failed');
  React.useEffect(() => {
    if (!src) return;
    let cancelled = false;
    fetch(src, { method: 'HEAD' })
      .then(r => { if (!cancelled) setStatus(r.ok ? 'ok' : 'failed'); })
      .catch(() => { if (!cancelled) setStatus('failed'); });
    return () => { cancelled = true; };
  }, [src]);
  if (status === 'ok') return <img src={src} alt={name} className="team-photo-img" />;
  return <TeamPlaceholder name={name} seed={seed} />;
};

const Team = () => (
  <section className="team" id="team">
    <div className="container">
      <div className="section-header reveal">
        <div>
          <div className="eyebrow">/ 05 · YOUR GUIDES</div>
          <h2 className="display" style={{ marginTop: 24 }}>
            Guided by those <em>who understand.</em>
          </h2>
        </div>
        <p className="section-header-aside">
          Clinical excellence paired with a genuine heart for transformation. Our team is intentionally small so every relationship runs deep.
        </p>
      </div>
      <div className="team-list">
        {TEAM.map((m, i) => (
          <article key={i} className={`team-member ${i % 2 === 1 ? 'reverse' : ''}`}>
            <div className="team-photo reveal">
              <TeamPhoto src={m.photo} name={m.name} seed={i * 17 + 5} />
            </div>
            <div>
              <div className="team-role">{m.role}</div>
              <h3 className="team-name">{m.name}</h3>
              <div className="team-suffix">{m.suffix}</div>
              <p className="team-bio">{m.bio}</p>
              {m.bio2 && <p className="team-bio" style={{ marginTop: 16 }}>{m.bio2}</p>}
              <div className="team-creds" style={{ marginTop: 28 }}>
                {m.creds.map((c, j) => <span key={j} className="cred">{c}</span>)}
              </div>
            </div>
          </article>
        ))}
      </div>
    </div>
  </section>
);

// ───────────────────── Testimonials ─────────────────────
const Testimonials = () => (
  <section className="testimonials">
    <div className="container">
      <div className="section-header reveal">
        <div>
          <div className="eyebrow">/ 06 · PATIENT STORIES</div>
          <h2 className="display" style={{ marginTop: 24 }}>
            In their own <em>words.</em>
          </h2>
        </div>
      </div>
      <div className="testimonials-grid reveal-stagger">
        {TESTIMONIALS.map((t, i) => (
          <div key={i} className="testimonial">
            <p className="testimonial-quote">{t.quote}</p>
            <div className="testimonial-meta">
              <span className="testimonial-meta-name">— {t.name}</span>
              <span>{t.meta}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ───────────────────── FAQ ─────────────────────
const FaqSection = () => {
  const [openIdx, setOpenIdx] = useState(0);
  return (
    <section className="faq" id="faq">
      <div className="container">
        <div className="section-header reveal" style={{ justifyContent: 'center', textAlign: 'center', flexDirection: 'column', alignItems: 'center' }}>
          <div className="eyebrow">/ 07 · QUESTIONS</div>
          <h2 className="display" style={{ marginTop: 24 }}>
            Good questions, <em>answered.</em>
          </h2>
        </div>
        <div className="faq-list reveal">
          {FAQ.map((f, i) => (
            <div key={i} className={`faq-item ${openIdx === i ? 'open' : ''}`} onClick={() => setOpenIdx(openIdx === i ? -1 : i)}>
              <div className="faq-q">
                <span>{f.q}</span>
                <span className="faq-toggle"><Plus /></span>
              </div>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ───────────────────── Final CTA ─────────────────────
const FinalCTA = ({ ctaLabel, onQuiz }) => (
  <section className="final-cta">
    <ParallaxImage src={IMAGERY.finalCta} speed={0.28} scale={1.2} overlay={0.78} />
    <DriftingParticles count={12} />
    <div className="final-cta-bg"></div>
    <div className="container reveal">
      <div className="eyebrow eyebrow-dot" style={{ justifyContent: 'center' }}>
        ACCEPTING NEW PATIENTS · LIMITED AVAILABILITY
      </div>
      <h2>Your <em>next chapter</em><br/>starts with one conversation.</h2>
      <p>Most patients tell us they wish they'd started years earlier. We'd rather you start today.</p>
      <div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a href="#quiz" className="btn btn-primary" onClick={(e) => { e.preventDefault(); onQuiz(); }}>
          {ctaLabel}
          <span className="btn-arrow"><ArrowRight /></span>
        </a>
      </div>
    </div>
  </section>
);

// ───────────────────── Footer ─────────────────────
// `home` prefix is empty on homepage, "index.html" elsewhere — so #-anchors navigate cross-page.
const Footer = ({ home = '' }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div>
          <div className="footer-logo">
            <EdenLogoMark size={120} />
          </div>
          <p className="footer-tag">Functional medicine and longevity care delivered virtually across New England, New York and Maryland. Rooted in the White Mountains of New Hampshire.</p>
        </div>
        <div className="footer-col">
          <h4>Programs</h4>
          {PROGRAMS.map(p => <a key={p.id} href={`${home}#programs`}>{p.short}</a>)}
        </div>
        <div className="footer-col">
          <h4>Clinic</h4>
          <a href={`${home}#process`}>Our Work</a>
          <a href={`${home}#team`}>Team</a>
          <a href={`${home}#science`}>Science</a>
          <a href={`${home}#faq`}>FAQ</a>
        </div>
        <div className="footer-col">
          <h4>Home Clinic</h4>
          <p>16 Mill Street #3<br/>Littleton, NH 03561</p>
          <p style={{ marginTop: 10, color: 'var(--eden-bone-dim)' }}>Virtual visits in NH · VT · MA · CT · NE · NY · MD</p>
          <a href="tel:6039327908">(603) 932-7908</a>
          <a href="mailto:hello@edenwellnessclinic.com">hello@edenwellnessclinic.com</a>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 EDEN WELLNESS · LITTLETON, NH · VIRTUAL IN SELECT STATES</span>
        <span className="footer-legal">
          <a href="legal/privacy.html">Privacy Policy</a>
          <span aria-hidden="true">·</span>
          <a href="legal/terms.html">Terms &amp; Disclaimer</a>
          <span aria-hidden="true">·</span>
          <a href="legal/accessibility.html">Accessibility</a>
        </span>
      </div>
    </div>
  </footer>
);

Object.assign(window, { Nav, Hero, Programs, Process, Quiz, Science, Team, Testimonials, FaqSection, FinalCTA, Footer });

// ───────────────────── Season chips + ambient controls bar ─────────────────────
const SeasonChips = ({ season, onChange }) => {
  const S = window.SEASONS || {};
  const keys = ['spring', 'summer', 'autumn', 'winter'];
  return (
    <div className="season-chips" role="tablist" aria-label="Season">
      {keys.map(k => (
        <button
          key={k}
          role="tab"
          aria-selected={season === k}
          className={`season-chip ${season === k ? 'active' : ''}`}
          onClick={() => onChange(k)}
          style={{ '--dot': (S[k] && S[k].accent) || '#888' }}
          title={(S[k] && S[k].label) || k}
        >
          <span className="season-chip-dot" style={{ background: (S[k] && S[k].accent) || '#888' }} />
          {(S[k] && S[k].label) || k}
        </button>
      ))}
    </div>
  );
};

const AmbientControls = ({ season, onSeasonChange }) => (
  <div className="ambient-controls">
    <SeasonChips season={season} onChange={onSeasonChange} />
    {window.AudioToggle ? <window.AudioToggle /> : null}
  </div>
);

Object.assign(window, { SeasonChips, AmbientControls });
