// 05 · The Shift — return periods + hot/cold ratio.

function TabShift() {
  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="05 · THE SHIFT"
        title="Are hundred-year events still hundred-year events?"
        right="Non-stationary GEV · M3" />

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 24 }}>
        <ReturnPeriodPanel />
        <ShiftSidebar />
      </div>

      {/* Hot vs cold ratio — the scientific wow */}
      <div style={{ marginTop: 56 }}>
        <Eyebrow id="05 · ADDENDUM"
          title="The signal that needs no model."
          right="Counting · no inference" />

        <RatioPanel />
      </div>
    </div>
  );
}

function ReturnPeriodPanel() {
  const r = window.RETURN_PERIOD;
  const [hoverYear, setHoverYear] = React.useState(2025);
  const current = r.byYear.find(p => p.year === hoverYear) || r.byYear[r.byYear.length - 2];

  const W = 700, H = 360, padL = 60, padR = 24, padT = 28, padB = 50;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const xs = (y) => padL + ((y - 1950) / 100) * innerW;
  const ymax = 110, ymin = 0;
  const ys = (v) => padT + (1 - (v - ymin) / (ymax - ymin)) * innerH;

  // Smooth curve
  const data = r.byYear;
  const solidIdx = data.findIndex(d => d.projected);
  const solidData = data.slice(0, solidIdx);
  const dashedData = data.slice(solidIdx - 1);
  const solidPath = solidData.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(d.year)},${ys(d.period)}`).join(' ');
  const dashedPath = dashedData.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(d.year)},${ys(d.period)}`).join(' ');

  return (
    <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,0.6)' }}>
      <div style={{ padding: '20px 24px 8px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <Tick color="#C9A84C">▌ RETURN PERIOD · 105°F DAY</Tick>
            <div className="serif" style={{ fontSize: 22, color: '#E6ECF2', marginTop: 8, letterSpacing: -0.2 }}>
              {r.city}
            </div>
          </div>
          <Confidence level="candidate" />
        </div>
        <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 4 }}>
          How often, on average, the threshold is exceeded — based on a GEV fit with time-varying location.
        </div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%', height: 'auto' }}
           onMouseLeave={() => setHoverYear(2025)}>
        {/* Gridlines */}
        {[20, 40, 60, 80, 100].map(v => (
          <g key={v}>
            <line x1={padL} x2={W - padR} y1={ys(v)} y2={ys(v)} stroke="#1B2740" strokeWidth="0.5" strokeDasharray="2 4" />
            <text x={padL - 8} y={ys(v) + 3} textAnchor="end" className="mono" fill="#4E6A82" fontSize="10" fontFamily="Space Mono">{v} yr</text>
          </g>
        ))}
        {/* X ticks */}
        {[1950, 1970, 1990, 2010, 2030, 2050].map(y => (
          <g key={y}>
            <text x={xs(y)} y={padT + innerH + 16} textAnchor="middle" className="mono" fill="#4E6A82" fontSize="9.5" fontFamily="Space Mono">{y}</text>
          </g>
        ))}
        {/* "Today" marker */}
        <line x1={xs(2025)} x2={xs(2025)} y1={padT} y2={padT + innerH} stroke="#C9A84C" strokeWidth="0.6" strokeDasharray="2 3" opacity="0.7" />
        <text x={xs(2025)} y={padT - 8} textAnchor="middle" className="mono" fill="#C9A84C" fontSize="9" fontFamily="Space Mono">TODAY</text>

        {/* Solid line */}
        <path d={solidPath} fill="none" stroke="#E6ECF2" strokeWidth="2" />
        {/* Dashed projection */}
        <path d={dashedPath} fill="none" stroke="#FDAE61" strokeWidth="2" strokeDasharray="4 4" />

        {/* Confidence band (decorative) */}
        <path d={`${solidPath} L${xs(2025)},${ys(0)} L${xs(1950)},${ys(0)} Z`} fill="url(#shiftFill)" opacity="0.3" />
        <defs>
          <linearGradient id="shiftFill" x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor="#74ADD1" stopOpacity="0.4" />
            <stop offset="100%" stopColor="#D73027" stopOpacity="0.5" />
          </linearGradient>
        </defs>

        {/* Points */}
        {data.map(d => (
          <g key={d.year}
             onMouseEnter={() => setHoverYear(d.year)}
             style={{ cursor: 'pointer' }}>
            <circle cx={xs(d.year)} cy={ys(d.period)} r="14" fill="transparent" />
            <circle cx={xs(d.year)} cy={ys(d.period)} r={hoverYear === d.year ? 5 : 3.5}
              fill={d.projected ? '#FDAE61' : '#C9A84C'}
              stroke="#0A0F1A" strokeWidth="1.2" />
          </g>
        ))}

        {/* Hover label */}
        <g transform={`translate(${xs(current.year)}, ${ys(current.period) - 22})`}>
          <rect x="-46" y="-22" width="92" height="22" fill="rgba(10,15,26,0.95)" stroke="#243353" />
          <text x="0" y="-7" textAnchor="middle" className="mono" fill="#E6ECF2" fontSize="11" fontFamily="Space Mono" fontWeight="700">
            1 in {current.period} years
          </text>
        </g>

        {/* Y axis label */}
        <text x={padL - 50} y={padT + innerH / 2} textAnchor="middle" className="mono" fill="#4E6A82" fontSize="10"
          transform={`rotate(-90, ${padL - 50}, ${padT + innerH / 2})`} fontFamily="Space Mono">
          AVERAGE RETURN INTERVAL
        </text>
      </svg>

      {/* Footer readout */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', borderTop: '1px solid #1B2740' }}>
        {r.byYear.filter(d => d.period != null).map((d, i, arr) => ({
          label: d.projected ? `${d.year} PROJ.` : String(d.year),
          value: `1 in ${Math.round(d.period)} yr`,
          sub: d.period > 80 ? 'rare' : d.period > 30 ? 'recurring' : d.projected ? 'near-annual' : 'now expected',
          color: d.projected ? '#FDAE61' : i === arr.length - 2 ? '#D73027' : undefined,
        })).map((s, i) => (
          <div key={i} style={{ padding: '14px 18px', borderLeft: i > 0 ? '1px solid #1B2740' : 'none' }}>
            <Tick>{s.label}</Tick>
            <div className="mono" style={{ color: s.color || '#E6ECF2', fontSize: 17, fontWeight: 700, marginTop: 4 }}>
              {s.value}
            </div>
            <div className="mono" style={{ color: '#8BAFC7', fontSize: 10, marginTop: 2 }}>{s.sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ShiftSidebar() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,0.6)', padding: 24 }}>
        <Tick color="#C9A84C">▌ THE FINDING</Tick>
        <div className="serif" style={{ fontSize: 22, color: '#E6ECF2', marginTop: 12, lineHeight: 1.32, fontWeight: 300, textWrap: 'pretty' }}>
          A "hundred-year heat event" in 1950 is, today, a 17-year event. Over 41 years of record, the risk of high-temperature extremes has increased by a factor of 2.1.
        </div>
        <div className="serif" style={{ fontSize: 13, color: '#8BAFC7', marginTop: 14, lineHeight: 1.55 }}>
          The fitted GEV model allows its location parameter to vary linearly with time. That single parameter,
          and how fast it has moved, is the entire shift.
        </div>
      </div>

      <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,0.6)', padding: 24 }}>
        <Tick>▌ THRESHOLD</Tick>
        <div className="mono" style={{ color: '#E6ECF2', fontSize: 38, fontWeight: 700, marginTop: 4, letterSpacing: -1 }}>
          105°F
        </div>
        <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 4 }}>
          Daily maximum threshold for {window.RETURN_PERIOD.city}.
        </div>
        <div style={{ height: 1, background: '#1B2740', margin: '18px 0' }} />
        <Tick>▌ MODEL</Tick>
        <div className="mono" style={{ color: '#E6ECF2', fontSize: 12, marginTop: 8, lineHeight: 1.7 }}>
          μ(t) = μ₀ + β·t<br/>
          σ, ξ stationary<br/>
          MLE · 1000-bootstrap CI
        </div>
      </div>
    </div>
  );
}

