/* facts-sections.jsx — editorial sections composed of charts + copy */

const { useState: useStateJS, useEffect: useEffectJS, useRef: useRefJS } = React;
// alias to expected names
const useState = useStateJS;
const useEffect = useEffectJS;
const useRef = useRefJS;

const D = window.FACTS_DATA;

/* ─── 01 — Hero ─── */
function JHero(){
  return (
    <section className="j-hero">
      <div className="ed-meta-row">
        <span><span className="ed-meta-num">VOL. 01</span> &nbsp;·&nbsp; THE JAW ISSUE</span>
        <span>SOMAFACE&nbsp;/&nbsp;TMJDIRECTORY FACTS</span>
        <span>SPRING 2026</span>
      </div>
      <h1 className="j-hero-title">
        A jaw <span className="ital">epidemic</span><br/>
        nobody is <span className="ital">talking</span> about.
      </h1>
      <div className="j-hero-grid">
        <div className="j-hero-stat">
          <div className="j-hero-stat-num"><Counter to={D.hero.globalAdult} suffix="%" /></div>
          <div className="j-hero-stat-label">of adults worldwide live with some form of TMD</div>
          <div className="j-hero-stat-cite">Valesan et al., 2021</div>
        </div>
        <div className="j-hero-stat">
          <div className="j-hero-stat-num"><Counter to={D.hero.globalProjected} suffix="%" delay={300}/></div>
          <div className="j-hero-stat-label">projected prevalence by 2050</div>
          <div className="j-hero-stat-cite">Zieliński et al., 2025</div>
        </div>
        <div className="j-hero-stat">
          <div className="j-hero-stat-num"><Counter to={D.hero.femaleRatio} decimals={2} suffix="×" delay={600}/></div>
          <div className="j-hero-stat-label">more likely in women than men</div>
          <div className="j-hero-stat-cite">Almashraqi et al., 2025</div>
        </div>
        <div className="j-hero-stat">
          <div className="j-hero-stat-num"><Counter to={D.hero.seekTreatment} suffix="%" delay={900}/></div>
          <div className="j-hero-stat-label">of those affected ever seek treatment</div>
          <div className="j-hero-stat-cite">NIDCR, 2018</div>
        </div>
      </div>
      <p className="j-hero-deck">
        Your jaw opens and closes around 2,000 times a day. For roughly one in three adults, that simple motion comes with a click, an ache, a pop, or a pain that radiates into the head, neck, and ears. This is what we know about why — and who is bearing it.
      </p>
    </section>
  );
}

