/* global React, ReactDOM */
const { useState, useEffect } = React;

const _roots = new WeakMap();
function mount(id, el) {
  const node = document.getElementById(id);
  if (!node) return;
  let root = _roots.get(node);
  if (!root) { root = ReactDOM.createRoot(node); _roots.set(node, root); }
  root.render(el);
}

// Definition of the 11 dimension sections, in order.
// Each entry tells us: where to pull the distribution from, what to display,
// and which sub-question codes to list under "dive deeper".
const DIMENSION_DEFS = [
  // From the `flourishing` array (uses key without `fl_` prefix and with `ai_impact`).
  { key:'fl_satisfaction_ai', source:'flourishing', srcKey:'satisfaction',
    category:'Life satisfaction', title:'How AI shapes overall life satisfaction.',
    dek:'Respondents rated AI’s perceived impact on their general satisfaction with life on a 7-point scale.',
    summary: <><strong>63% report a positive effect</strong> on overall life satisfaction; only 3% report a negative one. The strongest net-positive of the six core flourishing dimensions.</> },
  { key:'fl_health_ai', source:'flourishing', srcKey:'health',
    category:'Health', title:'How AI shapes mental and physical health.',
    dek:'Self-reported impact of AI on health behaviors and overall wellbeing.',
    summary: <><strong>Half of respondents (50%) say AI helps</strong> their health; 44% say it has no real effect, and 6% report harm, the second-highest harm rate among the core dimensions.</> },
  { key:'fl_purpose_ai', source:'flourishing', srcKey:'purpose',
    category:'Purpose & meaning', title:'How AI shapes purpose and meaning.',
    dek:'Whether AI helped or hindered respondents’ sense of direction, goals, and meaning.',
    summary: <><strong>43% report a positive effect</strong> on purpose and meaning, but a majority (52%) say AI has no real impact here at all.</> },
  { key:'fl_character_ai', source:'flourishing', srcKey:'character',
    category:'Character & virtue', title:'How AI shapes character and virtue.',
    dek:'Self-reported impact of AI on honesty, patience, and other traits respondents value.',
    summary: <><strong>47% report a positive effect</strong> on their character; nearly half (49%) see no effect. The closest-to-neutral of the six core dimensions.</> },
  { key:'fl_social_ai', source:'flourishing', srcKey:'social',
    category:'Social relationships', title:'How AI shapes social relationships.',
    dek:'Whether AI improved or strained respondents’ relationships with others.',
    summary: <><strong>Just 30% say AI helps their relationships</strong>, by far the lowest of the six core dimensions. 65% say it has no effect, and 5% report harm.</> },
  { key:'fl_financial_ai', source:'flourishing', srcKey:'financial',
    category:'Financial security', title:'How AI shapes financial security.',
    dek:'Self-reported impact of AI on income, work, and financial stability.',
    summary: <><strong>34% report a positive effect</strong> on their finances; the majority (62%) report no effect, suggesting AI’s economic upside hasn’t reached most respondents yet.</> },
  // From the `thrive_ai` array (key matches directly).
  { key:'thrive_skills_ai', source:'thrive_ai', srcKey:'thrive_skills_ai',
    category:'Skills development', title:'How AI shapes skill development.',
    dek:'Whether AI helped respondents build the skills they care about.',
    summary: <><strong>58% say AI helps them build skills</strong> they care about, with 8% reporting harm, the highest helpful rate among the thriving items below the core six.</> },
  { key:'thrive_learn_ai', source:'thrive_ai', srcKey:'thrive_learn_ai',
    category:'Learning ability', title:'How AI shapes learning ability.',
    dek:'Self-reported impact of AI on learning new things and understanding complex topics.',
    summary: <><strong>79% say AI improved their ability to learn</strong>, the highest helpful rate of any flourishing item. Yet 13% report harm, suggesting a real downside for some learners.</> },
  { key:'thrive_accomplish_ai', source:'thrive_ai', srcKey:'thrive_accomplish_ai',
    category:'Accomplishment', title:'How AI shapes accomplishment.',
    dek:'Whether AI helped respondents get done what mattered to them.',
    summary: <><strong>Polarized:</strong> 45% say AI helps them accomplish things, but 33% say it actively hurts. Net effect lands close to neutral (mean ≈ 3.06 on the 1–7 scale).</> },
];

