// 02 · The Strangest Day

function TabStrangest() {
  const [q, setQ] = React.useState('');
  const [result, setResult] = React.useState(window.STRANGEST.default);
  const [searching, setSearching] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(true);

  const submit = (s) => {
    setSearching(true);
    setTimeout(() => {
      setResult(window.strangestLookup(s));
      setSearching(false);
      setSubmitted(true);
    }, 700);
  };

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="02 · THE STRANGEST DAY" title="Enter any place. The model returns the strangest day in its record." right="Composite anomaly model · M1" />

      {/* Search */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 28 }}>
        <div style={{ flex: 1, position: 'relative', border: '1px solid #243353', background: 'rgba(14,20,34,0.6)' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ padding: '0 14px', borderRight: '1px solid #1B2740' }}>
              <Crosshair size={14} color="#C9A84C" />
            </div>
            <input
              type="text"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') submit(q); }}
              placeholder="Burlington, Vermont · 02601 · Portland, OR · Death Valley…"
              className="mono"
              style={{
                flex: 1, background: 'transparent', border: 'none', outline: 'none',
                color: '#E6ECF2', fontSize: 16, padding: '18px 0', letterSpacing: 0.04,
                fontFamily: "'Space Mono', monospace",
              }}
            />
            <button
              onClick={() => submit(q)}
              className="mono"
              style={{
                background: '#C9A84C', color: '#0A0F1A', border: 'none', padding: '14px 22px',
                fontSize: 11, letterSpacing: 0.25, textTransform: 'uppercase', cursor: 'pointer',
                fontFamily: "'Space Mono', monospace", fontWeight: 700,
              }}>
              Find the strangest day →
            </button>
          </div>
        </div>
      </div>

      {/* Suggestion chips */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 36, flexWrap: 'wrap' }}>
        <Tick>TRY:</Tick>
        {['Portland, OR', 'New York', 'Chicago', 'Death Valley', 'Miami', 'Phoenix', 'Boston'].map(s => (
          <button key={s} onClick={() => { setQ(s); submit(s); }} className="mono" style={{
            background: 'transparent', border: '1px solid #243353', color: '#8BAFC7',
            padding: '5px 10px', fontSize: 10.5, letterSpacing: 0.08, cursor: 'pointer',
            fontFamily: "'Space Mono', monospace",
          }}>
            {s}
          </button>
        ))}
      </div>

      {/* Result card */}
      <div style={{ position: 'relative', minHeight: 460 }}>
        {searching && (
          <div style={{
            position: 'absolute', inset: 0, background: 'rgba(10,15,26,0.6)', zIndex: 5,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div className="mono" style={{ color: '#C9A84C', fontSize: 12, letterSpacing: 0.3, textTransform: 'uppercase' }}>
              ⟳ Fitting kernel density · station_id resolved · scoring…
            </div>
          </div>
        )}
        {submitted && <StrangestCard data={result} />}
      </div>

      {/* Methods note */}
      <div style={{ marginTop: 36, display: 'flex', gap: 24 }}>
        <div style={{ flex: 1, padding: '20px 24px', border: '1px dashed #243353', background: 'rgba(14,20,34,0.4)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
            <Tick color="#C9A84C">METHOD · M1 STATION ANOMALY ENGINE</Tick>
            <Confidence level="high" />
          </div>
          <div className="serif" style={{ fontSize: 14, color: '#E6ECF2', lineHeight: 1.5, maxWidth: 880 }}>
            Strangeness is a non-parametric kernel density fit on every recorded value for the same
            calendar date at the nearest long-record station — minimum 30 years of record. The score is the
            negative log-probability of the observed temperature under that distribution, expressed as a σ equivalent.
            A −40°F day in January is unremarkable in International Falls; the same temperature in April is the strangest day on record.
            The model knows the difference.
          </div>
        </div>
      </div>
    </div>
  );
}

function StrangestCard({ data }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 1, background: '#1B2740', border: '1px solid #1B2740' }}>
      {/* Left half — the card */}
      <div style={{ background: 'var(--bg-2)', padding: '32px 36px', position: 'relative' }}>
        <ScanLine />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative' }}>
          <Tick color="#C9A84C">▌ FINDING · STATION REPORT</Tick>
          <Tick>{data.station}</Tick>
        </div>

        <div className="serif" style={{ fontSize: 38, color: '#E6ECF2', marginTop: 22, letterSpacing: -0.8, lineHeight: 1.05, fontWeight: 300 }}>
          {data.city}
        </div>
        <div className="mono" style={{ color: '#C9A84C', fontSize: 14, marginTop: 6, letterSpacing: 0.06 }}>
          {data.date}
        </div>

        <div style={{ display: 'flex', gap: 32, marginTop: 28, paddingTop: 24, borderTop: '1px solid #1B2740' }}>
          <Stat label="ANOMALY SCORE" value={`${data.sigma.toFixed(1)}σ`} color="#D73027" mono />
          <Stat label="OBSERVED" value={`${data.high}°F`} color={data.high < data.avgHigh ? '#74ADD1' : '#FDAE61'} mono />
          <Stat label="DATE AVERAGE" value={`${data.avgHigh}°F`} color="#E6ECF2" mono />
          <Stat label="YEARS OF RECORD" value={data.recordYears} color="#E6ECF2" mono />
        </div>

        <div className="serif" style={{ fontSize: 22, color: '#E6ECF2', marginTop: 30, lineHeight: 1.32, fontStyle: 'italic', textWrap: 'pretty' }}>
          {data.headline}
        </div>
        <div className="serif" style={{ fontSize: 14, color: '#8BAFC7', marginTop: 16, lineHeight: 1.55, maxWidth: 540 }}>
          {data.note}
        </div>

        {/* Share row */}
        <div style={{ display: 'flex', gap: 10, marginTop: 32, paddingTop: 20, borderTop: '1px solid #1B2740' }}>
          <ShareBtn label="Copy card" />
          <ShareBtn label="Share to X" />
          <ShareBtn label="Compare a second city →" highlight />
        </div>
      </div>

      {/* Right half — distribution histogram */}
      <div style={{ background: 'var(--bg-2)', padding: '32px 36px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Tick color="#8BAFC7">▌ DISTRIBUTION · {data.date.split(',')[0].toUpperCase()} · ALL YEARS</Tick>
          <Tick>n = {data.recordYears}</Tick>
        </div>
        <Histogram mean={data.distMean} sd={data.distSd} point={data.point} sigma={data.sigma} />
        <div className="serif" style={{ fontSize: 13, color: '#8BAFC7', marginTop: 14, lineHeight: 1.55 }}>
          The distribution of every {data.date.split(',')[0]} on record at this station.
          The bar where this day lands sits {data.sigma.toFixed(1)} standard deviations from the mean.
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value, color = '#E6ECF2', mono }) {
  return (
    <div>
      <div className="mono" style={{ color: '#4E6A82', fontSize: 9.5, letterSpacing: 0.18, textTransform: 'uppercase' }}>{label}</div>
      <div className={mono ? 'mono' : 'serif'} style={{ color, fontSize: 26, fontWeight: 700, lineHeight: 1.1, marginTop: 4, letterSpacing: -0.5 }}>{value}</div>
    </div>
  );
}

function ShareBtn({ label, highlight }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      className="mono"
      style={{
        background: hover ? (highlight ? '#C9A84C' : 'rgba(139,175,199,0.1)') : 'transparent',
        color: highlight ? (hover ? '#0A0F1A' : '#C9A84C') : '#8BAFC7',
        border: `1px solid ${highlight ? '#C9A84C' : '#243353'}`,
        padding: '8px 14px', fontSize: 11, letterSpacing: 0.18, textTransform: 'uppercase',
        cursor: 'pointer', fontFamily: "'Space Mono', monospace",
        transition: 'all 180ms',
      }}>
      {label}
    </button>
  );
}

