// Main app — real USA map, red/black palette, real Medicaid data underneath.

function App() {
  const [year, setYear] = React.useState(() => {
    const saved = parseInt(localStorage.getItem('fw_year'));
    return window.FW_YEARS.includes(saved) ? saved : window.FW_MAX_YEAR;
  });
  const [playing, setPlaying] = React.useState(false);
  const [metric, setMetric] = React.useState('paid');
  const [activeStory, setActiveStory] = React.useState(null);
  const [zoomedState, setZoomedState] = React.useState(null);
  const [activeRegion, setActiveRegion] = React.useState(
    () => (window.FW_EMBED && window.FW_EMBED.region) || 'midwest');

  React.useEffect(() => { localStorage.setItem('fw_year', String(year)); }, [year]);

  // Debug hook for driving the app from the console / verification tooling.
  React.useEffect(() => {
    window.__fwDebug = { zoomTo: setZoomedState, setYear, setPlaying, setRegion: setActiveRegion };
    return () => { delete window.__fwDebug; };
  }, []);

  // Deep-link from an embed: ?state=michigan opens that state's drill-down.
  React.useEffect(() => {
    const want = window.FW_EMBED && window.FW_EMBED.state;
    if (!want) return;
    const names = Object.keys(window.STATE_ABBR_BY_NAME || {});
    const match = names.find(n => n.toLowerCase() === String(want).toLowerCase())
      || names.find(n => (window.STATE_ABBR_BY_NAME[n] || '').toLowerCase() === String(want).toLowerCase());
    if (match) setZoomedState(match);
  }, []);

  const handleStateClick = (name) => {
    setZoomedState(name);
  };

  const drilled = zoomedState && fwIsPilot(zoomedState);

  return (
    <div style={{
      width: '100vw', height: '100vh',
      background: '#000',
      color: '#f0dada',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
      fontFamily: '"Space Grotesk", -apple-system, system-ui, sans-serif',
    }}>
      <TopBar />

      <div style={{ flex: 1, display: 'flex', overflow: 'hidden', minHeight: 0 }}>
        <StoryRail side="left" stories={window.STORIES} onOpen={setActiveStory} />

        <div style={{ flex: 1, position: 'relative', minWidth: 0,
                      background: 'radial-gradient(ellipse at center, #0a0204 0%, #000 75%)' }}>
          <MetricsHud metric={metric} onMetric={setMetric} year={year}
            zoomedState={drilled ? zoomedState : null}
            activeRegion={drilled ? null : activeRegion} />
          <MapLegend />
          {!zoomedState &&
            <RegionToggle activeRegion={activeRegion} onRegion={setActiveRegion} year={year} />}
          <USAMap
            year={year}
            playing={playing}
            zoomedState={zoomedState}
            activeRegion={activeRegion}
            onStateClick={handleStateClick}
            onYear={setYear}
            onPlayingChange={setPlaying}
            onBack={() => setZoomedState(null)}
          />
          <Timeline year={year} onYear={setYear} playing={playing}
            externalDrive={drilled}
            zoomedState={drilled ? zoomedState : null}
            activeRegion={drilled ? null : activeRegion}
            onPlay={() => setPlaying(p => !p)} />

          {zoomedState && !drilled &&
            <DrillDetails state={zoomedState} year={year} onClose={() => setZoomedState(null)} />}
        </div>

        <StoryRail side="right" stories={window.STORIES} onOpen={setActiveStory} />
      </div>

      <StoryModal story={activeStory} onClose={() => setActiveStory(null)} />
    </div>
  );
}

function TopBar() {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '16px 28px',
      background: '#050000',
      borderBottom: '1px solid rgba(255,40,40,0.3)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 32, height: 32,
          background: '#ff2020',
          clipPath: 'polygon(50% 0, 100% 38%, 82% 100%, 18% 100%, 0 38%)',
          boxShadow: '0 0 16px rgba(255,40,40,0.7)',
        }}/>
        <div>
          <div style={{
            fontSize: 17, fontWeight: 800, letterSpacing: 0.5, color: '#fff',
          }}>FRAUD WATCHERS</div>
          <div style={{
            fontFamily: 'ui-monospace, monospace', fontSize: 9, fontWeight: 700,
            letterSpacing: 2.5, color: '#ff3030',
          }}>MEDICAID SPEND INTEL · {window.FW_MIN_YEAR}—{window.FW_MAX_YEAR}</div>
        </div>
      </div>

      <div style={{
        fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700,
        letterSpacing: 2, color: 'rgba(255,100,100,0.6)',
      }}>
        <span style={{
          display: 'inline-block', width: 8, height: 8, background: '#ff2020',
          borderRadius: '50%', marginRight: 8,
          boxShadow: '0 0 8px #ff2020',
          animation: 'blink 1.4s ease-in-out infinite',
        }}/>
        HHS T-MSIS · 238M CLAIM ROWS · NPPES GEOCODED
        <style>{`@keyframes blink { 0%,100% { opacity:1; } 50% { opacity:0.3; } }`}</style>
      </div>
    </div>
  );
}