/* ─── 02 — Scrolly definitions: TMJ vs TMJD vs TMD ─── */
function JDefinitions(){
  const [active, setActive] = useState(0);
  const containerRef = useRef(null);
  const stepRefs = useRef([]);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setActive(parseInt(e.target.dataset.idx));
        }
      });
    }, { rootMargin: "-45% 0px -45% 0px", threshold: 0 });
    stepRefs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <section className="j-section j-defs">
      <div className="j-section-head">
        <div className="ed-num">§ 01<strong>The Words</strong></div>
        <h2 className="ed-section-title">Three letters, three words,
          <br/><span className="ital">one stubborn confusion.</span></h2>
      </div>
      <div className="j-defs-stage" ref={containerRef}>
        <div className="j-defs-sticky">
          {D.definitions.map((d, i) => (
            <div key={d.abbr} className={`j-def-card ${active === i ? 'on' : ''}`}>
              <div className="j-def-tag">{d.tag}</div>
              <div className="j-def-abbr">{d.abbr}</div>
              <div className="j-def-full">{d.full}</div>
              <div className="j-def-what">{d.what}</div>
              <p className="j-def-body">{d.body}</p>
            </div>
          ))}
        </div>
        <div className="j-defs-scroll">
          {D.definitions.map((d, i) => (
            <div key={d.abbr} className="j-def-step" data-idx={i}
                 ref={el => stepRefs.current[i] = el}>
              <div className="j-def-step-num">0{i+1}</div>
              <div className="j-def-step-label">{d.abbr}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="j-defs-tldr">
        <span className="j-tldr-label">TL;DR</span>
        <p>Everyone has a <strong>TMJ</strong>. <strong>TMD</strong> means something is wrong with it. <strong>TMJD</strong> usually means the same thing as TMD — clinicians just disagree on the acronym. We use <strong>TMD</strong> through this issue.</p>
      </div>
    </section>
  );
}

/* ─── 03 — Global prevalence ─── */
function JGlobal(){
  return (
    <section className="j-section">
      <div className="j-section-head">
        <div className="ed-num">§ 02<strong>The World</strong></div>
        <h2 className="ed-section-title">It's <span className="ital">everywhere.</span> Some places more than others.</h2>
      </div>
      <p className="j-deck">A 2025 meta-analysis of 27 studies and 20,971 subjects across five continents found wildly different prevalence depending on where you live — but everywhere, the rate is high enough to call this a quietly global problem.</p>
      <WorldDotMap data={D.globalByContinent} />
      <div className="j-twin">
        <div>
          <div className="j-eyebrow">By continent</div>
          <BarChart data={D.globalByContinent} max={45} barColor="var(--accent-ink)" labelWidth={180}/>
        </div>
        <div className="j-twin-aside">
          <p>Why the gap between Europe (33.8%) and North America (19.4%)?</p>
          <p>Mostly diagnostic culture. North American clinicians under-diagnose TMD — many doctors aren't trained to recognize it, and patients are more often told "it's just stress." European studies use stricter screening protocols (DC/TMD), so they catch more.</p>
          <p className="j-twin-cite">— Almashraqi et al., 2025</p>
        </div>
      </div>
    </section>
  );
}

/* ─── 04 — Gender gap ─── */
function JGender(){
  return (
    <section className="j-section j-section-paper">
      <div className="j-section-head">
        <div className="ed-num">§ 03<strong>The Gap</strong></div>
        <h2 className="ed-section-title">The pain isn't <span className="ital">equal-opportunity.</span></h2>
      </div>
      <div className="j-gender-grid">
        <div className="j-gender-figure">
          <div className="j-gender-row">
            <div className="j-gender-label">Women</div>
            <div className="j-gender-bar female">
              <Counter to={D.genderGap.female} suffix="%" />
            </div>
          </div>
          <div className="j-gender-row">
            <div className="j-gender-label">Men</div>
            <div className="j-gender-bar male" style={{ width: `${(D.genderGap.male/D.genderGap.female)*100}%` }}>
              <Counter to={D.genderGap.male} suffix="%" delay={400}/>
            </div>
          </div>
          <div className="j-gender-ratio">
            <Counter to={D.genderGap.ratio} decimals={2} suffix="×" delay={800}/>
            <div>more likely</div>
          </div>
        </div>
        <div className="j-gender-prose">
          <p>It isn't subtle. Across every continent, every age band, every diagnostic protocol — women are diagnosed with TMD at roughly <strong>1.75 times</strong> the rate of men. The gap is widest between ages 20 and 50.</p>
          <p>Why? Researchers have a few converging answers, none of them complete on their own:</p>
          <ul className="j-list">
            <li><strong>Hormones.</strong> Estrogen receptors line the temporomandibular joint. Symptoms track with menstrual cycle, pregnancy, oral contraceptives, and — as we'll see — perimenopause.</li>
            <li><strong>Anatomy.</strong> Women on average have smaller condyles, thinner discs, and more flexible ligaments — all things that load the joint differently.</li>
            <li><strong>Comorbid pain conditions.</strong> Migraine, fibromyalgia, and IBS — all more common in women — share central-pain pathways with TMD.</li>
            <li><strong>Diagnostic bias.</strong> Women's pain is more readily believed to be psychosomatic. They <em>are</em> diagnosed more, but men may simply be diagnosed less.</li>
          </ul>
        </div>
      </div>
    </section>
  );
}

/* ─── 05 — Age pyramid ─── */
function JAge(){
  return (
    <section className="j-section">
      <div className="j-section-head">
        <div className="ed-num">§ 04<strong>The Curve</strong></div>
        <h2 className="ed-section-title">A young person's <span className="ital">condition.</span></h2>
      </div>
      <p className="j-deck">Unusual for a chronic-pain disorder, TMD doesn't accumulate with age — it peaks during the most active reproductive years and softens after. This shape is one of the strongest hints that hormones are central to the story.</p>
      <Pyramid data={D.agePyramid}/>
      <div className="j-callout">
        <div className="j-callout-num">30–44</div>
        <div className="j-callout-text">The peak band: 44% of women, 24% of men report TMD symptoms. By 75, both rates fall by half.</div>
      </div>
    </section>
  );
}

/* ─── 06 — Symptoms ─── */
function JSymptoms(){
  return (
    <section className="j-section j-section-paper">
      <div className="j-section-head">
        <div className="ed-num">§ 05<strong>The Signs</strong></div>
        <h2 className="ed-section-title">It rarely shows up <span className="ital">just</span> as jaw pain.</h2>
      </div>
      <p className="j-deck">Most people with TMD don't go to the doctor for their jaw. They go for a headache, an earache, a stiff neck — and learn months or years later that the source was the joint they'd never thought about.</p>
      <BarChart data={D.symptoms} max={45} barColor="var(--accent-ink)" labelWidth={280}/>
      <p className="j-cite">Source: Almashraqi et al. (2025), pooled across 27 studies.</p>
    </section>
  );
}

/* ─── 07 — Where pain shows up (replaced body map with referral diagram) ─── */
/* Skipped per scope; symptom chart covers it */

/* ─── 07 — Hormones / perimenopause ─── */
function JHormones(){
  return (
    <section className="j-section">
      <div className="j-section-head">
        <div className="ed-num">§ 06<strong>The Hormones</strong></div>
        <h2 className="ed-section-title">Why <span className="ital">perimenopause</span> makes it worse.</h2>
      </div>
      <div className="j-hormones-grid">
        <div className="j-hormones-stat">
          <div className="j-hormones-num"><Counter to={D.hormones.perimenoFlare} suffix="%"/></div>
          <div className="j-hormones-label">of women report jaw symptoms <em>worsen</em> through perimenopause</div>
        </div>
        <div className="j-hormones-stat">
          <div className="j-hormones-num"><Counter to={D.hormones.afterMeno} suffix="%" delay={300}/></div>
          <div className="j-hormones-label">continue to have elevated symptoms after menopause</div>
        </div>
        <div className="j-hormones-stat">
          <div className="j-hormones-num"><Counter to={D.hormones.riskMultiplier} decimals={1} suffix="×" delay={600}/></div>
          <div className="j-hormones-label">elevated risk during reproductive years vs. men</div>
        </div>
      </div>
      <div className="j-hormones-prose">
        <p>The TMJ is dense with estrogen receptors. As estrogen falls and fluctuates through perimenopause, the cartilage and ligaments that cushion the joint lose some of their mechanical resilience. Disc displacement becomes more common. Chronic muscle tension — already higher in women — gets less relief from sleep, which itself fragments through this transition.</p>
        <p>Most women who arrive at a TMD diagnosis in their 40s and 50s have been quietly accommodating jaw pain for a decade or more. Perimenopause is often the point where accommodating stops working.</p>
      </div>

      <div className="j-mech">
        <div className="j-eyebrow">The two hormones driving the flares</div>
        <div className="j-mech-grid">
          <div className="j-mech-card">
            <div className="j-mech-tag">Estrogen</div>
            <h3 className="j-mech-name">Beta-estradiol</h3>
            <div className="j-mech-flow">
              <div className="j-mech-step">Binds to receptors in your jaw joint</div>
              <div className="j-mech-step">Drives inflammation</div>
              <div className="j-mech-step">Accelerates joint degeneration</div>
            </div>
          </div>
          <div className="j-mech-card">
            <div className="j-mech-tag">Pregnancy hormone</div>
            <h3 className="j-mech-name">Relaxin</h3>
            <div className="j-mech-flow">
              <div className="j-mech-step">Loosens ligaments system-wide, including your jaw</div>
              <div className="j-mech-step">Reduces support around the joint</div>
              <div className="j-mech-step">Creates instability in the articular disc</div>
            </div>
          </div>
        </div>
        <p className="j-mech-tldr">
          Both hormones fluctuate during <strong>pregnancy</strong>, <strong>postpartum</strong>, and through <strong>your cycle</strong>. That's why TMJ flares aren't random.
        </p>
      </div>
    </section>
  );
}

/* ─── 08 — US map ─── */
function JUSMap(){
  return (
    <section className="j-section j-section-paper">
      <div className="j-section-head">
        <div className="ed-num">§ 07<strong>The States</strong></div>
        <h2 className="ed-section-title">United States, <span className="ital">unevenly</span> affected.</h2>
      </div>
      <p className="j-deck">Self-reported jaw pain in the past 30 days, by state. Higher in Appalachia, the Mountain West, and the Deep South — patterns that mirror chronic-pain prevalence broadly. Hover any state.</p>
      <USChoropleth data={D.usStates}/>
      <p className="j-cite">Illustrative composite of CDC NHIS regional facial-pain data and TMD-specific studies. Hover for state values.</p>
    </section>
  );
}

/* ─── 09 — Diagnostic journey ─── */
function JJourney(){
  return (
    <section className="j-section">
      <div className="j-section-head">
        <div className="ed-num">§ 08<strong>The Journey</strong></div>
        <h2 className="ed-section-title">It takes <span className="ital">years</span> to get a name for it.</h2>
      </div>
      <div className="j-journey-headline">
        <div>
          <div className="j-journey-num"><Counter to={D.journey.avgYears} decimals={1}/></div>
          <div className="j-journey-label">years from first symptom to diagnosis</div>
        </div>
        <div>
          <div className="j-journey-num"><Counter to={D.journey.avgProviders} decimals={1} delay={200}/></div>
          <div className="j-journey-label">providers seen along the way</div>
        </div>
        <div>
          <div className="j-journey-num"><Counter to={D.journey.misdiagnosedFirst} suffix="%" delay={400}/></div>
          <div className="j-journey-label">misdiagnosed at first</div>
        </div>
      </div>
      <div className="j-journey-paths">
        <div className="j-eyebrow">Where patients go before getting answers</div>
        <BarChart data={D.journey.paths.map(p => ({ name: p.step, rate: p.pct }))} max={80} barColor="var(--gold)" labelWidth={260}/>
      </div>
    </section>
  );
}

/* ─── 10 — Comorbidities ─── */
function JComorbid(){
  return (
    <section className="j-section j-section-paper">
      <div className="j-section-head">
        <div className="ed-num">§ 09<strong>The Company It Keeps</strong></div>
        <h2 className="ed-section-title">TMD rarely <span className="ital">travels alone.</span></h2>
      </div>
      <p className="j-deck">If you have TMD, the odds you also have at least one of these is over 80%. The conditions share central-nervous-system pain pathways — which is part of why treating just the jaw rarely solves the whole picture.</p>
      <BarChart data={D.comorbid} max={70} barColor="var(--plum)" labelWidth={240}/>
      <p className="j-cite">Composite: Liou et al. 2023 (anxiety/depression); Al-Jewair et al. 2021 (sleep); Gonçalves et al. 2011 (migraine).</p>
    </section>
  );
}

/* ─── 11 — Cost ─── */
function JCost(){
  const segs = [
    { label: "Not covered",        value: D.cost.insuredNot,     color: "var(--rose)" },
    { label: "Partially covered",  value: D.cost.insuredPartial, color: "var(--gold)" },
    { label: "Fully covered",      value: D.cost.insuredFully,   color: "var(--accent)" },
  ];
  return (
    <section className="j-section">
      <div className="j-section-head">
        <div className="ed-num">§ 10<strong>The Cost</strong></div>
        <h2 className="ed-section-title">A condition that falls into <span className="ital">an insurance gap.</span></h2>
      </div>
      <div className="j-cost-grid">
        <div className="j-cost-stat">
          <div className="j-cost-num">$<Counter to={D.cost.annualUS} />B</div>
          <div className="j-cost-label">annual US cost of TMD treatment</div>
        </div>
        <div className="j-cost-stat">
          <div className="j-cost-num">$<Counter to={D.cost.avgOOP} delay={200}/></div>
          <div className="j-cost-label">average out-of-pocket per affected adult / year</div>
        </div>
      </div>
      <div className="j-cost-bar">
        <div className="j-eyebrow">How insurance covers TMD treatment</div>
        <StackedBar segments={segs}/>
        <p className="j-cite">TMD sits between dental and medical insurance — most plans treat it as the other's responsibility. Slade & Durham (2018), NASEM commissioned report.</p>
      </div>
    </section>
  );
}

/* ─── 12 — Trend / projection ─── */
function JTrend(){
  return (
    <section className="j-section j-section-paper">
      <div className="j-section-head">
        <div className="ed-num">§ 11<strong>The Trajectory</strong></div>
        <h2 className="ed-section-title">It's <span className="ital">growing.</span></h2>
      </div>
      <p className="j-deck">A 2025 projection model published in <em>J Clin Med</em> estimates global TMD prevalence will keep climbing — driven by stress, sleep debt, screen-time posture, and longer life expectancy in already-affected populations.</p>
      <LineChart data={D.trend} xKey="year" yKey="rate" height={360} color="var(--accent-ink)"/>
      <p className="j-cite">Sources: Valesan 2021 (historical), Zieliński 2025 (2030–2050 projection).</p>
    </section>
  );
}

/* ─── 13 — Citations ─── */
function JCitations(){
  return (
    <section className="j-section j-citations">
      <div className="j-section-head">
        <div className="ed-num">§ 12<strong>Sources</strong></div>
        <h2 className="ed-section-title">Where this came from.</h2>
      </div>
      <ol className="j-cite-list">
        {D.citations.map(c => (
          <li key={c.id}><span className="j-cite-num">{String(c.id).padStart(2,'0')}</span>{c.ref}</li>
        ))}
      </ol>
    </section>
  );
}

/* ─── Outro ─── */
function JOutro(){
  return (
    <section className="j-outro">
      <h2 className="j-outro-title">
        Now that you know,<br/><span className="ital">find someone who can help.</span>
      </h2>
      <a href="TMJDirectory.html" className="j-outro-cta">Browse the directory →</a>
    </section>
  );
}

Object.assign(window, {
  JHero, JDefinitions, JGlobal, JGender, JAge, JSymptoms,
  JHormones, JUSMap, JJourney, JComorbid, JCost, JTrend, JCitations, JOutro,
});
