/* Stats — live infographics page.
 *
 * All numbers derive from window.KESTREL_SUMMARY (industry aggregates) and
 * window.COMPANIES (per-company rollups). Nothing is hardcoded — if the
 * dataset changes, this page updates with it. Uses primitives already shipped
 * elsewhere on the site (AnimatedNumber, Reveal, Donut, LineChart, BarChart,
 * HBarList, StackedBar, Sparkline, EyebrowRow). */

const Stats = ({ setRoute }) => {
  const summary = window.KESTREL_SUMMARY || {};
  const companies = window.COMPANIES || [];
  const meta = summary.meta || {};
  const global = summary.global || {};

  /* ── Headline counters ─────────────────────────────────────────────── */
  const totalPassages = meta.total_passages || 0;
  const nCompanies = meta.n_companies || companies.length;
  const nReports = meta.n_reports || 0;
  const yearRange = meta.year_range || [];
  const yearSpan = yearRange.length === 2 ? (yearRange[1] - yearRange[0] + 1) : 0;

  const labelCount = global.label_primary || {};
  const labelPct = global.label_pct || {};
  const tCount = labelCount.positive || 0;
  const aCount = labelCount.ambiguous || 0;
  const nCount = labelCount.negative || 0;
  const tPct = +(labelPct.positive  ?? 0).toFixed(2);
  const aPct = +(labelPct.ambiguous ?? 0).toFixed(2);
  const nPct = +(labelPct.negative  ?? 0).toFixed(2);

  /* Average analyst confidence — passage-weighted across companies. */
  const avgConfidence = React.useMemo(() => {
    let num = 0, den = 0;
    for (const c of companies) {
      num += (c.conf || 0) * (c.n_disc || 0);
      den += (c.n_disc || 0);
    }
    return den ? num / den : 0;
  }, [companies]);

  /* ── Year trend ────────────────────────────────────────────────────── */
  const byYear = global.by_year || {};
  const years = Object.keys(byYear).sort();
  const truePctSeries = years.map(y => byYear[y].positive_pct || 0);
  const ambigPctSeries = years.map(y => byYear[y].ambiguous_pct || 0);
  const passagesByYear = years.map(y => byYear[y].n || 0);
  const truePctMax = Math.max(0.6, ...truePctSeries) * 1.25;
  const truePctTicks = (() => {
    const step = truePctMax / 4;
    return [0, step, step*2, step*3, truePctMax];
  })();

  /* Year-over-year change in true % (latest vs first) */
  const trueDelta = truePctSeries.length >= 2
    ? truePctSeries[truePctSeries.length - 1] - truePctSeries[0]
    : 0;
  const trueDeltaPct = truePctSeries[0] > 0
    ? ((truePctSeries[truePctSeries.length - 1] / truePctSeries[0]) - 1) * 100
    : 0;
  const passagesDelta = passagesByYear.length >= 2
    ? passagesByYear[passagesByYear.length - 1] - passagesByYear[0]
    : 0;

  /* ── Best / worst performers ───────────────────────────────────────── */
  const ranked = [...companies].sort((a,b) => (b.t_pct || 0) - (a.t_pct || 0));
  const topByPct = ranked[0];
  const bottomByPct = ranked[ranked.length - 1];

  const rankedAbs = [...companies].sort((a,b) => {
    const at = Math.round((a.t_pct/100) * a.n_disc);
    const bt = Math.round((b.t_pct/100) * b.n_disc);
    return bt - at;
  });
  const topByAbs = rankedAbs[0];

  /* ── Industry-wide categorical breakdowns (counts → bar data) ──────── */
  const initiativeData = (() => {
    const o = global.initiative_type || {};
    const order = ['transformational','transitional','transactional','no_initiative'];
    return order.filter(k => o[k] !== undefined).map(k => ({
      k: window.INITIATIVE_LABEL?.[k] || k,
      v: o[k] || 0,
      color: k === 'transformational' ? 'var(--class-true)'
           : k === 'transitional'     ? 'var(--moss)'
           : k === 'transactional'    ? 'var(--class-ambig)'
           : 'var(--class-none)',
    }));
  })();
  const initiativeTotal = initiativeData.reduce((s,d) => s + d.v, 0);

  const pillarData = (() => {
    const o = global.csv_pillar || {};
    const order = ['value_chain','cluster_development','products_markets','none'];
    return order.filter(k => o[k] !== undefined).map(k => ({
      k: window.PILLAR_LABEL?.[k] || k,
      v: o[k] || 0,
      color: k === 'none' ? 'var(--class-none)' : 'var(--moss)',
    }));
  })();
  const pillarTotal = pillarData.reduce((s,d) => s + d.v, 0);
  const pillarMapped = pillarTotal - (global.csv_pillar?.none || 0);

  const linkageData = (() => {
    const o = global.linkage_strength || {};
    const order = ['explicit','implied','none'];
    const labels = { explicit:'Explicit', implied:'Implied', none:'No linkage' };
    return order.filter(k => o[k] !== undefined).map(k => ({
      k: labels[k],
      v: o[k] || 0,
      color: k === 'explicit' ? 'var(--class-true)'
           : k === 'implied'  ? 'var(--class-ambig)'
           : 'var(--class-none)',
    }));
  })();
  const linkageExplicit = global.linkage_strength?.explicit || 0;

  const evidenceData = (() => {
    const o = global.evidence_strength || {};
    const order = ['4','3','2','1','none'];
    const labels = { '4':'A · Verified', '3':'B · Reviewed', '2':'C · Self-reported', '1':'D · Unsupported', 'none':'No claim' };
    return order.filter(k => o[k] !== undefined).map(k => ({
      k: labels[k],
      v: o[k] || 0,
      color: k === '4' ? 'var(--class-true)'
           : k === '3' ? 'var(--moss)'
           : k === '2' ? 'var(--class-ambig)'
           : k === '1' ? '#A4886A'
           : 'var(--class-none)',
    }));
  })();
  const evidenceVerified = (global.evidence_strength?.['4'] || 0) + (global.evidence_strength?.['3'] || 0);

  /* ── Heatmap: companies × years, intensity = positive_pct ──────────── */
  const heatmapMaxPct = React.useMemo(() => {
    let m = 0;
    for (const c of companies) {
      for (const y of years) {
        const v = c.by_year?.[y]?.positive_pct;
        if (typeof v === 'number' && v > m) m = v;
      }
    }
    return m || 1;
  }, [companies, years]);

  /* ── Helpers ───────────────────────────────────────────────────────── */
  const fmt = (n) => (n || 0).toLocaleString();
  const pct = (n, d=2) => `${(+(n||0)).toFixed(d)}%`;
  const heatColor = (v) => {
    if (typeof v !== 'number' || v <= 0) return 'var(--canvas-3)';
    const t = Math.min(1, v / heatmapMaxPct);
    /* Interpolate sage-tint → moss-deep */
    const lerp = (a,b) => Math.round(a + (b-a)*t);
    const r = lerp(237, 78);
    const g = lerp(241, 90);
    const b = lerp(230, 65);
    return `rgb(${r},${g},${b})`;
  };

  /* ── Loading guard ────────────────────────────────────────────────── */
  if (!summary.meta) {
    return (
      <section className="section">
        <div className="site-wrap">
          <EyebrowRow label="Live stats"/>
          <p style={{color:'var(--ink-2)'}}>Loading dataset…</p>
        </div>
      </section>
    );
  }

  return (
    <>
      {/* ── Hero: pulse-dot eyebrow + dominant headline ─────────────── */}
      <section className="section stats-hero-section">
        <div className="site-wrap">
          <div className="stats-eyebrow-live">
            <span className="stats-live-dot" aria-hidden="true"/>
            <span className="eyebrow">Live · updated with the dataset</span>
          </div>

          <div className="stats-hero-grid">
            <div>
              <h1 className="stats-hero-headline">
                <span className="stats-hero-num">
                  <AnimatedNumber value={tPct} decimals={2} duration={1400}/>
                  <span className="stats-hero-num-unit">%</span>
                </span>
                <span className="serif-moment stats-hero-tagline">
                  of {fmt(totalPassages)} mining-disclosure passages
                  qualify as <em>true shared value</em>.
                </span>
              </h1>
              <p className="lede stats-hero-lede">
                A live read of the Kestrel dataset — every counter, ranking and breakdown on this page is computed from the published aggregates at load time.
                Coverage spans <strong>{yearRange[0]}–{yearRange[1]}</strong>, <strong>{nCompanies} mining majors</strong> and <strong>{nReports} reports</strong>.
              </p>
            </div>

            <div className="stats-hero-side">
              <div className="stats-hero-side-row">
                <div className="stats-hero-side-num tabular" style={{color:'var(--class-true)'}}>
                  <AnimatedNumber value={tCount} decimals={0} duration={1600}/>
                </div>
                <div className="stats-hero-side-lab">true shared-value passages</div>
              </div>
              <div className="stats-hero-side-row">
                <div className="stats-hero-side-num tabular" style={{color:'var(--class-ambig)'}}>
                  <AnimatedNumber value={aCount} decimals={0} duration={1600}/>
                </div>
                <div className="stats-hero-side-lab">ambiguous</div>
              </div>
              <div className="stats-hero-side-row">
                <div className="stats-hero-side-num tabular" style={{color:'var(--ink-3)'}}>
                  <AnimatedNumber value={nCount} decimals={0} duration={1600}/>
                </div>
                <div className="stats-hero-side-lab">no measurable value</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ── KPI strip: five accent-bar cells with hover lift ───────── */}
      <section className="section stats-kpi-section">
        <div className="site-wrap">
          <div className="stats-kpi-row">
            {[
              { label:'Passages analysed', value: totalPassages,  decimals:0, accent:'var(--moss)'        },
              { label:'Companies covered', value: nCompanies,     decimals:0, accent:'var(--class-true)'  },
              { label:'Reports parsed',    value: nReports,       decimals:0, accent:'var(--moss-deep)'   },
              { label:'Years of coverage', value: yearSpan,       decimals:0, accent:'var(--class-ambig)', suffix:' yrs' },
              { label:'Avg analyst confidence', value: avgConfidence, decimals:1, accent:'var(--moss)', suffix:'%' },
            ].map((k,i) => (
              <div key={i} className="stats-kpi-card" style={{animationDelay:`${i*70}ms`,'--accent':k.accent}}>
                <span className="stats-kpi-accent" aria-hidden="true"/>
                <div className="stats-kpi-label">{k.label}</div>
                <div className="stats-kpi-value tabular">
                  <AnimatedNumber value={k.value} decimals={k.decimals} suffix={k.suffix||''}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── The 0.34% moment: oversized donut + satellite stats ──── */}
      <section className="section alt">
        <div className="site-wrap">
          <EyebrowRow label="Shared-value classification"/>
          <h2 style={{maxWidth:780,marginTop:6}}>How the {fmt(totalPassages)} passages classify across the three CSV bands.</h2>

          <div className="stats-csv-grid">
            <Reveal>
              <div className="stats-donut-frame">
                <Donut
                  size={360} thickness={36}
                  segments={[
                    { value: Math.max(tPct, 0.6), color:'var(--class-true)'  },
                    { value: aPct,                color:'var(--class-ambig)' },
                    { value: nPct,                color:'var(--class-none)'  },
                  ]}
                  centerValue={`${tPct.toFixed(tPct < 1 ? 2 : 1)}%`}
                  centerLabel="True shared value"
                  centerSub={`${fmt(tCount)} of ${fmt(totalPassages)}`}
                />
              </div>
            </Reveal>
            <div className="stats-csv-rows">
              <StackedBar t={Math.max(tPct, 0.6)} a={aPct} n={nPct} height={16}/>
              <div className="stats-csv-cards">
                {[
                  { label:'True shared value',  count:tCount, p:tPct, tone:'var(--class-true)',  bg:'var(--sage-tint)',
                    note:'Measurable, tied to operations, with an explicit causal link.' },
                  { label:'Ambiguous',          count:aCount, p:aPct, tone:'var(--class-ambig)', bg:'#F2F2EC',
                    note:'Plausible but lacks evidence, specificity, or linkage.' },
                  { label:'No measurable value',count:nCount, p:nPct, tone:'var(--ink-2)',       bg:'#F4F4EE',
                    note:'Narrative, policy, or compliance framing only.' },
                ].map((s,i) => (
                  <div key={s.label} className="stats-csv-card" style={{background:s.bg,'--tone':s.tone,animationDelay:`${i*120}ms`}}>
                    <div className="stats-csv-card-eyebrow" style={{color:s.tone}}>
                      <span style={{width:8,height:8,background:s.tone,borderRadius:2,display:'inline-block'}}/>
                      {s.label}
                    </div>
                    <div className="stats-csv-card-pct tabular" style={{color:s.tone}}>
                      <AnimatedNumber value={s.p} decimals={s.p < 1 ? 2 : 1} suffix="%"/>
                    </div>
                    <div className="tabular" style={{fontSize:13,color:'var(--ink-2)',marginTop:6}}>
                      {fmt(s.count)} passages
                    </div>
                    <p style={{fontSize:13,lineHeight:'20px',color:'var(--ink-2)',marginTop:12}}>{s.note}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ── Trend section: chart cards with big headline numbers ──── */}
      <section className="section">
        <div className="site-wrap">
          <EyebrowRow label="Trend"/>
          <h2 style={{maxWidth:680,marginTop:6}}>True-shared-value rate, year by year.</h2>
          <p style={{fontSize:14,color:'var(--ink-2)',marginTop:10,maxWidth:640}}>
            Share of passages flagged as <em>true shared value</em> — the strictest of the three bands — across {yearRange[0]}–{yearRange[1]}.
            The bars on the right show how many passages were analysed in each year.
          </p>

          <div className="stats-trend-grid">
            <Reveal>
              <div className="stats-chart-card">
                <div className="stats-chart-headline">
                  <div>
                    <div className="eyebrow">True shared value · {yearRange[1]}</div>
                    <div className="stats-chart-headline-num tabular" style={{color:'var(--class-true)'}}>
                      <AnimatedNumber value={truePctSeries[truePctSeries.length-1] || 0} decimals={2} suffix="%"/>
                    </div>
                  </div>
                  <div className={`stats-chart-delta ${trueDelta >= 0 ? 'up' : 'down'}`}>
                    {trueDelta >= 0 ? '▲' : '▼'} {Math.abs(trueDeltaPct).toFixed(0)}% <span style={{color:'var(--ink-3)',fontWeight:400}}>vs {yearRange[0]}</span>
                  </div>
                </div>
                <LineChart
                  series={truePctSeries}
                  labels={years}
                  width={520}
                  height={220}
                  color="var(--class-true)"
                  yDomain={[0, truePctMax]}
                  yTicks={truePctTicks}
                  yFormat={(v)=>`${v.toFixed(2)}%`}
                />
              </div>
            </Reveal>
            <Reveal delay={80}>
              <div className="stats-chart-card">
                <div className="stats-chart-headline">
                  <div>
                    <div className="eyebrow">Passages analysed · {yearRange[1]}</div>
                    <div className="stats-chart-headline-num tabular" style={{color:'var(--moss)'}}>
                      <AnimatedNumber value={passagesByYear[passagesByYear.length-1] || 0} decimals={0}/>
                    </div>
                  </div>
                  <div className={`stats-chart-delta ${passagesDelta >= 0 ? 'up' : 'down'}`}>
                    {passagesDelta >= 0 ? '▲' : '▼'} {fmt(Math.abs(passagesDelta))} <span style={{color:'var(--ink-3)',fontWeight:400}}>vs {yearRange[0]}</span>
                  </div>
                </div>
                <BarChart
                  data={years.map((y,i) => ({ k:y, v: passagesByYear[i] }))}
                  width={520} height={220}
                  color="var(--moss)"
                  valueFormat={(v)=>v.toLocaleString()}
                />
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* ── Leaderboard: trophy-style cards ────────────────────────── */}
      <section className="section alt">
        <div className="site-wrap">
          <EyebrowRow label="Leaderboard"/>
          <h2 style={{maxWidth:760,marginTop:6}}>Best and worst performers.</h2>
          <p style={{fontSize:14,color:'var(--ink-2)',marginTop:10,maxWidth:640}}>
            Performance is measured two ways — by share (% of a company's passages that qualify as true shared value) and by absolute count.
            Both views matter: small reporters can look strong on share alone.
          </p>

          <div className="stats-leader-row">
            {[
              {
                rank:'01', tag:'Highest share', co: topByPct,
                metric: pct(topByPct?.t_pct ?? 0, 2), tone:'var(--class-true)',
                bg:'linear-gradient(160deg, var(--sage-tint) 0%, var(--canvas) 75%)',
                sub:`of ${fmt(topByPct?.n_disc)} passages`
              },
              {
                rank:'★',  tag:'Most true passages', co: topByAbs,
                metric: fmt(Math.round(((topByAbs?.t_pct||0)/100) * (topByAbs?.n_disc||0))),
                tone:'var(--moss-deep)',
                bg:'linear-gradient(160deg, var(--canvas) 0%, var(--sage-tint) 100%)',
                sub:`out of ${fmt(topByAbs?.n_disc)} analysed`
              },
              {
                rank:'↓', tag:'Lowest share', co: bottomByPct,
                metric: pct(bottomByPct?.t_pct ?? 0, 2), tone:'var(--ink-2)',
                bg:'var(--canvas)',
                sub:`of ${fmt(bottomByPct?.n_disc)} passages`
              },
            ].map((card,i) => card.co && (
              <Reveal key={i} delay={i*100}>
                <div className="stats-leader-card stat-card"
                  onClick={() => setRoute({ page:'company', id: card.co.id })}
                  style={{background:card.bg,'--tone':card.tone}}>
                  <div className="stats-leader-rank serif-moment" style={{color:card.tone}}>{card.rank}</div>
                  <div className="stats-leader-tag">
                    <span style={{width:7,height:7,borderRadius:999,background:card.tone}}/> {card.tag}
                  </div>
                  <div className="stats-leader-name">{card.co.name}</div>
                  <div className="stats-leader-meta tabular">
                    {card.co.country} · {card.co.commodity}
                  </div>
                  <div className="stats-leader-metric tabular" style={{color:card.tone}}>
                    {card.metric}
                  </div>
                  <div className="stats-leader-sub">{card.sub}</div>
                  <div className="stats-leader-cta">
                    Open scorecard <Icon name="arrow-right" size={12} className="arrow"/>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* ── Heatmap: companies × years, true-pct intensity ────────── */}
      <section className="section">
        <div className="site-wrap">
          <EyebrowRow label="Heatmap"/>
          <h2 style={{maxWidth:760,marginTop:6}}>True-shared-value rate by company and year.</h2>
          <p style={{fontSize:14,color:'var(--ink-2)',marginTop:10,maxWidth:640}}>
            Darker cells signal a higher share of true-shared-value passages. Empty cells: company didn't disclose that year.
          </p>

          <Reveal>
            <div className="stats-heatmap-frame">
              <div className="stats-heatmap-grid" style={{gridTemplateColumns:`160px repeat(${years.length}, 1fr) 56px`}}>
                <div/>
                {years.map(y => (
                  <div key={y} className="stats-heatmap-yearlabel tabular">{y}</div>
                ))}
                <div className="stats-heatmap-yearlabel" style={{textAlign:'right',color:'var(--ink-3)'}}>Avg</div>

                {ranked.map(c => (
                  <React.Fragment key={c.id}>
                    <div className="stats-heatmap-rowname"
                      onClick={() => setRoute({ page:'company', id: c.id })}
                      title={`Open ${c.name} scorecard`}>
                      <span style={{fontWeight:500}}>{c.name}</span>
                      <span style={{fontSize:11,color:'var(--ink-3)'}}>{c.country}</span>
                    </div>
                    {years.map(y => {
                      const v = c.by_year?.[y]?.positive_pct;
                      const exists = typeof v === 'number';
                      return (
                        <div key={y} className="stats-heatmap-cell"
                          style={{background: heatColor(v), color: (v && v > heatmapMaxPct*0.55) ? 'var(--canvas)' : 'var(--ink-2)'}}
                          title={exists ? `${c.name} · ${y} · ${v.toFixed(2)}% true` : `${c.name} · ${y} · no data`}>
                          {exists ? `${v.toFixed(2)}` : '·'}
                        </div>
                      );
                    })}
                    <div className="stats-heatmap-cell stats-heatmap-avg tabular" style={{background:'transparent',color:'var(--ink)',fontWeight:500}}>
                      {pct(c.t_pct, 1)}
                    </div>
                  </React.Fragment>
                ))}
              </div>

              <div className="stats-heatmap-legend">
                <span className="eyebrow" style={{color:'var(--ink-3)'}}>0.00%</span>
                <span className="stats-heatmap-legend-bar"/>
                <span className="eyebrow" style={{color:'var(--ink-3)'}}>{heatmapMaxPct.toFixed(2)}%</span>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* ── League table: rank pills + sparkline + hover ───────────── */}
      <section className="section alt">
        <div className="site-wrap">
          <EyebrowRow label="League table"/>
          <h2 style={{maxWidth:760,marginTop:6}}>Every company, ranked.</h2>
          <p style={{fontSize:14,color:'var(--ink-2)',marginTop:10,maxWidth:640}}>
            Sorted by share of true shared value. Sparkline shows the per-year trend. Click any row for the full scorecard.
          </p>

          <div className="stats-league">
            <div className="stats-league-head">
              <span>#</span>
              <span>Company</span>
              <span style={{textAlign:'right'}}>Passages</span>
              <span style={{textAlign:'right'}}>True %</span>
              <span style={{textAlign:'right'}}>Ambig %</span>
              <span style={{textAlign:'right'}}>Conf</span>
              <span>Trend</span>
              <span>CSV mix</span>
            </div>
            {ranked.map((c,i) => {
              const sparkPoints = years.map(y => c.by_year?.[y]?.positive_pct || 0);
              const isLeader = i === 0;
              return (
                <div key={c.id}
                  onClick={() => setRoute({ page:'company', id: c.id })}
                  className={`stats-league-row ${isLeader ? 'is-leader' : ''}`}
                  style={{animationDelay:`${i*40}ms`}}>
                  <span className="stats-league-rank tabular">{String(i+1).padStart(2,'0')}</span>
                  <span className="stats-league-co">
                    <span className="stats-league-co-name">{c.name}</span>
                    <span className="stats-league-co-meta">{c.country} · {c.commodity}</span>
                  </span>
                  <span className="tabular" style={{textAlign:'right'}}>{fmt(c.n_disc)}</span>
                  <span className="tabular stats-league-true" style={{textAlign:'right'}}>{pct(c.t_pct, 2)}</span>
                  <span className="tabular" style={{textAlign:'right',color:'var(--ink-2)'}}>{pct(c.a_pct, 2)}</span>
                  <span className="tabular" style={{textAlign:'right',color:'var(--ink-2)'}}>{c.conf}%</span>
                  <span><Sparkline points={sparkPoints} width={92} height={26} color={isLeader ? 'var(--class-true)' : 'var(--moss)'}/></span>
                  <span><StackedBar t={Math.max(c.t_pct, 0.4)} a={c.a_pct} n={c.n_pct} height={8}/></span>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── Structural breakdowns: bigger cards with totals ────────── */}
      <section className="section">
        <div className="site-wrap">
          <EyebrowRow label="Structure"/>
          <h2 style={{maxWidth:760,marginTop:6}}>What the disclosures actually contain.</h2>
          <p style={{fontSize:14,color:'var(--ink-2)',marginTop:10,maxWidth:640}}>
            Every passage is tagged with four structural signals. Together they explain why the true-shared-value share is so small.
          </p>

          <div className="stats-structure-grid">
            <Reveal>
              <div className="stats-structure-card" style={{'--accent':'var(--moss)'}}>
                <div className="stats-structure-head">
                  <div>
                    <div className="eyebrow">Initiative type</div>
                    <div className="stats-structure-head-num tabular">
                      {(((global.initiative_type?.transformational || 0) / (initiativeTotal || 1)) * 100).toFixed(2)}%
                    </div>
                    <div className="stats-structure-head-sub">transformational</div>
                  </div>
                </div>
                <HBarList data={initiativeData} valueFormat={(v)=>v.toLocaleString()}/>
              </div>
            </Reveal>
            <Reveal delay={80}>
              <div className="stats-structure-card" style={{'--accent':'var(--class-true)'}}>
                <div className="stats-structure-head">
                  <div>
                    <div className="eyebrow">CSV pillar</div>
                    <div className="stats-structure-head-num tabular">
                      {fmt(pillarMapped)}
                    </div>
                    <div className="stats-structure-head-sub">passages mapped to a pillar</div>
                  </div>
                </div>
                <HBarList data={pillarData} valueFormat={(v)=>v.toLocaleString()}/>
              </div>
            </Reveal>
            <Reveal delay={140}>
              <div className="stats-structure-card" style={{'--accent':'var(--class-ambig)'}}>
                <div className="stats-structure-head">
                  <div>
                    <div className="eyebrow">Linkage strength</div>
                    <div className="stats-structure-head-num tabular">
                      {fmt(linkageExplicit)}
                    </div>
                    <div className="stats-structure-head-sub">explicit business-society linkages</div>
                  </div>
                </div>
                <HBarList data={linkageData} valueFormat={(v)=>v.toLocaleString()}/>
              </div>
            </Reveal>
            <Reveal delay={200}>
              <div className="stats-structure-card" style={{'--accent':'var(--moss-deep)'}}>
                <div className="stats-structure-head">
                  <div>
                    <div className="eyebrow">Evidence strength</div>
                    <div className="stats-structure-head-num tabular">
                      {fmt(evidenceVerified)}
                    </div>
                    <div className="stats-structure-head-sub">passages with B-grade or better evidence</div>
                  </div>
                </div>
                <HBarList data={evidenceData} valueFormat={(v)=>v.toLocaleString()}/>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* ── Methodology footer ───────────────────────────────────────── */}
      <section className="section alt">
        <div className="site-wrap">
          <div className="stats-footer-row">
            <p style={{fontSize:13,color:'var(--ink-3)',maxWidth:640,margin:0}}>
              Live figures derive from <code>data/kestrel_public.json</code>. Categorical breakdowns reflect Kestrel {window.KESTREL_VERSION || 'V2'} structural metadata only — passage text and analyst justifications are reserved for analyst access.
            </p>
            <div style={{display:'flex',gap:12}}>
              <button className="btn btn-ghost" onClick={() => setRoute({ page:'method' })}>Method</button>
              <button className="btn btn-primary" onClick={() => setRoute({ page:'explore' })}>
                Explore passages <Icon name="arrow-right" size={14} style={{marginLeft:2}}/>
              </button>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};
window.Stats = Stats;

/* ─────────────────────────────────────────────────────────────────────
 * StatsTeaser — compact preview rail for the Overview page.
 *
 * Surfaces the three "trophy" leaderboard cards (highest share, most true
 * passages, lowest share) plus a CTA into the full Stats page. Uses the same
 * .stats-leader-card styles as the full page so the visual language carries.
 * ──────────────────────────────────────────────────────────────────── */
const StatsTeaser = ({ setRoute }) => {
  const companies = window.COMPANIES || [];
  if (!companies.length) return null;

  const ranked = [...companies].sort((a,b) => (b.t_pct || 0) - (a.t_pct || 0));
  const topByPct = ranked[0];
  const bottomByPct = ranked[ranked.length - 1];
  const rankedAbs = [...companies].sort((a,b) => {
    const at = Math.round((a.t_pct/100) * a.n_disc);
    const bt = Math.round((b.t_pct/100) * b.n_disc);
    return bt - at;
  });
  const topByAbs = rankedAbs[0];

  const fmt = (n) => (n || 0).toLocaleString();
  const pct = (n, d=2) => `${(+(n||0)).toFixed(d)}%`;

  const cards = [
    {
      rank:'01', tag:'Highest share', co: topByPct,
      metric: pct(topByPct.t_pct, 2), tone:'var(--class-true)',
      bg:'linear-gradient(160deg, var(--sage-tint) 0%, var(--canvas) 75%)',
      sub:`of ${fmt(topByPct.n_disc)} passages`,
    },
    {
      rank:'★', tag:'Most true passages', co: topByAbs,
      metric: fmt(Math.round(((topByAbs.t_pct||0)/100) * (topByAbs.n_disc||0))),
      tone:'var(--moss-deep)',
      bg:'linear-gradient(160deg, var(--canvas) 0%, var(--sage-tint) 100%)',
      sub:`out of ${fmt(topByAbs.n_disc)} analysed`,
    },
    {
      rank:'↓', tag:'Lowest share', co: bottomByPct,
      metric: pct(bottomByPct.t_pct, 2), tone:'var(--ink-2)',
      bg:'var(--canvas)',
      sub:`of ${fmt(bottomByPct.n_disc)} passages`,
    },
  ];

  return (
    <section className="section">
      <div className="site-wrap">
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',flexWrap:'wrap',gap:24,marginBottom:32}}>
          <div>
            <EyebrowRow label="Highlights"/>
            <h2 style={{maxWidth:640}}>Best and worst performers, at a glance.</h2>
          </div>
          <button className="btn btn-text" style={{fontSize:13}} onClick={() => setRoute({page:'stats'})}>
            See full stats <Icon name="arrow-right" size={12} style={{marginLeft:2}} className="arrow"/>
          </button>
        </div>

        <div className="stats-leader-row">
          {cards.map((card,i) => (
            <Reveal key={i} delay={i*100}>
              <div className="stats-leader-card stat-card"
                onClick={() => setRoute({ page:'company', id: card.co.id })}
                style={{background:card.bg,'--tone':card.tone}}>
                <div className="stats-leader-rank serif-moment" style={{color:card.tone}}>{card.rank}</div>
                <div className="stats-leader-tag">
                  <span style={{width:7,height:7,borderRadius:999,background:card.tone}}/> {card.tag}
                </div>
                <div className="stats-leader-name">{card.co.name}</div>
                <div className="stats-leader-meta tabular">
                  {card.co.country} · {card.co.commodity}
                </div>
                <div className="stats-leader-metric tabular" style={{color:card.tone}}>
                  {card.metric}
                </div>
                <div className="stats-leader-sub">{card.sub}</div>
                <div className="stats-leader-cta">
                  Open scorecard <Icon name="arrow-right" size={12} className="arrow"/>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};
window.StatsTeaser = StatsTeaser;
