// 01 · The Baseline

function TabBaseline() {
  const data = window.annualAnomaly;
  const [hoverYear, setHoverYear] = React.useState(null);

  // Layout: anomaly chart — auto-scale Y axis from data
  const W = 1140, H = 320, padL = 48, padR = 16, padT = 24, padB = 36;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const yearMin = data[0]?.year || 1900, yearMax = data[data.length - 1]?.year || 2025;
  const xs = (y) => padL + ((y - yearMin) / (yearMax - yearMin)) * innerW;
  const dataMax = Math.max(...data.map(d => d.anomaly));
  const dataMin = Math.min(...data.map(d => d.anomaly));
  const yMax = Math.ceil(Math.max(dataMax * 1.15, 1));
  const yMin = Math.floor(Math.min(dataMin * 1.15, -1));
  const ys = (v) => padT + (1 - (v - yMin) / (yMax - yMin)) * innerH;
  const barW = Math.max(2, innerW / (yearMax - yearMin + 1) - 1.2);
  const yTicks = [];
  for (let v = yMin; v <= yMax; v++) yTicks.push(v);

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

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="01 · THE BASELINE" title="The establishment of normal — and the departure from it." right="Continental US · 1900–2025" />

      {/* Counter strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 1, background: '#1B2740', border: '1px solid #1B2740', marginBottom: 40 }}>
        {window.BASELINE_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 }}>
            {i === 5 && (
              <span style={{ position: 'absolute', top: 12, right: 12, width: 6, height: 6, background: '#D73027', borderRadius: '50%', animation: 'pulse 1.6s ease-in-out infinite' }} />
            )}
            <div className="mono" style={{ color: '#4E6A82', fontSize: 9.5, letterSpacing: 0.18, textTransform: 'uppercase' }}>
              {s.label}
            </div>
            <div className="mono" style={{ color: i === 2 ? '#D73027' : i === 3 ? '#74ADD1' : i === 4 ? '#FDAE61' : '#E6ECF2', fontSize: 30, fontWeight: 700, lineHeight: 1, letterSpacing: -0.5 }}>
              {s.value}
            </div>
            <div className="mono" style={{ color: '#8BAFC7', fontSize: 10, opacity: 0.85 }}>
              {s.sub}
            </div>
          </div>
        ))}
      </div>

      {/* The big chart */}
      <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,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: '#E6ECF2', letterSpacing: -0.2 }}>
              Annual mean temperature anomaly, continental US
            </div>
            <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 4, letterSpacing: 0.04 }}>
              °F above (red) or below (blue) the 1900–1950 mean. Each bar one calendar year.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 16, alignItems: 'flex-end' }}>
            <TempLegend width={220} />
            <Confidence level="high" />
          </div>
        </div>

        <svg viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%', height: 'auto' }}
             onMouseLeave={() => setHoverYear(null)}>
          {/* Gridlines */}
          {yTicks.map(v => (
            <g key={v}>
              <line x1={padL} x2={W - padR} y1={ys(v)} y2={ys(v)}
                    stroke={v === 0 ? '#8BAFC7' : '#1B2740'} strokeWidth={v === 0 ? 1 : 0.5}
                    strokeDasharray={v === 0 ? '0' : '2 4'} />
              <text x={padL - 8} y={ys(v) + 3} textAnchor="end"
                    className="mono" fill="#4E6A82" fontSize="9" fontFamily="Space Mono">
                {v > 0 ? `+${v}` : v}°
              </text>
            </g>
          ))}
          <text x={padL - 30} y={ys(0) + 3} className="mono" fill="#8BAFC7" fontSize="9" fontFamily="Space Mono">BASE</text>

          {/* Decade tick marks */}
          {[1900, 1920, 1940, 1960, 1980, 2000, 2020].filter(y => y >= yearMin && y <= yearMax).map(y => (
            <g key={y}>
              <line x1={xs(y)} x2={xs(y)} y1={padT + innerH} y2={padT + innerH + 4} stroke="#4E6A82" strokeWidth="0.6" />
              <text x={xs(y)} y={padT + innerH + 16} textAnchor="middle"
                    className="mono" fill="#4E6A82" fontSize="9" fontFamily="Space Mono">{y}</text>
            </g>
          ))}

          {/* Bars */}
          {data.map(d => {
            const isHover = hoverYear === d.year;
            return (
              <rect key={d.year}
                x={xs(d.year) - barW / 2}
                y={d.anomaly >= 0 ? ys(d.anomaly) : ys(0)}
                width={barW}
                height={Math.abs(ys(d.anomaly) - ys(0))}
                fill={window.anomalyColor(d.anomaly)}
                opacity={hoverYear && !isHover ? 0.35 : 1}
                onMouseEnter={() => setHoverYear(d.year)}
              />
            );
          })}

          {/* Notable annotations — dynamically positioned */}
          {(() => {
            const annotations = [];
            const d1936 = data.find(x => x.year === 1936);
            if (d1936) annotations.push({ year: 1936, label: 'Dust Bowl', anchor: 'start', d: d1936 });
            const d1970 = data.find(x => x.year === 1970);
            if (d1970 && d1970.anomaly < 0) annotations.push({ year: 1970, label: 'Mid-century cooling', anchor: 'middle', d: d1970 });
            const lastYear = data[data.length - 1];
            if (lastYear) annotations.push({ year: lastYear.year, label: `+${lastYear.anomaly.toFixed(1)}°F`, anchor: 'end', d: lastYear });
            return annotations.map(a => (
              <g key={a.year}>
                <line x1={xs(a.year)} x2={xs(a.year)} y1={ys(a.d.anomaly) - 4} y2={ys(a.d.anomaly) - 18}
                      stroke="#C9A84C" strokeWidth="0.6" />
                <text x={xs(a.year)} y={ys(a.d.anomaly) - 24} textAnchor={a.anchor}
                      className="mono" fill="#C9A84C" fontSize="9" fontFamily="Space Mono"
                      letterSpacing="0.1">
                  {a.label.toUpperCase()}
                </text>
              </g>
            ));
          })()}

          {/* Hover crosshair */}
          {hovered && (
            <g>
              <line x1={xs(hovered.year)} x2={xs(hovered.year)} y1={padT} y2={padT + innerH}
                    stroke="#C9A84C" strokeWidth="0.6" strokeDasharray="2 2" opacity="0.7" />
            </g>
          )}
        </svg>

        {/* Hover readout (always-on, fixed position) */}
        <div style={{
          position: 'absolute', top: 24, right: 24, width: 200,
          border: '1px solid #243353', background: 'rgba(10,15,26,0.85)',
          padding: '10px 14px', pointerEvents: 'none',
        }}>
          <Tick>{hovered ? 'YEAR' : '— · — · —'}</Tick>
          <div className="mono" style={{
            fontSize: 28, color: hovered ? window.anomalyColor(hovered.anomaly) : '#4E6A82',
            fontWeight: 700, lineHeight: 1.1, marginTop: 4,
          }}>
            {hovered ? hovered.year : '— — — —'}
          </div>
          <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 6 }}>
            Anomaly · {hovered ? (hovered.anomaly > 0 ? `+${hovered.anomaly}` : hovered.anomaly) : '—'} °F
          </div>
          <div style={{ height: 1, background: '#1B2740', margin: '8px 0' }} />
          <div className="serif" style={{ color: '#8BAFC7', fontSize: 11, fontStyle: 'italic', lineHeight: 1.4 }}>
            {hovered ? noteForYear(hovered.year, hovered.anomaly) : 'Hover any bar to read its value.'}
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 24px 16px' }}>
          <Tick>n = 1,218 stations · gridded average</Tick>
          <Tick>BASELINE = MEAN(1900–1950)</Tick>
        </div>
      </div>

      {/* Below: rolling 12-mo and the thesis quote */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 40 }}>
        <RollingPanel />
        <ThesisQuote />
      </div>
    </div>
  );
}

