// 06 · The Reckoning — three visualizations. No narrative text except labels and source citations.

function TabReckoning() {
  const stats = window.reckoningStats;
  const companies = window.fortune500Immigrants;
  const nobel = window.nobelTimeline;
  const ratio = window.arrivalRemovalRatio;
  const scrollRef = React.useRef(null);

  // Fortune 500 auto-scroll
  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    let raf, pos = 0;
    const tick = () => {
      pos += 0.3;
      el.scrollLeft = pos;
      if (pos >= el.scrollWidth - el.clientWidth) pos = 0;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Chart dimensions
  const W = 1320, pad = { l: 60, r: 20, t: 10, b: 30 };
  const innerW = W - pad.l - pad.r;

  // ------- Viz 1: Arrivals as % of population ----------
  const pctData = React.useMemo(() => {
    const pops = { 1820: 9.6, 1830: 12.9, 1840: 17.1, 1850: 23.2, 1860: 31.4, 1870: 38.6, 1880: 50.2, 1890: 62.9, 1900: 76.2, 1910: 92.2, 1920: 106, 1930: 123, 1940: 132, 1950: 151, 1960: 179, 1970: 203, 1980: 226, 1990: 248, 2000: 281, 2010: 308, 2020: 331, 2024: 340 };
    const years = Object.keys(pops).map(Number).sort((a, b) => a - b);
    return window.arrivalData.map(d => {
      let pop = 340;
      for (let i = 0; i < years.length - 1; i++) {
        if (d.year >= years[i] && d.year <= years[i + 1]) {
          const t = (d.year - years[i]) / (years[i + 1] - years[i]);
          pop = pops[years[i]] + t * (pops[years[i + 1]] - pops[years[i]]);
          break;
        }
      }
      return { year: d.year, pct: (d.total / (pop * 1_000_000)) * 100 };
    });
  }, []);

  const maxPct = Math.max(...pctData.map(d => d.pct));
  const H1 = 200, innerH1 = H1 - pad.t - pad.b;
  const cx = (yr) => pad.l + ((yr - 1820) / (2024 - 1820)) * innerW;

  // ------- Viz 2: Arrival-to-removal ratio ----------
  const maxRatio = Math.min(200, Math.max(...ratio.map(d => d.ratio)));
  const H2 = 220, innerH2 = H2 - pad.t - pad.b;
  const cx2 = (yr) => pad.l + ((yr - 1892) / (2024 - 1892)) * innerW;

  // ------- Nobel timeline ----------
  const nobelW = 800, nobelH = 100;
  const nobelX = (yr) => 20 + ((yr - 2000) / (2024 - 2000)) * (nobelW - 40);

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="06 · THE RECKONING"
        title=""
        right="No narrative text. Labels and source citations only." />

      {/* Viz 1: Arrivals as % of population */}
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '18px 24px 12px', marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span className="serif" style={{ fontSize: 19, color: '#D4C8B8' }}>
            Arrivals as percentage of US population, year by year
          </span>
          <Confidence level="high" />
        </div>
        <svg width={W} height={H1} style={{ display: 'block' }}>
          <path d={
            pctData.map((d, i) => `${i === 0 ? 'M' : 'L'}${cx(d.year).toFixed(1)},${(pad.t + innerH1 - (d.pct / maxPct) * innerH1).toFixed(1)}`).join(' ') +
            ` L${cx(2024)},${pad.t + innerH1} L${cx(1820)},${pad.t + innerH1} Z`
          } fill="#C9A84C" opacity="0.15" />
          <path d={
            pctData.map((d, i) => `${i === 0 ? 'M' : 'L'}${cx(d.year).toFixed(1)},${(pad.t + innerH1 - (d.pct / maxPct) * innerH1).toFixed(1)}`).join(' ')
          } fill="none" stroke="#C9A84C" strokeWidth="1.5" />
          <line x1={pad.l} x2={W - pad.r} y1={pad.t + innerH1} y2={pad.t + innerH1} stroke="#2A2218" strokeWidth="0.5" />
          {Array.from({ length: 21 }).map((_, i) => {
            const yr = 1820 + i * 10;
            if (yr > 2024) return null;
            return <text key={yr} x={cx(yr)} y={H1 - 4} textAnchor="middle" className="mono" fill="#5A4E3A" fontSize="9" fontFamily="Space Mono">{yr}</text>;
          })}
        </svg>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 10, marginTop: 6 }}>
          The early 1900s were proportionally more intensive than any period since. The chart reframes what {"\""}unprecedented{"\""} means.
        </div>
      </div>

      {/* Viz 2: Arrival-to-removal ratio */}
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '18px 24px 12px', marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span className="serif" style={{ fontSize: 19, color: '#D4C8B8' }}>
            Ratio of arrivals to removals, 1892{'–'}2024
          </span>
          <Confidence level="high" />
        </div>
        <svg width={W} height={H2} style={{ display: 'block' }}>
          {/* Ratio = 1 line (equal arrivals and removals) */}
          <line x1={pad.l} x2={W - pad.r}
            y1={pad.t + innerH2 - (1 / maxRatio) * innerH2}
            y2={pad.t + innerH2 - (1 / maxRatio) * innerH2}
            stroke="#C0392B" strokeWidth="0.8" strokeDasharray="4 3" opacity="0.6" />
          <text x={pad.l - 8} y={pad.t + innerH2 - (1 / maxRatio) * innerH2 + 3}
            textAnchor="end" className="mono" fill="#C0392B" fontSize="8" fontFamily="Space Mono">1:1</text>

          {/* Area fill */}
          <path d={
            ratio.map((d, i) => {
              const r = Math.min(maxRatio, d.ratio);
              return `${i === 0 ? 'M' : 'L'}${cx2(d.year).toFixed(1)},${(pad.t + innerH2 - (r / maxRatio) * innerH2).toFixed(1)}`;
            }).join(' ') +
            ` L${cx2(ratio[ratio.length - 1].year)},${pad.t + innerH2} L${cx2(ratio[0].year)},${pad.t + innerH2} Z`
          } fill="#C9A84C" opacity="0.12" />

          {/* Line */}
          <path d={
            ratio.map((d, i) => {
              const r = Math.min(maxRatio, d.ratio);
              return `${i === 0 ? 'M' : 'L'}${cx2(d.year).toFixed(1)},${(pad.t + innerH2 - (r / maxRatio) * innerH2).toFixed(1)}`;
            }).join(' ')
          } fill="none" stroke="#C9A84C" strokeWidth="1.5" />

          {/* IIRIRA marker */}
          <line x1={cx2(1996)} x2={cx2(1996)} y1={pad.t} y2={pad.t + innerH2}
            stroke="#C0392B" strokeWidth="0.8" strokeDasharray="3 3" opacity="0.5" />
          <text x={cx2(1996)} y={pad.t - 2} textAnchor="middle" className="mono" fill="#C0392B" fontSize="8" fontFamily="Space Mono">IIRIRA</text>

          <line x1={pad.l} x2={W - pad.r} y1={pad.t + innerH2} y2={pad.t + innerH2} stroke="#2A2218" strokeWidth="0.5" />
          {Array.from({ length: 14 }).map((_, i) => {
            const yr = 1890 + i * 10;
            if (yr > 2024) return null;
            return <text key={yr} x={cx2(yr)} y={H2 - 4} textAnchor="middle" className="mono" fill="#5A4E3A" fontSize="9" fontFamily="Space Mono">{yr}</text>;
          })}
        </svg>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 10, marginTop: 6 }}>
          For most of the century the ratio is heavily skewed toward arrivals. The ratio compresses in the 1990s. By 2024, the country removes roughly one person for every three it admits.
        </div>
      </div>

      {/* Viz 3: The Ledger */}
      <HRule>THE LEDGER</HRule>

      {/* Innovation premium circles */}
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '28px 32px', marginTop: 16 }}>
        <div className="serif" style={{ fontSize: 19, color: '#D4C8B8', marginBottom: 20 }}>The innovation premium</div>
        <svg width={600} height={200} style={{ display: 'block', margin: '0 auto' }}>
          <circle cx="150" cy="100" r={60} fill="none" stroke="#C9A84C" strokeWidth="1.5" />
          <text x="150" y="92" textAnchor="middle" className="mono" fill="#C9A84C" fontSize="28" fontWeight="700" fontFamily="Space Mono">16%</text>
          <text x="150" y="112" textAnchor="middle" className="mono" fill="#8A7E6A" fontSize="9" fontFamily="Space Mono">OF INVENTORS</text>

          <circle cx="330" cy="100" r={75} fill="none" stroke="#C9A84C" strokeWidth="1.5" />
          <circle cx="330" cy="100" r={75} fill="#C9A84C" opacity="0.06" />
          <text x="330" y="92" textAnchor="middle" className="mono" fill="#C9A84C" fontSize="32" fontWeight="700" fontFamily="Space Mono">23%</text>
          <text x="330" y="112" textAnchor="middle" className="mono" fill="#8A7E6A" fontSize="9" fontFamily="Space Mono">OF PATENTS</text>

          <circle cx="510" cy="100" r={90} fill="none" stroke="#C9A84C" strokeWidth="1" strokeDasharray="3 3" />
          <text x="510" y="92" textAnchor="middle" className="mono" fill="#C9A84C" fontSize="36" fontWeight="700" fontFamily="Space Mono">32%</text>
          <text x="510" y="112" textAnchor="middle" className="mono" fill="#8A7E6A" fontSize="9" fontFamily="Space Mono">TOTAL OUTPUT</text>
          <text x="510" y="126" textAnchor="middle" className="mono" fill="#5A4E3A" fontSize="8" fontFamily="Space Mono">incl. spillover</text>
        </svg>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 9, textAlign: 'center', marginTop: 8 }}>
          Source: NBER Working Paper 30797 {'·'} Bernstein et al.
        </div>
      </div>

      {/* Key stats grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 16 }}>
        <Readout label="FORTUNE 500 IMMIGRANT-FOUNDED" value={stats.fortune500Pct + '%'} sub={stats.fortune500Revenue + ' revenue'} accent="#C9A84C" size={28} />
        <Readout label="US ENTREPRENEURS" value={'1 in ' + (100 / stats.entrepreneurPct)} sub="Who are immigrants" accent="#C9A84C" size={28} />
        <Readout label="US NOBEL PRIZES (SCIENCE)" value={'1 in ' + Math.round(100 / stats.nobelPct)} sub="Last decade, awarded to immigrants" accent="#C9A84C" size={28} />
        <Readout label="EMPLOYEES" value={stats.fortune500Employees} sub="At immigrant-founded Fortune 500s" accent="#D4C8B8" size={28} />
      </div>

      {/* Nobel timeline dots */}
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '20px 24px', marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <span className="serif" style={{ fontSize: 17, color: '#D4C8B8' }}>
            US Nobel Prizes in Science, 2000{'–'}2024
          </span>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#C9A84C' }} />
              <span className="mono" style={{ color: '#8A7E6A', fontSize: 9 }}>Immigrant laureate</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#D4C8B8', opacity: 0.5 }} />
              <span className="mono" style={{ color: '#8A7E6A', fontSize: 9 }}>Native-born</span>
            </div>
          </div>
        </div>
        <svg width={nobelW} height={nobelH} style={{ display: 'block', margin: '0 auto' }}>
          {/* Year axis */}
          <line x1="20" x2={nobelW - 20} y1={nobelH - 16} y2={nobelH - 16} stroke="#2A2218" strokeWidth="0.5" />
          {Array.from({ length: 13 }).map((_, i) => {
            const yr = 2000 + i * 2;
            return <text key={yr} x={nobelX(yr)} y={nobelH - 4} textAnchor="middle" className="mono" fill="#5A4E3A" fontSize="8" fontFamily="Space Mono">{yr}</text>;
          })}

          {/* Dots — stacked per year */}
          {(() => {
            const byYear = {};
            nobel.forEach(n => {
              if (!byYear[n.year]) byYear[n.year] = [];
              byYear[n.year].push(n);
            });
            const dots = [];
            Object.entries(byYear).forEach(([yr, entries]) => {
              entries.forEach((n, j) => {
                dots.push(
                  <circle key={n.name}
                    cx={nobelX(Number(yr))}
                    cy={nobelH - 26 - j * 14}
                    r={5}
                    fill={n.immigrant ? '#C9A84C' : '#D4C8B8'}
                    opacity={n.immigrant ? 0.9 : 0.3}
                    stroke={n.immigrant ? '#C9A84C' : 'none'}
                    strokeWidth="0.5"
                  >
                    <title>{n.name} ({n.field}, {n.year}){n.immigrant ? ' — immigrant' : ''}</title>
                  </circle>
                );
              });
            });
            return dots;
          })()}
        </svg>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 9, textAlign: 'center', marginTop: 4 }}>
          {(() => {
            const imm = nobel.filter(n => n.immigrant).length;
            const total = nobel.length;
            return `${imm} of ${total} laureates (${Math.round(imm/total*100)}%) are immigrants. The ratio speaks for itself.`;
          })()}
        </div>
      </div>

      {/* Fortune 500 scroll */}
      <div style={{ marginTop: 16, border: '1px solid #2A2218', background: '#1E1810', padding: '16px 0', overflow: 'hidden' }}>
        <div ref={scrollRef} style={{
          display: 'flex', gap: 32, overflowX: 'hidden', whiteSpace: 'nowrap', padding: '0 24px',
        }}>
          {[...companies, ...companies, ...companies].map((name, i) => (
            <span key={i} className="display" style={{
              color: '#D4C8B8', fontSize: 22, fontWeight: 400, fontStyle: 'italic',
              opacity: 0.7,
            }}>
              {name}
            </span>
          ))}
        </div>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 9, textAlign: 'center', marginTop: 10, letterSpacing: 0.2 }}>
          COMPANIES FOUNDED BY IMMIGRANTS OR THEIR CHILDREN
        </div>
      </div>

      {/* Workforce stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginTop: 16 }}>
        <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '16px 20px' }}>
          <Tick color="#C9A84C">{'▌'} HEALTHCARE</Tick>
          <div style={{ display: 'flex', gap: 24, marginTop: 12 }}>
            <Readout label="HEALTH AIDES" value="28%" sub="Who are immigrants" accent="#C9A84C" size={24} />
            <Readout label="NURSES" value="16%" sub="Who are immigrants" accent="#C9A84C" size={24} />
          </div>
        </div>
        <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '16px 20px' }}>
          <Tick color="#C9A84C">{'▌'} FORTUNE 500 BY SECTOR</Tick>
          <div style={{ marginTop: 12 }}>
            {[
              ['Professional services', '80.0%'],
              ['Manufacturing', '65.6%'],
              ['Information technology', '57.5%'],
            ].map(([sector, pct]) => (
              <div key={sector} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: '1px solid #1A1510' }}>
                <span className="mono" style={{ color: '#8A7E6A', fontSize: 11 }}>{sector}</span>
                <span className="mono" style={{ color: '#C9A84C', fontSize: 11, fontWeight: 700 }}>{pct}</span>
              </div>
            ))}
            <div className="mono" style={{ color: '#5A4E3A', fontSize: 9, marginTop: 6 }}>% founded by immigrants or their children</div>
          </div>
        </div>
      </div>

      {/* Closing line */}
      <div style={{
        marginTop: 40, padding: '20px 28px', borderTop: '1px solid #2A2218', borderBottom: '1px solid #2A2218',
        textAlign: 'center',
      }}>
        <div className="mono" style={{ color: '#8A7E6A', fontSize: 11, letterSpacing: 0.1, lineHeight: 1.6 }}>
          All figures sourced from peer-reviewed research, USPTO data, US Census, BLS, and DHS. Methodology in Tab 07.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TabReckoning });
