<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flight Tracker</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=VT323&family=Share+Tech+Mono&display=swap');

  :root {
    --bg: #00205b;
    --board: #005587;
    --amber: #b7c9d3;
    --amber-dim: #6399ae;
    --amber-glow: rgba(183,201,211,0.12);
    --amber-bright: #ffffff;
    --red: #b7c9d3;
    --green: #0085ad;
    --orange: #000000;
    --row-border: rgba(99,153,174,0.28);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    background: var(--bg);
    color: var(--amber);
    font-family: 'Share Tech Mono', monospace;
    min-height: 100vh;
    overflow-x: hidden;
  }

  /* Scanlines */
  body::before {
    content: '';
    position: fixed;
    inset: 0;
    background: repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.03) 2px, rgba(0,0,0,0.03) 4px);
    pointer-events: none;
    z-index: 1000;
  }

  /* Header */
  .board-header {
    background: linear-gradient(90deg, #b7c9d3, #0085ad);
    color: #00205b;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .board-title {
    font-family: 'VT323', monospace;
    font-size: 32px;
    letter-spacing: 4px;
    text-transform: uppercase;
  }

  .board-subtitle {
    font-size: 11px;
    letter-spacing: 3px;
    text-transform: uppercase;
    opacity: 0.6;
    font-family: 'Share Tech Mono', monospace;
    margin-left: 8px;
  }

  .board-clock {
    font-family: 'VT323', monospace;
    font-size: 24px;
    margin-left: auto;
    background: #00205b;
    color: var(--amber);
    padding: 2px 12px;
    letter-spacing: 3px;
  }

  /* Column headers */
  .col-headers {
    display: grid;
    grid-template-columns: 85px 1fr 100px 80px 110px;
    padding: 8px 16px;
    border-bottom: 2px solid var(--amber-dim);
    background: rgba(183,201,211,0.08);
  }

  .col-header {
    font-size: 10px;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: var(--amber-dim);
  }

  /* Board rows */
  .board-section { }

  .section-label {
    font-family: 'VT323', monospace;
    font-size: 22px;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: var(--amber-bright);
    padding: 10px 16px 6px;
    border-bottom: 1px solid var(--amber-dim);
  }

  a.board-row {
    display: grid;
    grid-template-columns: 85px 1fr 100px 80px 110px;
    padding: 0 16px;
    border-bottom: 1px solid var(--row-border);
    text-decoration: none;
    color: var(--amber);
    position: relative;
    overflow: hidden;
  }

  a.board-row::before {
    content: '';
    position: absolute;
    inset: 0;
    background: var(--amber-glow);
    opacity: 0;
    transition: opacity 0.15s;
  }

  a.board-row:hover::before { opacity: 1; }

  .row-cell {
    padding: 10px 8px;
    font-family: 'VT323', monospace;
    font-size: 20px;
    letter-spacing: 1px;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 1;
  }

  .row-cell.time { color: var(--amber-bright); font-size: 22px; }
  .row-cell.flight { color: var(--amber-dim); font-size: 17px; }
  .row-cell.gate { color: var(--amber-dim); font-size: 17px; }
  .status-open { color: var(--green); }
  .status-data { color: var(--amber); }

  .board-divider {
    height: 6px;
    background: repeating-linear-gradient(90deg, var(--amber-dim) 0, var(--amber-dim) 4px, transparent 4px, transparent 12px);
    opacity: 0.25;
    margin: 6px 0;
  }

  /* Two-panel area */
  .panels-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    border-top: 2px solid var(--amber-dim);
    border-bottom: 2px solid var(--amber-dim);
    margin: 6px 0;
  }

  .panel {
    padding: 14px 16px;
    border-right: 1px solid var(--amber-dim);
  }

  .panel:last-child { border-right: none; }

  .panel-label {
    font-family: 'VT323', monospace;
    font-size: 22px;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: var(--amber-bright);
    margin-bottom: 10px;
    padding-bottom: 6px;
    border-bottom: 1px solid var(--amber-dim);
  }

  .track-status {
    font-family: 'VT323', monospace;
    font-size: 20px;
    color: var(--amber-dim);
    margin-bottom: 8px;
    min-height: 22px;
  }

  .track-status span { color: var(--amber-bright); }

  .input-row {
    display: flex;
    gap: 6px;
    margin-bottom: 6px;
  }

  input[type=text] {
    flex: 1;
    min-width: 0;
    background: transparent;
    border: none;
    border-bottom: 2px solid var(--amber-dim);
    color: var(--amber);
    font-family: 'VT323', monospace;
    font-size: 22px;
    padding: 3px 6px;
    outline: none;
    letter-spacing: 2px;
    text-transform: uppercase;
    transition: border-color 0.2s;
  }

  input[type=text]:focus { border-color: var(--amber); }
  input[type=text]::placeholder { color: var(--amber-dim); text-transform: none; font-size: 16px; letter-spacing: 0; }

  button {
    background: transparent;
    border: 1px solid var(--amber-dim);
    color: var(--amber);
    font-family: 'VT323', monospace;
    font-size: 20px;
    letter-spacing: 2px;
    padding: 3px 12px;
    cursor: pointer;
    text-transform: uppercase;
    transition: all 0.15s;
    white-space: nowrap;
  }

  button:hover { background: var(--amber-glow); border-color: var(--amber); }
  button.clear { color: var(--amber-dim); }
  button.save-anyway { color: var(--orange); border-color: var(--orange); }
  button.cancel { color: var(--amber-dim); }
  button:disabled { opacity: 0.3; cursor: wait; }

  .status {
    font-family: 'VT323', monospace;
    font-size: 17px;
    padding: 5px 8px;
    display: none;
    border-left: 3px solid;
    margin-top: 5px;
    letter-spacing: 1px;
  }

  .status.found     { border-color: var(--green);  color: var(--green);  display: block; }
  .status.not-found { border-color: var(--orange); color: var(--orange); display: block; }
  .status.error     { border-color: var(--red);    color: var(--red);    display: block; }
  .status.saved     { border-color: var(--amber);  color: var(--amber);  display: block; }
  .status.searching { border-color: var(--amber-dim); color: var(--amber-dim); display: block; }

  .confirm-row { display: none; gap: 6px; margin-top: 6px; }

  .note {
    font-size: 11px;
    color: var(--amber-dim);
    margin-top: 8px;
    letter-spacing: 0.5px;
    line-height: 1.5;
  }

  .note span { color: var(--amber); }

  .airport-row {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 6px;
  }

  .airport-input { width: 65px; flex: none; text-align: center; }
  .arrow-sep { color: var(--amber-dim); font-family: 'VT323', monospace; font-size: 22px; }

  .results-table {
    width: 100%;
    border-collapse: collapse;
    font-family: 'VT323', monospace;
    font-size: 17px;
    display: none;
    margin-top: 8px;
  }

  .results-table th {
    text-align: left;
    padding: 4px 6px;
    color: var(--amber-dim);
    font-size: 10px;
    letter-spacing: 2px;
    text-transform: uppercase;
    border-bottom: 1px solid var(--amber-dim);
    font-family: 'Share Tech Mono', monospace;
  }

  .results-table td { padding: 5px 6px; border-bottom: 1px solid var(--row-border); }
  .results-table tr:hover td { background: var(--amber-glow); cursor: pointer; }
  .live-badge { color: var(--green); font-size: 13px; margin-left: 5px; }

  @media (max-width: 600px) {
    .panels-grid { grid-template-columns: 1fr; }
    .panel { border-right: none; border-bottom: 1px solid var(--amber-dim); }
    .col-headers, a.board-row { grid-template-columns: 70px 1fr 80px; }
    .col-header:nth-child(n+4), .row-cell:nth-child(n+4) { display: none; }
    .board-title { font-size: 24px; }
  }
