<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Track a Flight</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;
  }
  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;
  }
  .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;
  }
  .back {
    font-family: 'VT323', monospace;
    font-size: 20px;
    letter-spacing: 2px;
    margin-left: auto;
    background: #00205b;
    color: #ffffff;
    padding: 2px 12px;
    text-decoration: none;
  }
  .content {
    padding: 18px 16px 32px;
    max-width: 980px;
  }
  .panel {
    border: 1px solid var(--amber-dim);
    background: var(--board);
    padding: 16px;
  }
  .panel-label {
    font-family: 'VT323', monospace;
    font-size: 24px;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: var(--amber-bright);
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--amber-dim);
  }
  .track-status {
    font-family: 'VT323', monospace;
    font-size: 22px;
    color: var(--amber-dim);
    margin-bottom: 12px;
    min-height: 24px;
  }
  .track-status span { color: var(--amber-bright); }
  .input-row {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
  }
  .override-row {
    display: grid;
    gap: 8px;
    margin: 10px 0 12px;
  }
  .override-option {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--amber-bright);
    font-family: 'VT323', monospace;
    font-size: 21px;
    letter-spacing: 1px;
    cursor: pointer;
    line-height: 1.1;
  }
  input[type=checkbox] {
    appearance: none;
    width: 18px;
    height: 18px;
    flex: 0 0 18px;
    background: #000000;
    border: 1px solid var(--amber-dim);
    display: grid;
    place-items: center;
    cursor: pointer;
  }
  input[type=checkbox]::after {
    content: "";
    width: 10px;
    height: 10px;
    background: var(--amber-bright);
    transform: scale(0);
    transition: transform 0.08s ease-out;
  }
  input[type=checkbox]:checked::after { transform: scale(1); }
  input[type=checkbox]:focus-visible {
    outline: 2px solid var(--amber-bright);
    outline-offset: 2px;
  }
  input[type=text] {
    flex: 1;
    min-width: 0;
    background: #000000;
    border: 1px solid var(--amber-dim);
    color: var(--amber-bright);
    font-family: 'VT323', monospace;
    font-size: 28px;
    padding: 6px 10px;
    outline: none;
    letter-spacing: 2px;
    text-transform: uppercase;
  }
  input[type=text]:focus {
    border-color: var(--amber-bright);
    box-shadow: 0 0 0 2px rgba(183,201,211,0.20);
  }
  input[type=text]::placeholder {
    color: var(--amber-dim);
    text-transform: none;
    font-size: 18px;
    letter-spacing: 0;
  }
  button {
    background: transparent;
    border: 1px solid var(--amber-dim);
    color: var(--amber);
    font-family: 'VT323', monospace;
    font-size: 22px;
    letter-spacing: 2px;
    padding: 6px 14px;
    cursor: pointer;
    text-transform: uppercase;
    white-space: nowrap;
  }
  button:hover { background: var(--amber-glow); border-color: var(--amber-bright); color: var(--amber-bright); }
  button.clear { color: var(--amber-dim); }
  button.save-anyway { color: var(--amber-bright); border-color: var(--amber-bright); }
  button.cancel { color: var(--amber-dim); }
  button:disabled { opacity: 0.3; cursor: wait; }
  .status {
    font-family: 'VT323', monospace;
    font-size: 19px;
    padding: 7px 10px;
    display: none;
    border-left: 3px solid;
    margin-top: 8px;
    letter-spacing: 1px;
  }
  .status.found { border-color: var(--green); color: var(--green); display: block; }
  .status.not-found { border-color: var(--amber-bright); color: var(--amber-bright); 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: 8px; margin-top: 8px; }
  .note {
    font-size: 12px;
    color: var(--amber-dim);
    margin-top: 12px;
    letter-spacing: 0.5px;
    line-height: 1.5;
  }
  .note span { color: var(--amber-bright); }
  #flight-picker {
    display: none;
    flex-direction: column;
    gap: 6px;
    margin-top: 10px;
  }
  @media (max-width: 700px) {
    .input-row { flex-direction: column; }
    .board-title { font-size: 26px; }
    .content { padding: 12px; }
  }