function RatioPanel() {
  const data = window.RATIO_BY_DECADE;
  const W = 1140, H = 320, padL = 60, padR = 200, padT = 28, padB = 38;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const xs = (i) => padL + (i / (data.length - 1)) * innerW;
  const ymin = 0, ymax = 3;
  const ys = (v) => padT + (1 - (v - ymin) / (ymax - ymin)) * innerH;

  const hotPath = data.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(i)},${ys(d.hot)}`).join(' ');
  const coldPath = data.map((d, i) => `${i === 0 ? 'M' : 'L'}${xs(i)},${ys(d.cold)}`).join(' ');
  const fillPath = hotPath +
    ' ' + data.slice().reverse().map((d, i) => `L${xs(data.length - 1 - i)},${ys(d.cold)}`).join(' ') + ' Z';

  return (
    <div style={{ border: '1px solid #1B2740', background: 'rgba(14,20,34,0.6)' }}>
      <div style={{ padding: '22px 28px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div>
          <div className="serif" style={{ fontSize: 24, color: '#E6ECF2', letterSpacing: -0.3, fontWeight: 300 }}>
            The ratio that needs no model
          </div>
          <div className="mono" style={{ color: '#8BAFC7', fontSize: 11, marginTop: 6, maxWidth: 700, lineHeight: 1.5 }}>
            For every all-time daily high vs all-time daily low set in each decade. In a stable climate this should hover at 1:1.
            It has not been 1:1 since the 1980s. No modeling. Just counting.
          </div>
        </div>
        <Confidence level="high" />
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%', height: 'auto' }}>
        {/* Gridlines */}
        {[0.5, 1, 1.5, 2, 2.5].map(v => (
          <g key={v}>
            <line x1={padL} x2={W - padR} y1={ys(v)} y2={ys(v)}
              stroke={v === 1 ? '#8BAFC7' : '#1B2740'} strokeWidth={v === 1 ? 1 : 0.4} strokeDasharray={v === 1 ? '0' : '2 4'} />
            <text x={padL - 8} y={ys(v) + 3} textAnchor="end" className="mono" fill="#4E6A82" fontSize="9.5" fontFamily="Space Mono">{v.toFixed(1)}×</text>
          </g>
        ))}
        <text x={padL - 50} y={ys(1) - 6} className="mono" fill="#8BAFC7" fontSize="9" fontFamily="Space Mono">PARITY</text>

        {/* X */}
        {data.map((d, i) => (
          <text key={d.decade} x={xs(i)} y={padT + innerH + 18} textAnchor="middle"
            className="mono" fill="#4E6A82" fontSize="10" fontFamily="Space Mono">{d.decade}</text>
        ))}

        {/* Fill gap */}
        <path d={fillPath} fill="rgba(215,48,39,0.10)" />

        {/* Hot line */}
        <path d={hotPath} fill="none" stroke="#D73027" strokeWidth="2.4" />
        {data.map((d, i) => (
          <circle key={'h' + i} cx={xs(i)} cy={ys(d.hot)} r="3.5" fill="#D73027" stroke="#0A0F1A" strokeWidth="1" />
        ))}

        {/* Cold line */}
        <path d={coldPath} fill="none" stroke="#74ADD1" strokeWidth="2.4" />
        {data.map((d, i) => (
          <circle key={'c' + i} cx={xs(i)} cy={ys(d.cold)} r="3.5" fill="#74ADD1" stroke="#0A0F1A" strokeWidth="1" />
        ))}

        {/* End-labels */}
        <g>
          <text x={xs(data.length - 1) + 12} y={ys(data[data.length - 1].hot) + 4}
            className="mono" fill="#D73027" fontSize="11" fontFamily="Space Mono" fontWeight="700">
            HOT 2.34×
          </text>
          <text x={xs(data.length - 1) + 12} y={ys(data[data.length - 1].cold) + 4}
            className="mono" fill="#74ADD1" fontSize="11" fontFamily="Space Mono" fontWeight="700">
            COLD 0.42×
          </text>
        </g>

        {/* Annotations */}
        <g>
          <line x1={xs(7)} x2={xs(7)} y1={ys(1.45)} y2={ys(0.92)} stroke="#C9A84C" strokeWidth="0.6" strokeDasharray="2 2" />
          <text x={xs(7)} y={ys(1.55)} textAnchor="middle" className="mono" fill="#C9A84C" fontSize="9" fontFamily="Space Mono">CROSSOVER</text>
        </g>

        {/* Side legend */}
        <g transform={`translate(${W - padR + 24}, ${padT + 10})`}>
          <rect x="0" y="0" width="155" height="120" fill="rgba(10,15,26,0.6)" stroke="#1B2740" />
          <text x="14" y="22" className="mono" fill="#4E6A82" fontSize="9" letterSpacing="1.8" fontFamily="Space Mono">▌ LEGEND</text>
          <line x1="14" x2="38" y1="44" y2="44" stroke="#D73027" strokeWidth="2.4" />
          <text x="46" y="48" className="mono" fill="#E6ECF2" fontSize="11" fontFamily="Space Mono">Hot records</text>
          <line x1="14" x2="38" y1="68" y2="68" stroke="#74ADD1" strokeWidth="2.4" />
          <text x="46" y="72" className="mono" fill="#E6ECF2" fontSize="11" fontFamily="Space Mono">Cold records</text>
          <line x1="14" x2="38" y1="92" y2="92" stroke="#8BAFC7" strokeWidth="0.8" />
          <text x="46" y="96" className="mono" fill="#8BAFC7" fontSize="11" fontFamily="Space Mono">Stable climate</text>
        </g>
      </svg>
    </div>
  );
}

Object.assign(window, { TabShift });