</style>
</head>
<body>

<div class="board-header">
  <span style="font-size:26px">✈</span>
  <div>
    <span class="board-title" id="board-title">Flight Tracker</span>
    <span class="board-subtitle" id="location-name"></span>
  </div>
  <div class="board-clock" id="clock">00:00:00</div>
</div>

<div class="col-headers">
  <div class="col-header">Time</div>
  <div class="col-header">Destination</div>
  <div class="col-header">Flight No.</div>
  <div class="col-header">Gate</div>
  <div class="col-header">Remarks</div>
</div>

<div class="board-body">

  <div class="section-label">▸ Data &amp; Maps</div>

  <a class="board-row" href="/stats">
    <div class="row-cell time" id="t0">--:--</div>
    <div class="row-cell">FLIGHT STATISTICS</div>
    <div class="row-cell flight">STATS</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <a class="board-row" href="/closest">
    <div class="row-cell time" id="t1">--:--</div>
    <div class="row-cell">CLOSEST FLIGHT MAP</div>
    <div class="row-cell flight">MAP01</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <a class="board-row" href="/farthest">
    <div class="row-cell time" id="t2">--:--</div>
    <div class="row-cell">FARTHEST FLIGHTS MAP</div>
    <div class="row-cell flight">MAP02</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <a class="board-row" href="/counter">
    <div class="row-cell time" id="t3">--:--</div>
    <div class="row-cell">FLIGHT COUNTER LOG</div>
    <div class="row-cell flight">LOG03</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-data">DATA</span></div>
  </a>

  <a class="board-row" href="/database">
    <div class="row-cell time" id="t7">--:--</div>
    <div class="row-cell">FLIGHT DATABASE</div>
    <div class="row-cell flight">DB</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-data">DATA</span></div>
  </a>

  <a class="board-row" href="/closest/json">
    <div class="row-cell time" id="t4">--:--</div>
    <div class="row-cell">CLOSEST FLIGHT LOGS</div>
    <div class="row-cell flight">LOG01</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-data">DATA</span></div>
  </a>

  <a class="board-row" href="/farthest/json">
    <div class="row-cell time" id="t5">--:--</div>
    <div class="row-cell">FARTHEST FLIGHTS LOGS</div>
    <div class="row-cell flight">LOG02</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-data">DATA</span></div>
  </a>

  <a class="board-row" href="/tracked">
    <div class="row-cell time" id="t8">--:--</div>
    <div class="row-cell">TRACK A FLIGHT</div>
    <div class="row-cell flight">TRK</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <a class="board-row" href="/bounding-box">
    <div class="row-cell time" id="t9">--:--</div>
    <div class="row-cell">BOUNDING BOX EARTH VIEW</div>
    <div class="row-cell flight">ZONE</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <a class="board-row" href="/config">
    <div class="row-cell time" id="t6">--:--</div>
    <div class="row-cell">CONFIGURATION</div>
    <div class="row-cell flight">CFG</div>
    <div class="row-cell gate">--</div>
    <div class="row-cell"><span class="status-open">OPEN</span></div>
  </a>

  <div class="board-divider"></div>

  <div style="display:none;padding:0 16px;">
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;">

    <!-- Track a Flight -->
    <div style="border:1px solid var(--amber-dim);padding:16px;background:rgba(183,201,211,0.06);">
      <div class="panel-label">▸ Track a Flight</div>
      <div class="track-status" id="current-tracked">Loading...</div>
      <div class="input-row">
        <input type="text" id="callsign-input" placeholder="e.g. UAL1134" maxlength="10" />
        <button id="btn-track" onclick="lookupAndTrack()">Track</button>
        <button class="clear" onclick="clearTracked()">Clear</button>
      </div>
      <div id="track-status" class="status"></div>
      <div class="confirm-row" id="confirm-row">
        <button class="save-anyway" onclick="saveAnyway()">Save anyway</button>
        <button class="cancel" onclick="cancelSave()">Cancel</button>
      </div>
      <div id="flight-picker" style="display:none;flex-direction:column;gap:6px;margin-top:8px"></div>
      <div class="note">Use 3-letter ICAO callsign (e.g. <span>UAL</span>1134, <span>AAL</span>2709, <span>DAL</span>8008) — not the 2-letter code. Regional flights may not be supported.</div>
    </div>

    <!-- Empty right cell -->
    <div></div>

  </div>
  </div>