function Histogram({ mean, sd, point, sigma }) {
  // Build 30 bins of a Gaussian distribution
  const W = 480, H = 220, padL = 30, padR = 14, padT = 20, padB = 30;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const lo = mean - 5 * sd, hi = mean + 5 * sd;
  // Extend range to include point
  const rLo = Math.min(lo, point - sd);
  const rHi = Math.max(hi, point + sd);
  const bins = 30;
  const binW = (rHi - rLo) / bins;
  const data = [];
  let maxH = 0;
  for (let i = 0; i < bins; i++) {
    const c = rLo + (i + 0.5) * binW;
    const z = (c - mean) / sd;
    const h = Math.exp(-0.5 * z * z) * 100; // scaled
    maxH = Math.max(maxH, h);
    data.push({ c, h });
  }
  const xs = (v) => padL + ((v - rLo) / (rHi - rLo)) * innerW;
  const ys = (h) => padT + (1 - h / maxH) * innerH;
  const pointX = xs(point);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ marginTop: 18, display: 'block', width: '100%', height: 'auto' }}>
      {/* axis */}
      <line x1={padL} x2={W - padR} y1={padT + innerH} y2={padT + innerH} stroke="#243353" strokeWidth="0.6" />
      {/* ticks */}
      {[-3, -2, -1, 0, 1, 2, 3].map(zs => {
        const v = mean + zs * sd;
        return (
          <g key={zs}>
            <line x1={xs(v)} x2={xs(v)} y1={padT + innerH} y2={padT + innerH + 4} stroke="#4E6A82" strokeWidth="0.6" />
            <text x={xs(v)} y={padT + innerH + 16} textAnchor="middle" className="mono" fill="#4E6A82" fontSize="9" fontFamily="Space Mono">
              {Math.round(v)}°
            </text>
          </g>
        );
      })}
      {/* mean line */}
      <line x1={xs(mean)} x2={xs(mean)} y1={padT} y2={padT + innerH} stroke="#8BAFC7" strokeWidth="0.6" strokeDasharray="2 3" />
      <text x={xs(mean)} y={padT - 6} textAnchor="middle" className="mono" fill="#8BAFC7" fontSize="9" fontFamily="Space Mono">MEAN</text>

      {/* bars */}
      {data.map((b, i) => {
        const x = xs(b.c) - (innerW / bins) / 2 + 1;
        const w = (innerW / bins) - 2;
        const isPoint = Math.abs(b.c - point) <= binW / 2 + 0.001;
        const isCloseToPoint = !isPoint && Math.abs(b.c - point) <= binW * 1.5;
        return (
          <rect key={i}
            x={x} y={ys(b.h)}
            width={w} height={padT + innerH - ys(b.h)}
            fill={isPoint ? '#D73027' : isCloseToPoint ? '#FDAE61' : '#8BAFC7'}
            opacity={isPoint ? 1 : 0.5}
          />
        );
      })}

      {/* point indicator */}
      <g>
        <line x1={pointX} x2={pointX} y1={padT - 6} y2={padT + innerH} stroke="#D73027" strokeWidth="1" />
        <polygon points={`${pointX - 4},${padT - 6} ${pointX + 4},${padT - 6} ${pointX},${padT}`} fill="#D73027" />
        <text x={pointX} y={padT - 12} textAnchor="middle" className="mono" fill="#D73027" fontSize="10" fontWeight="700" fontFamily="Space Mono">
          {point}°F · {sigma.toFixed(1)}σ
        </text>
      </g>
    </svg>
  );
}

Object.assign(window, { TabStrangest });
