/* eslint-disable */
// Persistent HUD across top of viewport.

const __DFW_AIRPORTS = [
  // ── DFW Metro · Class B
  { icao: "KDFW", name: "Dallas/Ft. Worth Intl",  lat: "32.90°N", lon: "97.04°W", metar: "VFR" },
  { icao: "KDAL", name: "Dallas Love Field",      lat: "32.85°N", lon: "96.85°W", metar: "VFR" },
  // ── DFW Metro · Class D
  { icao: "KAFW", name: "Ft. Worth Alliance",     lat: "32.99°N", lon: "97.32°W", metar: "MVFR" },
  { icao: "KADS", name: "Addison",                lat: "32.97°N", lon: "96.84°W", metar: "VFR" },
  { icao: "KFTW", name: "Ft. Worth Meacham",      lat: "32.82°N", lon: "97.36°W", metar: "VFR" },
  { icao: "KGKY", name: "Arlington Muni",         lat: "32.66°N", lon: "97.10°W", metar: "MVFR" },
  { icao: "KFWS", name: "Ft. Worth Spinks",       lat: "32.57°N", lon: "97.31°W", metar: "VFR" },
  { icao: "KHQZ", name: "Mesquite Metro",         lat: "32.75°N", lon: "96.53°W", metar: "VFR" },
  { icao: "KTKI", name: "McKinney National",      lat: "33.18°N", lon: "96.59°W", metar: "VFR" },
  { icao: "KGPM", name: "Grand Prairie Muni",     lat: "32.70°N", lon: "97.05°W", metar: "MVFR" },
  { icao: "KRBD", name: "Dallas Executive",       lat: "32.68°N", lon: "96.87°W", metar: "LIFR" },
  // ── Texas Military Airfields
  { icao: "KNFW", name: "NAS JRB Ft. Worth",      lat: "32.77°N", lon: "97.44°W", metar: "IFR" },
  { icao: "KDYS", name: "Dyess AFB",              lat: "32.42°N", lon: "99.85°W", metar: "VFR" },
  { icao: "KSKF", name: "Kelly Fld / Lackland",   lat: "29.38°N", lon: "98.58°W", metar: "VFR" },
  { icao: "KRND", name: "Randolph AFB",           lat: "29.53°N", lon: "98.28°W", metar: "VFR" },
  { icao: "KBIF", name: "Biggs AAF / Ft. Bliss",  lat: "31.85°N", lon: "106.38°W", metar: "VFR" },
  { icao: "KGRK", name: "Robert Gray AAF",        lat: "31.07°N", lon: "97.83°W", metar: "VFR" },
  { icao: "KHLR", name: "Hood AAF / Ft. Cavazos", lat: "31.14°N", lon: "97.71°W", metar: "MVFR" },
  { icao: "KNGP", name: "NAS Corpus Christi",     lat: "27.69°N", lon: "97.29°W", metar: "VFR" },
  { icao: "KNGW", name: "NAS Kingsville",         lat: "27.50°N", lon: "97.81°W", metar: "VFR" },
  { icao: "KLRD", name: "Laredo / DPMC",          lat: "27.54°N", lon: "99.46°W", metar: "VFR" },
  { icao: "KGGG", name: "Longview / E.TX Reg.",   lat: "32.38°N", lon: "94.71°W", metar: "MVFR" },
];

