// 01 · The Rate

function TabRate() {
  const data = window.RATE_DATA || [];
  const gaData = (window.RATE_DATA || []).filter(d => d.ga_rate != null);
  const events = window.regulatoryEvents || [];
  const [hoverYear, setHoverYear] = React.useState(null);

  // Chart geometry
  const W = 1140, H = 380, padL = 64, padR = 40, padT = 28, padB = 44;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const yearMin = 1926, yearMax = 2024;
  const xs = (y) => padL + ((y - yearMin) / (yearMax - yearMin)) * innerW;

  // Y scale — rate per 100k flight hours
  const commRates = data.map(d => d.commercial_rate).filter(v => v != null);
  const gaRates = gaData.map(d => d.ga_rate).filter(v => v != null);
  const rateMax = Math.max(...commRates, ...gaRates, 1) * 1.15;
  const ys = (v) => padT + (1 - (v / rateMax)) * innerH;

  // Build commercial line path
  const commPoints = data.filter(d => d.commercial_rate != null);
  const commPath = commPoints.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(d.year)},${ys(d.commercial_rate)}`).join(' ');

  // Area fill under commercial line (12% opacity)
  const commArea = commPoints.length > 0
    ? commPath + ` L${xs(commPoints[commPoints.length - 1].year)},${ys(0)} L${xs(commPoints[0].year)},${ys(0)} Z`
    : '';

  // GA line path (starts 1962)
  const gaPoints = gaData.filter(d => d.ga_rate != null);
  const gaPath = gaPoints.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(d.year)},${ys(d.ga_rate)}`).join(' ');

  // Gridlines
  const rateTicks = [];
  if (rateMax > 0) {
    const step = rateMax > 20 ? 10 : rateMax > 5 ? 2 : 1;
    for (let v = 0; v <= rateMax; v += step) rateTicks.push(v);
  }
  const decadeTicks = [1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020];

  // Hover
  const handleMouseMove = (e) => {
    const svg = e.currentTarget;
    const rect = svg.getBoundingClientRect();
    const svgX = ((e.clientX - rect.left) / rect.width) * W;
    const year = Math.round(yearMin + ((svgX - padL) / innerW) * (yearMax - yearMin));
    const clamped = Math.max(yearMin, Math.min(yearMax, year));
    const closest = data.reduce((best, d) => Math.abs(d.year - clamped) < Math.abs(best.year - clamped) ? d : best, data[0]);
    setHoverYear(closest ? closest.year : null);
  };

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

  // Colgan annotation
  const colganPoint = data.find(d => d.year === 2009);

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="01 · THE RATE" title="A century of aviation fatality rates." right="NTSB · FAA · 1926–2024" />

      {/* 6-stat readout grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 1, background: 'var(--line)', border: '1px solid var(--line)', marginBottom: 40 }}>
        {(window.RATE_STATS || []).map((s, i) => (
          <div key={i} style={{ background: 'var(--bg-2)', padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 8, position: 'relative', overflow: 'hidden', minHeight: 132 }}>
            {s.pulse && (
              <span style={{ position: 'absolute', top: 12, right: 12, width: 6, height: 6, background: 'var(--red)', borderRadius: '50%', animation: 'pulse 1.6s ease-in-out infinite' }} />
            )}
            <div className="mono" style={{ color: 'var(--ink-dim)', fontSize: 9.5, letterSpacing: 0.18, textTransform: 'uppercase' }}>
              {s.label}
            </div>
            <div className="mono" style={{ color: s.accent || 'var(--ink)', fontSize: 30, fontWeight: 700, lineHeight: 1, letterSpacing: -0.5 }}>
              {s.value}
            </div>
            <div className="mono" style={{ color: 'var(--ink-dim)', fontSize: 10, opacity: 0.85 }}>
              {s.sub}
            </div>
          </div>
        ))}
      </div>

      {/* Main chart */}
      <div style={{ border: '1px solid var(--line)', background: 'rgba(20,20,20,0.6)', position: 'relative' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '20px 24px 8px' }}>
          <div>
            <div className="serif" style={{ fontSize: 20, color: 'var(--ink)', letterSpacing: -0.2 }}>
              Fatal accident rate per 100,000 flight hours, 1926–2024
            </div>
            <div className="mono" style={{ color: 'var(--ink-dim)', fontSize: 11, marginTop: 4, letterSpacing: 0.04 }}>
              Part 121 commercial (red, left axis) · Part 91 general aviation (amber, from 1962)
            </div>
          </div>
          <div style={{ display: 'flex', gap: 16, alignItems: 'flex-end' }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 16, height: 2, background: 'var(--red)' }} />
                <span className="mono" style={{ fontSize: 9, color: 'var(--ink-dim)', textTransform: 'uppercase' }}>Commercial</span>
              </span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 16, height: 2, background: 'var(--amber)' }} />
                <span className="mono" style={{ fontSize: 9, color: 'var(--ink-dim)', textTransform: 'uppercase' }}>GA</span>
              </span>
            </div>
            <Confidence level="high" />
          </div>
        </div>

        <svg viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%', height: 'auto' }}
             onMouseMove={handleMouseMove}
             onMouseLeave={() => setHoverYear(null)}>
          {/* Horizontal gridlines */}
          {rateTicks.map(v => (
            <line key={`g${v}`} x1={padL} x2={W - padR} y1={ys(v)} y2={ys(v)}
                  stroke="#1A1A1A" strokeWidth="0.5" strokeDasharray="3 5" />
          ))}

          {/* Left axis labels */}
          {rateTicks.map(v => (
            <text key={`rl${v}`} x={padL - 8} y={ys(v) + 3} textAnchor="end"
                  fill="var(--ink-dim)" fontSize="9" fontFamily="Space Mono" opacity="0.7">
              {v.toFixed(v < 1 ? 1 : 0)}
            </text>
          ))}

          {/* Decade tick marks */}
          {decadeTicks.map(y => (
            <g key={y}>
              <line x1={xs(y)} x2={xs(y)} y1={padT + innerH} y2={padT + innerH + 4} stroke="var(--ink-dimmer)" strokeWidth="0.6" />
              <text x={xs(y)} y={padT + innerH + 18} textAnchor="middle"
                    fill="var(--ink-dimmer)" fontSize="9" fontFamily="Space Mono">{y}</text>
            </g>
          ))}

          {/* Regulatory event vertical dashed lines */}
          {events.map((evt, i) => (
            <line key={`evt${i}`} x1={xs(evt.year)} x2={xs(evt.year)} y1={padT} y2={padT + innerH}
                  stroke="var(--amber)" strokeWidth="0.7" strokeDasharray="4 3" opacity="0.5" />
          ))}

          {/* Commercial area fill */}
          {commArea && <path d={commArea} fill="var(--red)" opacity="0.12" />}

          {/* Commercial line */}
          {commPath && <path d={commPath} fill="none" stroke="var(--red)" strokeWidth="2" />}

          {/* GA line */}
          {gaPath && <path d={gaPath} fill="none" stroke="var(--amber)" strokeWidth="1.5" opacity="0.9" />}

          {/* Colgan 3407 annotation */}
          {colganPoint && (
            <g>
              <line x1={xs(2009)} x2={xs(2009)}
                    y1={ys(colganPoint.commercial_rate || 0) - 4} y2={ys(colganPoint.commercial_rate || 0) - 40}
                    stroke="var(--gold)" strokeWidth="0.6" />
              <text x={xs(2009) + 5} y={ys(colganPoint.commercial_rate || 0) - 46} textAnchor="start"
                    fill="var(--gold)" fontSize="9" fontFamily="Space Mono" letterSpacing="0.1">
                COLGAN 3407
              </text>
              <text x={xs(2009) + 5} y={ys(colganPoint.commercial_rate || 0) - 34} textAnchor="start"
                    fill="var(--gold)" fontSize="8" fontFamily="Space Mono" opacity="0.7">
                LAST FATAL PART 121
              </text>
            </g>
          )}

          {/* Hover crosshair */}
          {hovered && (
            <g>
              <line x1={xs(hovered.year)} x2={xs(hovered.year)} y1={padT} y2={padT + innerH}
                    stroke="var(--gold)" strokeWidth="0.6" strokeDasharray="2 2" opacity="0.7" />
              {hovered.commercial_rate != null && (
                <circle cx={xs(hovered.year)} cy={ys(hovered.commercial_rate)} r="3.5"
                        fill="var(--red)" stroke="var(--bg)" strokeWidth="1.5" />
              )}
              {hovered.ga_rate != null && (
                <circle cx={xs(hovered.year)} cy={ys(hovered.ga_rate)} r="2.5"
                        fill="var(--amber)" stroke="var(--bg)" strokeWidth="1.5" />
              )}
            </g>
          )}
        </svg>

        {/* Hover readout panel */}
        <div style={{
          position: 'absolute', top: 24, right: 24, width: 220,
          border: '1px solid var(--line)', background: 'rgba(10,10,10,0.92)',
          padding: '10px 14px', pointerEvents: 'none',
        }}>
          <Tick>{hovered ? 'YEAR' : '— · — · —'}</Tick>
          <div className="mono" style={{
            fontSize: 28, color: hovered ? 'var(--ink)' : 'var(--ink-dimmer)',
            fontWeight: 700, lineHeight: 1.1, marginTop: 4,
          }}>
            {hovered ? hovered.year : '— — — —'}
          </div>
          <div className="mono" style={{ color: 'var(--red)', fontSize: 11, marginTop: 6 }}>
            Commercial · {hovered && hovered.commercial_rate != null ? hovered.commercial_rate.toFixed(2) : '—'}
          </div>
          <div className="mono" style={{ color: 'var(--amber)', fontSize: 11, marginTop: 3 }}>
            GA · {hovered && hovered.ga_rate != null ? hovered.ga_rate.toFixed(2) : '—'}
          </div>
          {hoveredEvent && (
            <React.Fragment>
              <div style={{ height: 1, background: 'var(--line)', margin: '8px 0' }} />
              <div className="serif" style={{ color: 'var(--gold)', fontSize: 11, fontStyle: 'italic', lineHeight: 1.4 }}>
                {hoveredEvent.name}
              </div>
            </React.Fragment>
          )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 24px 16px' }}>
          <Tick>n = {data.length} years · NTSB accident records + BTS flight hours</Tick>
          <Tick>SOURCE = NTSB AVIATION ACCIDENT DATABASE</Tick>
        </div>
      </div>

      {/* Event strip + thesis */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 40 }}>
        {/* Left: regulatory event strip */}
        <div style={{ border: '1px solid var(--line)', background: 'rgba(20,20,20,0.6)' }}>
          <div style={{ padding: '18px 20px 4px' }}>
            <div className="serif" style={{ fontSize: 17, color: 'var(--ink)' }}>Regulatory Milestones</div>
            <div className="mono" style={{ color: 'var(--ink-dim)', fontSize: 11, marginTop: 4 }}>
              Each vertical line on the chart marks a rule written after a crash.
            </div>
          </div>
          <div style={{ padding: '12px 20px 20px', display: 'flex', flexDirection: 'column', gap: 0 }}>
            {events.map((evt, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '52px 1fr', gap: 12, alignItems: 'baseline',
                padding: '6px 0', borderBottom: '1px solid var(--line)',
              }}>
                <span className="mono" style={{ color: 'var(--amber)', fontSize: 11, fontWeight: 700 }}>{evt.year}</span>
                <span className="mono" style={{ color: 'var(--ink-dim)', fontSize: 10, lineHeight: 1.4 }}>{evt.name}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Right: thesis quote */}
        <div style={{
          border: '1px solid rgba(201,168,76,0.27)', background: 'rgba(201,168,76,0.04)',
          padding: '24px 24px 22px', position: 'relative',
        }}>
          <div className="mono" style={{ color: 'var(--gold)', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase' }}>
            — THE THESIS —
          </div>
          <div className="serif" style={{
            fontSize: 21, lineHeight: 1.35, color: 'var(--ink)', marginTop: 14, letterSpacing: -0.1, fontWeight: 300,
            fontStyle: 'italic', textWrap: 'pretty',
          }}>
            "Aviation is the only industry in human history that learned from every single mistake and made it mandatory for everyone else to learn too."
          </div>
          <div className="mono" style={{ color: 'var(--ink-dim)', fontSize: 11, marginTop: 18, letterSpacing: 0.04 }}>
            — The rate went to zero. The question is how.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TabRate });