function noteForYear(y, a) {
  if (y === 1936) return 'Dust Bowl peak. 12 states posted all-time highs that July.';
  if (y === 1934) return 'Drought, dust, and the hottest summer on the Great Plains.';
  if (y >= 1960 && y <= 1976) return 'Mid-century cooling — partly aerosol-driven.';
  if (y === 2024) return 'Warmest year in the continental record.';
  if (y === 2023) return 'Second-warmest. Marine heatwaves off both coasts.';
  if (y === 2012) return 'US summer drought. Corn belt failed.';
  if (a > 1.5) return 'Among the warmest years on record.';
  if (a < -1.0) return 'Among the cooler years on record.';
  return 'Within the bounds of historical variability.';
}

function RollingPanel() {
  // 12-mo running mean since 1900, but rendered as a long line.
  const data = window.annualAnomaly;
  const W = 640, H = 200, padL = 40, padR = 14, padT = 18, padB = 28;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const rYearMin = data[0]?.year || 1900, rYearMax = data[data.length-1]?.year || 2025;
  const xs = (y) => padL + ((y - rYearMin) / (rYearMax - rYearMin)) * innerW;
  const smoothMax = Math.max(...data.map(d => d.anomaly));
  const ymin = -1.5, ymax = Math.max(3, Math.ceil(smoothMax * 1.1));
  const ys = (v) => padT + (1 - (v - ymin) / (ymax - ymin)) * innerH;

  // 5-yr trailing mean
  const smoothed = data.map((d, i) => {
    const slice = data.slice(Math.max(0, i - 4), i + 1);
    const m = slice.reduce((s, x) => s + x.anomaly, 0) / slice.length;
    return { year: d.year, v: m };
  });

  const path = smoothed.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(d.year)},${ys(d.v)}`).join(' ');
  const area = path + ` L${xs(rYearMax)},${ys(ymin)} L${xs(rYearMin)},${ys(ymin)} Z`;

  return (
    <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,0.6)' }}>
      <div style={{ padding: '18px 20px 4px' }}>
        <div className="serif" style={{ fontSize: 17, color: '#E6ECF2' }}>The 5-year running mean</div>
        <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 4 }}>
          The shape of the century, with the year-to-year noise filtered out.
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto' }}>
        <defs>
          <linearGradient id="rollFill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#D73027" stopOpacity="0.4" />
            <stop offset="55%" stopColor="#FDAE61" stopOpacity="0.15" />
            <stop offset="100%" stopColor="#2166AC" stopOpacity="0.0" />
          </linearGradient>
        </defs>
        {Array.from({ length: ymax - ymin + 2 }, (_, i) => ymin + i).filter(v => v <= ymax).map(v => (
          <g key={v}>
            <line x1={padL} x2={W - padR} y1={ys(v)} y2={ys(v)} stroke={v === 0 ? '#8BAFC7' : '#1B2740'} strokeDasharray={v === 0 ? '0' : '2 4'} strokeWidth={v === 0 ? 1 : 0.5} />
            <text x={padL - 6} y={ys(v) + 3} textAnchor="end" className="mono" fill="#4E6A82" fontSize="9" fontFamily="Space Mono">{v > 0 ? `+${v}` : v}°</text>
          </g>
        ))}
        {[1900, 1925, 1950, 1975, 2000, 2025].filter(y => y >= rYearMin && y <= rYearMax).map(y => (
          <text key={y} x={xs(y)} y={padT + innerH + 16} textAnchor="middle" className="mono" fill="#4E6A82" fontSize="9" fontFamily="Space Mono">{y}</text>
        ))}
        <path d={area} fill="url(#rollFill)" />
        <path d={path} fill="none" stroke="#E6ECF2" strokeWidth="1.6" />
      </svg>
    </div>
  );
}

function ThesisQuote() {
  return (
    <div style={{
      border: '1px solid #C9A84C44', background: 'rgba(201,168,76,0.04)',
      padding: '24px 24px 22px', position: 'relative',
    }}>
      <div className="mono" style={{ color: '#C9A84C', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase' }}>
        — THE THESIS —
      </div>
      <div className="serif" style={{
        fontSize: 22, lineHeight: 1.32, color: '#E6ECF2', marginTop: 14, letterSpacing: -0.1, fontWeight: 300,
        fontStyle: 'italic', textWrap: 'pretty',
      }}>
        "We built communities on about 100 years of past weather and assumed that was a good guide going forward.
        That assumption is starting to break."
      </div>
      <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 18, letterSpacing: 0.04 }}>
        — Former FEMA administrator, 2023
      </div>
    </div>
  );
}

Object.assign(window, { TabBaseline });
