// Timeline bar + in-map HUD + legend — driven by real national/state data.

function Timeline({ year, onYear, playing, onPlay, externalDrive, zoomedState, activeRegion }) {
  const years = window.FW_YEARS;
  const min = years[0], max = years[years.length - 1];

  React.useEffect(() => {
    if (!playing || externalDrive) return;
    const id = setInterval(() => {
      onYear(y => (y + 1 > max ? min : y + 1));
    }, 1400);
    return () => clearInterval(id);
  }, [playing, externalDrive, min, max]);

  const pct = ((year - min) / (max - min)) * 100;

  const info = zoomedState ? window.STATE_INFO[zoomedState] : null;
  const region = (!info && activeRegion) ? window.REGIONS[activeRegion] : null;
  const rt = region ? window.fwRegionTotals(activeRegion, year) : null;
  const readoutLabel = info ? `${info.abbr} MEDICAID PAID`
    : (region ? `${region.name.toUpperCase()} MEDICAID PAID` : 'US MEDICAID PAID');
  const readoutPaid = info ? (info.paid[year] || 0)
    : (rt ? rt.paid : ((window.NATIONAL[year] && window.NATIONAL[year].paid) || 0));

  return (
    <div style={{
      position: 'absolute', bottom: 24, left: 24, right: 24, zIndex: 20,
      background: 'rgba(8,0,0,0.88)',
      border: '1px solid rgba(255,40,40,0.35)',
      padding: '16px 22px',
      display: 'flex', alignItems: 'center', gap: 20,
      backdropFilter: 'blur(10px)',
    }}>
      <button onClick={onPlay} style={{
        width: 38, height: 38,
        border: '1.5px solid #ff2020', background: playing ? '#ff2020' : 'transparent',
        color: playing ? '#000' : '#ff5050', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {playing
          ? <svg width="12" height="14" viewBox="0 0 12 14"><rect x="1" y="1" width="3" height="12" fill="currentColor"/><rect x="8" y="1" width="3" height="12" fill="currentColor"/></svg>
          : <svg width="12" height="14" viewBox="0 0 12 14"><path d="M1 1 L11 7 L1 13 Z" fill="currentColor"/></svg>}
      </button>

      <div style={{ flex: 1, position: 'relative' }}>
        <div style={{
          height: 3, background: 'rgba(255,40,40,0.15)',
          position: 'relative',
        }}>
          <div style={{
            position: 'absolute', left: 0, top: 0, bottom: 0, width: `${pct}%`,
            background: '#ff2020',
            boxShadow: '0 0 14px #ff2020',
            transition: 'width 0.5s cubic-bezier(.4,.8,.3,1)',
          }} />
        </div>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          marginTop: 12,
        }}>
          {years.map(y => (
            <button key={y} onClick={() => onYear(y)} style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              fontFamily: '"Space Grotesk", sans-serif',
              fontSize: y === year ? 15 : 12, letterSpacing: 1.5,
              color: y === year ? '#ff5050' : 'rgba(200,100,100,0.55)',
              fontWeight: 800, padding: '2px 6px', position: 'relative',
              transition: 'all 0.2s',
            }}>{y}</button>
          ))}
        </div>
      </div>

      <div style={{
        fontFamily: '"Space Grotesk", sans-serif', minWidth: 150,
        textAlign: 'right', lineHeight: 1,
      }}>
        <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 9, color: 'rgba(255,100,100,0.55)', letterSpacing: 2, marginBottom: 4 }}>{readoutLabel}</div>
        <div style={{ fontSize: 26, color: '#ff5050', fontWeight: 800, letterSpacing: -0.5 }}>
          {fmtPaid(readoutPaid)}
        </div>
      </div>
    </div>
  );
}