// Non-pilot states: real top counties by Medicaid paid, no 3D drill yet.
function DrillDetails({ state, year, onClose }) {
  const abbr = window.STATE_ABBR_BY_NAME[state];
  const top = (window.TOP_COUNTIES[abbr] || []).slice(0, 6);
  const maxPaid = top.length ? top[0].paid : 1;
  return (
    <div style={{
      position: 'absolute', bottom: 100, right: 24, zIndex: 15,
      background: 'rgba(8,0,0,0.92)', border: '1px solid rgba(255,40,40,0.4)',
      padding: 20, width: 300, backdropFilter: 'blur(10px)',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
        <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 9, fontWeight: 700,
          letterSpacing: 2.5, color: '#ff3030' }}>
          {state.toUpperCase()} · TOP COUNTIES · {window.FW_MAX_YEAR}
        </div>
        <button onClick={onClose} style={{
          background:'transparent', border:'1px solid rgba(255,40,40,0.4)',
          color:'#ff5050', fontFamily:'ui-monospace, monospace',
          fontSize:9, fontWeight:700, letterSpacing:1.5,
          padding:'3px 8px', cursor:'pointer' }}>✕</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        {top.map((c, i) => (
          <div key={c.fips} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '9px 0', borderBottom: '1px solid rgba(255,40,40,0.12)',
          }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'baseline' }}>
              <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 10,
                color: 'rgba(200,100,100,0.5)', fontWeight: 700 }}>
                {String(i+1).padStart(2,'0')}
              </span>
              <span style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>{c.name}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                width: 50, height: 4, background: 'rgba(255,40,40,0.2)',
                position: 'relative',
              }}>
                <div style={{
                  position: 'absolute', left: 0, top: 0, bottom: 0,
                  width: `${(c.paid / maxPaid) * 100}%`, background: '#ff2020',
                }}/>
              </div>
              <span style={{
                fontFamily: 'ui-monospace, monospace', fontSize: 11, fontWeight: 700,
                color: '#ff8080', minWidth: 48, textAlign: 'right',
              }}>{fmtPaid(c.paid)}</span>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 10, fontSize: 10, fontFamily: 'ui-monospace, monospace',
        color: 'rgba(220,160,160,0.55)', letterSpacing: 1, lineHeight: 1.5 }}>
        FULL 3D COUNTY DRILL-DOWN: PILOT STATES (MI · MN · WI · PA)
      </div>
    </div>
  );
}

// Region selector + combined total, shown in the country view (top-center).
// Extensible: every region in REGION_ORDER gets a button, plus "All states".
function RegionToggle({ activeRegion, onRegion, year }) {
  const opts = [
    ...window.REGION_ORDER.map(k => ({ key: k, label: window.REGIONS[k].name })),
    { key: null, label: 'All states' },
  ];
  return (
    <div style={{ position: 'absolute', top: 20, left: '50%', transform: 'translateX(-50%)', zIndex: 22,
      display: 'flex', pointerEvents: 'none' }}>
      <div style={{ display: 'flex', background: 'rgba(8,0,0,0.9)', border: '1px solid rgba(255,40,40,0.35)',
        pointerEvents: 'auto', backdropFilter: 'blur(10px)' }}>
        {opts.map(o => (
          <button key={String(o.key)} onClick={() => onRegion(o.key)} style={{
            fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700, letterSpacing: 2,
            padding: '9px 16px', border: 'none', cursor: 'pointer',
            background: (o.key === activeRegion) ? '#ff2020' : 'transparent',
            color: (o.key === activeRegion) ? '#000' : 'rgba(255,120,120,0.85)' }}>
            {o.label.toUpperCase()}
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { App, RegionToggle });