</div>

<script>
  fetch('/airport-code').then(r=>r.json()).then(d=>{
    const loc = d.name || 'Flight Tracker';
    document.title = `${loc} Flight Tracker`;
    document.getElementById('board-title').textContent = `${loc} Flight Tracker`;
    document.getElementById('location-name').textContent = '';
  }).catch(()=>{});

  function updateClock() {
    const now = new Date();
    const pad = n => String(n).padStart(2,'0');
    document.getElementById('clock').textContent = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
    const base = now.getHours() * 60 + now.getMinutes();
    for (let i = 0; i < 10; i++) {
      const m = base + i * 5;
      const el = document.getElementById('t'+i);
      if (el) el.textContent = `${pad(Math.floor(m/60)%24)}:${pad(m%60)}`;
    }
  }
  updateClock();
  setInterval(updateClock, 1000);

  let pendingCallsign = "";
  let pendingCachedRoute = null;

  async function loadCurrent() {
    try {
      const res  = await fetch("/tracked/json");
      const data = await res.json();
      const el   = document.getElementById("current-tracked");
      el.innerHTML = data.callsign ? `TRACKING: <span>${data.callsign}</span>` : `NOT CURRENTLY TRACKING ANY FLIGHT`;
    } catch { document.getElementById("current-tracked").textContent = "ERROR"; }
  }

  function setStatus(id, msg, type) {
    const el = document.getElementById(id);
    el.textContent = msg; el.className = "status " + type;
  }

  function showConfirm(show) {
    document.getElementById("confirm-row").style.display = show ? "flex" : "none";
  }

  function showPicker(flights) {
    const picker = document.getElementById("flight-picker");
    picker.innerHTML = "";
    picker.style.display = "flex";
    flights.forEach(f => {
      const dep = f.scheduled_departure
        ? new Date(f.scheduled_departure * 1000).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})
        : "";
      const parts = [f.airline || f.callsign, f.origin && f.destination ? `${f.origin}→${f.destination}` : "",
        f.aircraft || "", f.registration || "", dep ? `DEP ${dep}` : "",
        `<span style="color:${f.is_live?'var(--green)':'var(--amber-dim)'}">${f.status}</span>`].filter(Boolean);
      const btn = document.createElement("button");
      btn.className = "save-anyway";
      btn.style.cssText = "text-align:left;font-size:12px;letter-spacing:1px;padding:6px 10px";
      btn.innerHTML = parts.join("  ·  ");
      btn.onclick = () => selectFlight(f);
      picker.appendChild(btn);
    });
  }

  function hidePicker() {
    const p = document.getElementById("flight-picker");
    p.style.display = "none"; p.innerHTML = "";
  }

  async function selectFlight(f) {
    hidePicker();
    await saveCallsign(f.callsign, f.cached_route || null, f.flight_id || "", f.scheduled_departure || null);
    const dep = f.scheduled_departure
      ? new Date(f.scheduled_departure * 1000).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})
      : null;
    const route = f.origin && f.destination ? `${f.origin}→${f.destination}` : "";
    const parts = [`✓ SAVED: ${f.callsign}`, f.airline || "", route, f.aircraft || "",
      dep ? `DEP ${dep}` : "", f.status === "Airborne" ? "AIRBORNE NOW" : (dep ? "WILL TRACK FROM DEPARTURE" : "")].filter(Boolean);
    setStatus("track-status", parts.join("  ·  "), "found");
    document.getElementById("callsign-input").value = "";
  }

  async function lookupAndTrack() {
    const val = document.getElementById("callsign-input").value.trim().toUpperCase();
    if (!val) return;
    const btn = document.getElementById("btn-track");
    btn.disabled = true; btn.textContent = "...";
    showConfirm(false); hidePicker();
    setStatus("track-status", `SEARCHING ${val}...`, "searching");
    try {
      const res  = await fetch("/tracked/lookup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callsign:val})});
      const data = await res.json();
      if (data.found && data.multiple) {
        setStatus("track-status", data.summary, "not-found");
        showPicker(data.flights);
      } else if (data.found) {
        const f = data.flight;
        await saveCallsign(f.callsign, f.cached_route || null, f.flight_id || "", f.scheduled_departure || null);
        const dep = f.scheduled_departure
          ? new Date(f.scheduled_departure * 1000).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})
          : null;
        const route = f.origin && f.destination ? `${f.origin}→${f.destination}` : "";
        const parts = [`✓ SAVED: ${f.callsign}`, f.airline || "", route, f.aircraft || "",
          dep ? `DEP ${dep}` : "", f.status === "Airborne" ? "AIRBORNE NOW" : (dep ? "WILL TRACK FROM DEPARTURE" : "")].filter(Boolean);
        setStatus("track-status", parts.join("  ·  "), "found");
        document.getElementById("callsign-input").value = "";
        showConfirm(false);
      } else {
        pendingCallsign = val; pendingCachedRoute = null;
        setStatus("track-status", `${val} NOT FOUND — NOT AIRBORNE? SAVE ANYWAY TO TRACK WHEN LIVE.`, "not-found");
        showConfirm(true);
      }
    } catch(e) { setStatus("track-status", "LOOKUP FAILED: " + e.message, "error"); showConfirm(false); }
    btn.disabled = false; btn.textContent = "Track";
  }

  async function saveAnyway() {
    if (!pendingCallsign) return;
    await saveCallsign(pendingCallsign, null, "", null);
    setStatus("track-status", `SAVED: ${pendingCallsign} — WILL TRACK WHEN LIVE`, "saved");
    document.getElementById("callsign-input").value = "";
    showConfirm(false); hidePicker(); pendingCallsign = ""; pendingCachedRoute = null;
  }

  function cancelSave() { showConfirm(false); hidePicker(); setStatus("track-status","",""); pendingCallsign=""; pendingCachedRoute=null; }

  async function saveCallsign(callsign, cached_route=null, flight_id="", scheduled_departure=null) {
    const body = {callsign};
    if (cached_route)        body.cached_route        = cached_route;
    if (flight_id)           body.flight_id           = flight_id;
    if (scheduled_departure) body.scheduled_departure = scheduled_departure;
    await fetch("/tracked/set",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
    loadCurrent();
  }

  async function clearTracked() {
    await saveCallsign("", null, "", null);
    document.getElementById("callsign-input").value = "";
    setStatus("track-status","TRACKING CLEARED","saved");
    showConfirm(false); hidePicker(); pendingCallsign = ""; pendingCachedRoute = null;
  }

  document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("callsign-input").addEventListener("keydown", e => { if(e.key==="Enter") lookupAndTrack(); });
    loadCurrent();
  });
</script>
</body>
</html>