function pickDistribution(data, def) {
  if (def.source === 'flourishing') {
    const item = data.flourishing.find(d => d.key === def.srcKey);
    if (!item) return null;
    return {
      distribution: item.ai_impact.distribution_7,
      mean: item.ai_impact.mean,
    };
  }
  if (def.source === 'thrive_ai') {
    const item = data.thrive_ai.find(d => d.key === def.srcKey);
    if (!item) return null;
    return {
      distribution: item.distribution,
      mean: item.mean,
    };
  }
  return null;
}

function App() {
  const [data, setData] = useState(window.__DATA__);
  const [meta, setMeta] = useState(window.__META__);

  useEffect(() => {
    if (data && meta) return;
    const onReady = () => { setData(window.__DATA__); setMeta(window.__META__); };
    window.addEventListener('data-ready', onReady);
    return () => window.removeEventListener('data-ready', onReady);
  }, [data, meta]);

  useEffect(() => {
    if (!data) return;

    // Section 1 — Overall AI influence (3 tabs).
    mount('overall-tabs', <OverallTabs data={data}/>);

    // Hero globe
    mount('globe-mount', <GlobeHero/>);

    // Sections 2..N — scroll-jacked dimension stage (33% nav / 66% chart).
    const container = document.getElementById('dimension-sections');
    if (container) {
      let root = _roots.get(container);
      if (!root) { root = ReactDOM.createRoot(container); _roots.set(container, root); }
      const metadataCols = (meta && meta.columns) || {};
      const subqData = window.__SUBQ__ || {};
      const dims = DIMENSION_DEFS.map(def => {
        const ds = pickDistribution(data, def);
        return ds ? { def, distribution: ds.distribution, mean: ds.mean } : null;
      }).filter(Boolean);
      root.render(<DimensionStage dimensions={dims} metadata={metadataCols} subqData={subqData}/>);
    }

    // Insights stage — usage / contexts / access / demographics
    const insightsContainer = document.getElementById('insights-sections');
    if (insightsContainer) {
      let root = _roots.get(insightsContainer);
      if (!root) { root = ReactDOM.createRoot(insightsContainer); _roots.set(insightsContainer, root); }

      const ins = window.__INSIGHTS__ || {};
      const fmtPct = (v) => v.toFixed(1) + '%';

      const mkRows = (arr, key) => (arr || []).map(r => ({
        key: r.code || r.label,
        label: r.label,
        pct: r[key] || 0,
      }));

      const tools = mkRows(ins.tools, 'pct_weekly');
      const contexts = mkRows(ins.contexts, 'pct_weekly');

      // Demographic groups now carry fl_mean (subgroup average perceived AI
      // impact on flourishing, on -3..+3 axis where 0 = no real effect).
      const ageRows = ins.by_age || [];
      const genderRows = ins.by_gender || [];
      const incomeRows = ins.by_income || [];
      const raceRows = ins.by_race || [];
      const polRows = ins.by_political || [];
      const mhRows = ins.by_mental_health || [];

      const panels = [
        tools.length ? {
          key: 'tools',
          navLabel: 'Which AI tools',
          title: 'Chatbots dominated the most common form of access to AI.',
          summary: <>The story of AI use in 2026 is, almost entirely, <strong>the story of chatbots</strong> and the office tools that quietly embed them. Companions, agents, and embodied AI remain minority habits.</>,
          stat: ins.tools && ins.tools[0] ? { value: ins.tools[0].pct_weekly.toFixed(0) + '%', label: `Use ${ins.tools[0].label.toLowerCase()} weekly+` } : null,
          render: () => <HBars rows={tools} valueKey="pct" maxVal={100} format={fmtPct}/>,
        } : null,
        contexts.length ? {
          key: 'contexts',
          navLabel: 'In which contexts',
          title: 'What are people actually doing with it?',
          summary: <><strong>Information, learning, and everyday tasks lead</strong> by a wide margin. Emotional and medical use is rarer, but real, and not zero.</>,
          stat: ins.contexts && ins.contexts[0] ? { value: ins.contexts[0].pct_weekly.toFixed(0) + '%', label: `Use AI for ${ins.contexts[0].label.toLowerCase()} weekly+` } : null,
          render: () => <HBars rows={contexts} valueKey="pct" maxVal={100} format={fmtPct}/>,
        } : null,
        (ins.by_access_provider || ins.by_access_paid_user || ins.by_access_thinking_mode) ? {
          key: 'access',
          navLabel: 'Through what access',
          title: 'How does access shape perceived AI impact on flourishing?',
          summary: <>Average perceived AI impact on flourishing (mean across the 8 dimensions, on a −3 to +3 axis where <strong>0 = no real effect</strong>), broken down by AI provider, paid tier, and whether respondents use a thinking / extended-reasoning model.</>,
          render: () => <AccessFlPanel
            provider={ins.by_access_provider}
            tier={ins.by_access_paid_user}
            mode={ins.by_access_thinking_mode}/>,
        } : null,
        ageRows.length ? {
          key: 'age',
          navLabel: 'By age group',
          title: 'Perceived AI impact on flourishing, by age group.',
          summary: <>Average perceived AI impact on flourishing (mean across the 8 dimensions, on a −3 to +3 axis where <strong>0 = no real effect</strong>) for each age group.</>,
          render: () => <FlMeanBars rows={ageRows} sort={false}/>,
        } : null,
        genderRows.length ? {
          key: 'gender',
          navLabel: 'By gender',
          title: 'Perceived AI impact on flourishing, by gender.',
          summary: <>Average perceived AI impact on flourishing (−3 to +3, <strong>0 = no real effect</strong>) for each gender group.</>,
          render: () => <FlMeanBars rows={genderRows} sort={false}/>,
        } : null,
        incomeRows.length ? {
          key: 'income',
          navLabel: 'By income',
          title: 'Perceived AI impact on flourishing, by income.',
          summary: <>Average perceived AI impact on flourishing (−3 to +3, <strong>0 = no real effect</strong>) by household income bracket.</>,
          render: () => <FlMeanBars rows={incomeRows} sort={false}/>,
        } : null,
        raceRows.length ? {
          key: 'race',
          navLabel: 'By race / ethnicity',
          title: 'Perceived AI impact on flourishing, by race / ethnicity.',
          summary: <>Multi-select; respondents are counted in every category they listed. Average perceived AI impact on flourishing (−3 to +3, <strong>0 = no real effect</strong>).</>,
          render: () => <FlMeanBars rows={raceRows}/>,
        } : null,
        polRows.length ? {
          key: 'political',
          navLabel: 'By political leaning',
          title: 'Perceived AI impact on flourishing, by political leaning.',
          summary: <>Average perceived AI impact on flourishing (−3 to +3, <strong>0 = no real effect</strong>) across the political spectrum.</>,
          render: () => <FlMeanBars rows={polRows} sort={false}/>,
        } : null,
        mhRows.length ? {
          key: 'mental_health',
          navLabel: 'By mental health',
          title: 'Perceived AI impact on flourishing, by prior diagnosis.',
          summary: <>Multi-select. Average perceived AI impact on flourishing (−3 to +3, <strong>0 = no real effect</strong>) for respondents reporting each prior mental-health diagnosis.</>,
          render: () => <FlMeanBars rows={mhRows}/>,
        } : null,
      ].filter(Boolean);

      root.render(<InsightStage panels={panels}/>);
    }
  }, [data, meta]);

  return null;
}

function _mountApp() {
  const _appMount = document.createElement('div');
  document.body.appendChild(_appMount);
  ReactDOM.createRoot(_appMount).render(<App/>);
}
if (document.body) _mountApp();
else document.addEventListener('DOMContentLoaded', _mountApp);
