// Boot — fetch real data from the local API, expose the globals the
// components read, then mount the app. Replaces the old mock map-data.jsx.

function fmtPaid(dollars) {
  if (dollars == null || isNaN(dollars)) return '—';
  const v = Math.abs(dollars);
  if (v >= 1e9) return '$' + (dollars / 1e9).toFixed(1) + 'B';
  if (v >= 1e6) return '$' + Math.round(dollars / 1e6) + 'M';
  if (v >= 1e3) return '$' + Math.round(dollars / 1e3) + 'K';
  return '$' + Math.round(dollars);
}

function fmtCount(n) {
  if (n == null || isNaN(n)) return '—';
  const v = Math.abs(n);
  if (v >= 1e9) return (n / 1e9).toFixed(2) + 'B';
  if (v >= 1e6) return (n / 1e6).toFixed(1) + 'M';
  if (v >= 1e3) return (n / 1e3).toFixed(1) + 'K';
  return String(n);
}

const FW_API = (window.FW_API_BASE || '');

async function fwLoad() {
  const r = await fetch(FW_API + '/api/bootstrap');
  if (!r.ok) throw new Error('bootstrap HTTP ' + r.status);
  const d = await r.json();
  if (d.error) throw new Error(d.error);

  window.FW_DATA = d;
  window.FW_YEARS = d.years;
  window.FW_MIN_YEAR = d.years[0];
  window.FW_MAX_YEAR = d.maxYear;
  window.FW_PILOT = new Set(d.pilot);

  // Per-state paid in $M keyed by full state name — the shape the 3D country
  // view extrudes from (kept from the original design).
  const heights = {};
  const info = {};
  const fipsByName = {};
  const abbrByName = {};
  d.states.forEach(s => {
    heights[s.name] = {};
    d.years.forEach(y => { heights[s.name][y] = (s.paid[y] || 0) / 1e6; });
    info[s.name] = s;
    fipsByName[s.name] = s.fips;
    abbrByName[s.name] = s.abbr;
  });
  window.STATE_HEIGHTS = heights;
  window.STATE_INFO = info;
  window.STATE_FIPS_BY_NAME = fipsByName;
  window.STATE_ABBR_BY_NAME = abbrByName;

  window.NATIONAL = d.national;
  window.COUNTY_DATA = d.counties;          // abbr -> fips -> {name,pop,paid{},claims{},providers{}}
  window.TOP_COUNTIES = d.topCounties;      // abbr -> [{fips,name,paid}]
  window.STORIES = d.stories || [];
  window.COUNTY_CASEFILES = d.countyCasefiles || {};
  window.CASES_BY_STATE = d.cases || {};
  const casesByFips = {};
  Object.values(window.CASES_BY_STATE).forEach(list => (list || []).forEach(c => {
    if (c.county_fips) (casesByFips[c.county_fips] = casesByFips[c.county_fips] || []).push(c);
  }));
  window.CASES_BY_FIPS = casesByFips;
  window.FW_META = d.meta || {};
}

const FW_COUNTY_DETAIL_CACHE = {};
async function fwCountyDetail(fips) {
  if (!FW_COUNTY_DETAIL_CACHE[fips]) {
    FW_COUNTY_DETAIL_CACHE[fips] = fetch(FW_API + '/api/county/' + fips)
      .then(r => r.json())
      .catch(() => ({ topCodes: {}, topProviders: {} }));
  }
  return FW_COUNTY_DETAIL_CACHE[fips];
}

Object.assign(window, { fmtPaid, fmtCount, fwCountyDetail });

fwLoad()
  .then(() => {
    document.getElementById('boot-status').remove();
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  })
  .catch(e => {
    document.getElementById('boot-status').textContent =
      'DATA LOAD FAILED — ' + e.message + ' · is server.py running and fraudwatch.db built?';
  });