// In-map HUD: metric selector + KPI, top-left. National by default,
// state-scoped when drilled in.
function MetricsHud({ metric, onMetric, year, zoomedState, activeRegion }) {
  const info = zoomedState ? window.STATE_INFO[zoomedState] : null;
  const region = (!info && activeRegion) ? window.REGIONS[activeRegion] : null;
  const rt = region ? window.fwRegionTotals(activeRegion, year) : null;
  const nat = window.NATIONAL[year] || {};
  const scopeLabel = info ? info.abbr : (region ? region.name.toUpperCase() : 'US');
  const paid = info ? (info.paid[year] || 0) : (rt ? rt.paid : (nat.paid || 0));
  const claims = info ? (info.claims[year] || 0) : (rt ? rt.claims : (nat.claims || 0));
  const providers = info ? (info.providers[year] || 0) : (rt ? rt.providers : (nat.providers || 0));

  const metrics = [
    { id: 'paid',      label: 'TOTAL PAID',  value: fmtPaid(paid) },
    { id: 'claims',    label: 'CLAIMS',      value: fmtCount(claims) },
    { id: 'providers', label: 'PROVIDERS',   value: fmtCount(providers) },
    { id: 'perclaim',  label: '$ / CLAIM',   value: claims ? '$' + (paid / claims).toFixed(0) : '—' },
  ];
  const active = metrics.find(m => m.id === metric) || metrics[0];
  return (
    <div style={{
      position: 'absolute', top: 24, left: 24, zIndex: 20,
      background: 'rgba(8,0,0,0.88)', border: '1px solid rgba(255,40,40,0.35)',
      padding: '18px 22px', backdropFilter: 'blur(10px)',
      minWidth: 240,
    }}>
      <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 9, letterSpacing: 2.5, color: 'rgba(255,100,100,0.6)', marginBottom: 6 }}>
        {scopeLabel} · {active.label} · {year}
      </div>
      <div style={{
        fontFamily: '"Space Grotesk", sans-serif',
        fontSize: 40, fontWeight: 800, color: '#ff3030',
        letterSpacing: -1.5, lineHeight: 1,
        textShadow: '0 0 20px rgba(255,40,40,0.6)',
      }}>{active.value}</div>
      <div style={{ display: 'flex', gap: 4, marginTop: 14, flexWrap: 'wrap' }}>
        {metrics.map(m => (
          <button key={m.id} onClick={() => onMetric(m.id)} style={{
            fontFamily: 'ui-monospace, monospace', fontSize: 9, fontWeight: 700,
            letterSpacing: 1.5, padding: '6px 9px',
            background: m.id === metric ? '#ff2020' : 'transparent',
            border: `1px solid ${m.id === metric ? '#ff2020' : 'rgba(255,40,40,0.3)'}`,
            color: m.id === metric ? '#000' : 'rgba(255,120,120,0.8)',
            cursor: 'pointer',
          }}>{m.label}</button>
        ))}
      </div>
    </div>
  );
}

function MapLegend() {
  return (
    <div style={{
      position: 'absolute', top: 24, right: 24, zIndex: 20,
      background: 'rgba(8,0,0,0.88)', border: '1px solid rgba(255,40,40,0.35)',
      padding: '14px 18px', backdropFilter: 'blur(10px)',
      fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700,
      color: 'rgba(220,160,160,0.8)', letterSpacing: 1.5,
    }}>
      <div style={{ color: 'rgba(255,100,100,0.6)', marginBottom: 8 }}>LEGEND</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
        <span style={{ width: 10, height: 10, background: '#ff2020', boxShadow: '0 0 8px #ff2020' }}/>PILOT STATE · DRILLABLE
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
        <span style={{ width: 10, height: 10, background: '#1a0304', border: '1px solid rgba(220,40,40,0.35)' }}/>STATE TOTALS ONLY
      </div>
      <div style={{ marginTop: 8, fontSize: 9, color: 'rgba(200,100,100,0.5)', fontWeight: 500 }}>
        HEIGHT = MEDICAID PAID $
      </div>
    </div>
  );
}

Object.assign(window, { Timeline, MetricsHud, MapLegend });