</style>
</head>
<body>
<div class="board-header">
  <span style="font-size:26px">^</span>
  <div class="board-title">Track a Flight</div>
  <a class="back" href="/">Board</a>
</div>

<div class="content">
  <div class="panel">
    <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" autofocus>
      <button id="btn-track" onclick="lookupAndTrack()">Track</button>
      <button class="clear" onclick="clearTracked()">Clear</button>
    </div>
    <div class="override-row">
      <label class="override-option">
        <input type="checkbox" id="override_flights">
        Override bounding box flight screens
      </label>
      <label class="override-option">
        <input type="checkbox" id="override_idle" checked>
        Override time, date, temperature and forecast screens
      </label>
    </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"></div>
    <div class="note">Use 3-letter ICAO callsign, for example <span>UAL</span>1134, <span>AAL</span>2709, or <span>DAL</span>8008. Regional flights may not be supported.</div>
  </div>
</div>

<script>
let pendingCallsign = "";
let currentTrackedCallsign = "";
let loadingOptions = false;

async function loadCurrent() {
  try {
    const res = await fetch("/tracked/json");
    const data = await res.json();
    const el = document.getElementById("current-tracked");
    currentTrackedCallsign = data.callsign || "";
    el.innerHTML = data.callsign ? `TRACKING: <span>${data.callsign}</span>` : "NOT CURRENTLY TRACKING ANY FLIGHT";
    loadingOptions = true;
    document.getElementById("override_flights").checked = !!data.override_flights;
    document.getElementById("override_idle").checked = data.override_idle !== false;
    loadingOptions = false;
  } 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 route = f.origin && f.destination ? `${f.origin} -> ${f.destination}` : "";
    const flightLabel = f.number && f.number !== f.callsign ? `${f.number} (${f.callsign})` : f.callsign;
    const parts = [f.airline || flightLabel, route, f.aircraft || "", f.registration || "", dep ? `DEP ${dep}` : "", f.status].filter(Boolean);
    const btn = document.createElement("button");
    btn.className = "save-anyway";
    btn.style.cssText = "text-align:left;font-size:14px;letter-spacing:1px;padding:8px 10px";
    btn.textContent = parts.join("  |  ");
    btn.onclick = () => selectFlight(f);
    picker.appendChild(btn);
  });
}

function hidePicker() {
  const picker = document.getElementById("flight-picker");
  picker.style.display = "none";
  picker.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 flightLabel = f.number && f.number !== f.callsign ? `${f.number} AS ${f.callsign}` : f.callsign;
  const parts = [`SAVED: ${flightLabel}`, 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) {
      await selectFlight(data.flight);
      showConfirm(false);
    } else {
      pendingCallsign = val;
      setStatus("track-status", `${val} NOT FOUND. 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 = "";
}

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

async function saveCallsign(callsign, cached_route=null, flight_id="", scheduled_departure=null) {
  const body = {callsign};
  if (callsign) {
    body.override_flights = document.getElementById("override_flights").checked;
    body.override_idle = document.getElementById("override_idle").checked;
  }
  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 saveDisplayOptions() {
  if (loadingOptions) return;
  if (!currentTrackedCallsign) {
    setStatus("track-status", "TRACK A FLIGHT FIRST, THEN CHOOSE DISPLAY OPTIONS", "not-found");
    return;
  }
  try {
    const res = await fetch("/tracked/options", {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify({
        override_flights: document.getElementById("override_flights").checked,
        override_idle: document.getElementById("override_idle").checked,
      }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || "Save failed");
    setStatus("track-status", "DISPLAY OPTIONS SAVED", "saved");
    loadCurrent();
  } catch (e) {
    setStatus("track-status", "OPTION SAVE FAILED: " + e.message, "error");
  }
}

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

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