function HUD() {
  const [today, setToday] = React.useState(formatToday());
  const [apIdx, setApIdx] = React.useState(0);
  const [airports, setAirports] = React.useState(__DFW_AIRPORTS);
  const [metarSource, setMetarSource] = React.useState("STATIC");

  React.useEffect(() => {
    const dayId = setInterval(() => setToday(formatToday()), 60000);
    return () => clearInterval(dayId);
  }, []);

  React.useEffect(() => {
    const rotId = setInterval(() => {
      setApIdx(i => (i + 1) % __DFW_AIRPORTS.length);
    }, 4200);
    return () => clearInterval(rotId);
  }, []);

  // Live METAR pull from aviationweather.gov ADDS
  React.useEffect(() => {
    let cancelled = false;

    async function pullMetar() {
      const ids = __DFW_AIRPORTS.map(a => a.icao).join(",");
      const upstream = `https://aviationweather.gov/api/data/metar?ids=${ids}&format=json&hours=2`;
      // Order: our own Cloudflare Worker first (most reliable), then
      // direct ADDS, then public CORS proxies as last-ditch.
      const attempts = [
        { label: "ADDS/wti",    url: `https://wtic2.com/api/metar?ids=${ids}&hours=2` },
        { label: "ADDS",        url: upstream },
        { label: "ADDS/proxy1", url: "https://corsproxy.io/?" + encodeURIComponent(upstream) },
        { label: "ADDS/proxy2", url: "https://api.allorigins.win/raw?url=" + encodeURIComponent(upstream) },
      ];

      for (const a of attempts) {
        try {
          const r = await fetch(a.url, { cache: "no-store" });
          if (!r.ok) throw new Error("HTTP " + r.status);
          const data = await r.json();
          if (cancelled) return;
          if (!Array.isArray(data) || data.length === 0) throw new Error("empty");

          // Build ICAO -> flight category lookup. ADDS returns multiple
          // observations per station; we take the most recent.
          const latest = {};
          data.forEach(m => {
            if (!m || !m.icaoId) return;
            const t = m.obsTime || 0;
            if (!latest[m.icaoId] || t > latest[m.icaoId].obsTime) {
              latest[m.icaoId] = m;
            }
          });

          const next = __DFW_AIRPORTS.map(base => {
            const m = latest[base.icao];
            if (!m) return base;
            const cat = m.fltCat || m.flight_category || base.metar;
            if (cat && /^(VFR|MVFR|IFR|LIFR)$/.test(cat)) {
              return { ...base, metar: cat };
            }
            return base;
          });
          if (!cancelled) {
            setAirports(next);
            setMetarSource(a.label);
          }
          return; // success — stop trying
        } catch (e) {
          // try next attempt
        }
      }
      if (!cancelled) setMetarSource("STATIC");
    }

    pullMetar();
    const refreshId = setInterval(pullMetar, 5 * 60 * 1000); // every 5 min
    return () => { cancelled = true; clearInterval(refreshId); };
  }, []);

  const ap = airports[apIdx] || __DFW_AIRPORTS[apIdx];

  return (
    <header className="hud" role="banner">
      <a href="#top" className="hud__brand" aria-label="Whiskey Tango Industries Command Center">
        <span className="hud__glyph" aria-hidden="true"></span>
        <span>WTI Command Center</span>
      </a>
      <div className="hud__chips" aria-label="System status">
        <span className="hud__chip">
          <span className="dot"></span>STATUS<strong>&nbsp;ONLINE</strong>
        </span>
        <span className="hud__chip">
          <span className="dot"></span>CH<strong>&nbsp;154.25</strong>
        </span>
        <span className="hud__chip">ENC<strong>&nbsp;AES-256</strong></span>
        <span className="hud__chip hud__chip--gps" key={ap.icao}>
          <strong>{ap.icao}</strong>
          <span className="hud__chip-coord">{ap.lat}&nbsp;·&nbsp;{ap.lon}</span>
          <span className={"metar metar--" + ap.metar} title={"METAR source: " + metarSource}>{ap.metar}</span>
        </span>
      </div>
      <span className="hud__class">WTI · For Public Release · {today}</span>
    </header>
  );
}

function formatToday() {
  const d = new Date();
  const pad = (n) => String(n).padStart(2, "0");
  const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
  return `${pad(d.getDate())} ${months[d.getMonth()]} ${d.getFullYear()}`;
}

window.HUD = HUD;
