// 01 · The Waves — a century of arrivals as a flow.

function TabWaves() {
  const [hoverYear, setHoverYear] = React.useState(null);
  const [filterCountry, setFilterCountry] = React.useState(null);
  const data = window.arrivalData;
  const W = 1320, H = 400, pad = { l: 60, r: 20, t: 10, b: 40 };
  const innerW = W - pad.l - pad.r;
  const innerH = H - pad.t - pad.b;
  const maxTotal = Math.max(...data.map(d => d.total));

  const x = (yr) => pad.l + ((yr - 1820) / (2024 - 1820)) * innerW;
  const barW = Math.max(1, innerW / data.length - 0.6);

  const hovered = hoverYear != null ? data.find(d => d.year === hoverYear) : null;

  // Era bands
  const eras = window.ERAS;

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="01 · THE WAVES"
        title="A century of arrivals. Each year a bar. Color tells you where they came from."
        right="DHS Yearbook · 1820–2024" />

      {/* Stat block */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 32 }}>
        <Readout label="TOTAL ARRIVALS" value={fmt(window.META.totalArrivals)} sub="1820–2024" accent="#C9A84C" />
        <Readout label="PEAK YEAR" value="1907" sub="1,285,349 arrivals" accent="#C9A84C" />
        <Readout label="1924 ACT IMPACT" value={'−' + Math.round((1 - 294314/706896) * 100) + '%'} sub="706,896 → 294,314 in one year" accent="#C0392B" />
        <Readout label="COUNTRIES OF ORIGIN" value="194" sub="Distinct nations in the full dataset" />
        <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.5)', padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 6, minHeight: 110 }}>
          <LiveCounter />
          <div className="mono" style={{ color: '#5A4E3A', fontSize: 10, marginTop: 4 }}>
            Removals since you opened this tab
          </div>
        </div>
      </div>

      {/* Main chart */}
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '18px 24px 12px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <div>
            <span className="serif" style={{ fontSize: 19, color: '#D4C8B8' }}>Annual immigration to the United States</span>
            {filterCountry && (
              <span className="mono" style={{ color: '#C9A84C', fontSize: 11, marginLeft: 12, cursor: 'pointer' }}
                onClick={() => setFilterCountry(null)}>
                {filterCountry} ×
              </span>
            )}
          </div>
          <Confidence level="high" />
        </div>

        <svg width={W} height={H} style={{ display: 'block' }}>
          {/* Era bands */}
          {eras.map(era => (
            <g key={era.id}>
              <rect x={x(era.start)} y={pad.t} width={x(era.end) - x(era.start)} height={innerH}
                fill={era.color} opacity="0.04" />
              <text x={x(era.start) + (x(era.end) - x(era.start)) / 2} y={pad.t + 14}
                textAnchor="middle" className="mono" fill={era.color} fontSize="9"
                fontFamily="Space Mono" letterSpacing="0.1" opacity="0.5">
                {era.label.toUpperCase()}
              </text>
            </g>
          ))}

          {/* Grid lines */}
          {[0.25, 0.5, 0.75, 1.0].map(t => {
            const yy = pad.t + innerH - t * innerH;
            return (
              <g key={t}>
                <line x1={pad.l} x2={W - pad.r} y1={yy} y2={yy} stroke="#2A2218" strokeWidth="0.5" />
                <text x={pad.l - 8} y={yy + 3} textAnchor="end" className="mono"
                  fill="#5A4E3A" fontSize="9" fontFamily="Space Mono">
                  {fmt(Math.round(maxTotal * t))}
                </text>
              </g>
            );
          })}

          {/* Bars */}
          {data.map(d => {
            const h = (d.total / maxTotal) * innerH;
            const bx = x(d.year);
            const by = pad.t + innerH - h;
            const dominant = d.origins[0];
            const color = window.regionColor(dominant.region);
            const isHovered = hoverYear === d.year;

            return (
              <rect key={d.year} x={bx} y={by} width={barW} height={h}
                fill={color} opacity={isHovered ? 1 : 0.85}
                stroke={isHovered ? '#F2EBD9' : 'none'} strokeWidth={isHovered ? 1 : 0}
                onMouseEnter={() => setHoverYear(d.year)}
                onMouseLeave={() => setHoverYear(null)}
                style={{ cursor: 'pointer' }}
              />
            );
          })}

          {/* Key legislation markers */}
          {[1882, 1924, 1965, 1996].map(yr => (
            <g key={yr}>
              <line x1={x(yr)} x2={x(yr)} y1={pad.t} y2={pad.t + innerH + 6}
                stroke="#C9A84C" strokeWidth="0.8" strokeDasharray="3 3" opacity="0.6" />
              <text x={x(yr)} y={pad.t + innerH + 18} textAnchor="middle"
                className="mono" fill="#C9A84C" fontSize="9" fontFamily="Space Mono" letterSpacing="0.05">
                {yr}
              </text>
            </g>
          ))}

          {/* Decade axis labels */}
          {Array.from({ length: 21 }).map((_, i) => {
            const yr = 1820 + i * 10;
            if (yr > 2024) return null;
            return (
              <text key={yr} x={x(yr)} y={H - 4} textAnchor="middle"
                className="mono" fill="#5A4E3A" fontSize="9" fontFamily="Space Mono">
                {yr}
              </text>
            );
          })}
        </svg>

        {/* Tooltip */}
        {hovered && (
          <div style={{
            position: 'absolute', pointerEvents: 'none',
            background: '#1E1810', border: '1px solid #2A2218', padding: '12px 16px',
            zIndex: 10, minWidth: 200,
          }}>
            <div className="mono" style={{ color: '#C9A84C', fontSize: 14, fontWeight: 700 }}>{hovered.year}</div>
            <div className="mono" style={{ color: '#D4C8B8', fontSize: 18, fontWeight: 700, marginTop: 4 }}>
              {hovered.total.toLocaleString()} arrivals
            </div>
            <div style={{ marginTop: 8, borderTop: '1px solid #2A2218', paddingTop: 8 }}>
              {hovered.origins.slice(0, 3).map(o => (
                <div key={o.country} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, marginTop: 2 }}>
                  <span className="mono" style={{ color: window.regionColor(o.region), fontSize: 10, fontVariant: 'all-small-caps' }}>{o.country}</span>
                  <span className="mono" style={{ color: '#8A7E6A', fontSize: 10 }}>{Math.round(o.pct * 100)}%</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Era legend */}
      <div style={{ display: 'flex', gap: 1, marginTop: 16, background: '#2A2218' }}>
        {eras.map(era => (
          <div key={era.id} style={{
            flex: era.end - era.start, background: '#1E1810', padding: '12px 14px',
          }}>
            <div className="mono" style={{ color: era.color, fontSize: 10, letterSpacing: 0.1, textTransform: 'uppercase' }}>
              {era.start}–{era.end}
            </div>
            <div className="display" style={{ color: '#D4C8B8', fontSize: 14, marginTop: 4, fontStyle: 'italic' }}>
              {era.label}
            </div>
            <div className="serif" style={{ color: '#8A7E6A', fontSize: 12, marginTop: 4, lineHeight: 1.4 }}>
              {era.brief}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TabWaves });
