<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bounding Box Earth View</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
  @import url('https://fonts.googleapis.com/css2?family=VT323&family=Share+Tech+Mono&display=swap');
  :root {
    --bg: #00205b;
    --panel: #005587;
    --blue: #0085ad;
    --mid: #6399ae;
    --light: #b7c9d3;
    --white: #ffffff;
    --black: #000000;
    --line: rgba(183,201,211,0.42);
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { width: 100%; height: 100%; }
  body {
    background: var(--bg);
    color: var(--white);
    font-family: 'Share Tech Mono', monospace;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .board-header {
    min-height: 56px;
    background: linear-gradient(90deg, var(--light), var(--blue));
    color: var(--bg);
    padding: 9px 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 0 0 auto;
  }
  .board-title {
    font-family: 'VT323', monospace;
    font-size: 29px;
    letter-spacing: 4px;
    text-transform: uppercase;
    line-height: 1;
  }
  .board-sub {
    font-size: 10px;
    letter-spacing: 2px;
    margin-top: 3px;
    text-transform: uppercase;
  }
  .actions {
    margin-left: auto;
    display: flex;
    gap: 8px;
  }
  .actions a {
    background: var(--bg);
    border: 1px solid var(--bg);
    color: var(--white);
    font-family: 'VT323', monospace;
    font-size: 19px;
    letter-spacing: 1px;
    padding: 4px 10px;
    text-decoration: none;
    white-space: nowrap;
  }
  .actions a:hover { background: var(--white); color: var(--bg); }
  .map-shell {
    position: relative;
    flex: 1 1 auto;
    min-height: 280px;
  }
  #map { position: absolute; inset: 0; background: #12202a; }
  .status {
    position: absolute;
    left: 12px;
    bottom: 12px;
    z-index: 600;
    max-width: min(620px, calc(100% - 24px));
    background: rgba(0,32,91,0.92);
    border: 1px solid var(--line);
    padding: 8px 11px;
    color: var(--light);
    font-size: 11px;
    line-height: 1.45;
  }
  .coordinate-strip {
    flex: 0 0 auto;
    background: var(--panel);
    border-top: 1px solid var(--line);
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
  }
  .coordinate {
    padding: 8px 10px;
    border-right: 1px solid var(--line);
    min-width: 0;
  }
  .coordinate:last-child { border-right: 0; }
  .coordinate strong {
    display: block;
    color: var(--white);
    font-family: 'VT323', monospace;
    font-size: 18px;
    letter-spacing: 1px;
    font-weight: normal;
  }
  .coordinate span {
    display: block;
    color: var(--light);
    font-size: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .point-marker {
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background: var(--white);
    border: 3px solid var(--bg);
    box-shadow: 0 0 0 2px var(--blue);
  }
  .home-marker {
    width: 18px;
    height: 18px;
    background: var(--bg);
    border: 3px solid var(--white);
    box-shadow: 0 0 0 2px var(--blue);
  }
  .leaflet-tooltip {
    background: var(--bg);
    border: 1px solid var(--mid);
    border-radius: 0;
    color: var(--white);
    box-shadow: none;
    font-family: 'Share Tech Mono', monospace;
    font-size: 11px;
  }
  .leaflet-tooltip::before { display: none; }
  @media (max-width: 720px) {
    .board-header { align-items: flex-start; flex-wrap: wrap; }
    .actions { width: 100%; margin-left: 0; }
    .actions a { flex: 1; text-align: center; }
    .coordinate-strip { grid-template-columns: 1fr 1fr; }
    .coordinate { border-bottom: 1px solid var(--line); }
    .coordinate:last-child { grid-column: 1 / -1; }
  }
</style>
</head>
<body>
  <header class="board-header">
    <div>
      <div class="board-title">Bounding Box Earth View</div>
      <div class="board-sub">Current configured flight detection area</div>
    </div>
    <nav class="actions">
      <a href="/bounding-box.kml">Google Earth KML</a>
      <a href="/config">Config</a>
      <a href="/">Board</a>
    </nav>
  </header>

  <main class="map-shell">
    <div id="map" role="application" aria-label="Bounding box satellite map"></div>
    <div class="status" id="status">Loading current coordinates...</div>
  </main>

  <footer class="coordinate-strip" id="coordinates"></footer>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
  const statusEl = document.getElementById('status');
  const coordinatesEl = document.getElementById('coordinates');

  function pointIcon(home = false) {
    return L.divIcon({
      className: '',
      html: `<div class="point-marker${home ? ' home-marker' : ''}"></div>`,
      iconSize: home ? [18, 18] : [14, 14],
      iconAnchor: home ? [9, 9] : [7, 7],
    });
  }

  function coordinateItem(label, point) {
    return `<div class="coordinate"><strong>${label}</strong>` +
      `<span>${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}</span></div>`;
  }

  async function loadMap() {
    try {
      const response = await fetch(`/api/bounding-box?_=${Date.now()}`, {cache: 'no-store'});
      const data = await response.json();
      if (!response.ok || !data.ok) throw new Error(data.error || 'Coordinates unavailable');

      const map = L.map('map', {zoomControl: true});
      L.tileLayer(
        'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        {maxZoom: 19, attribution: 'Imagery &copy; Esri and contributors'}
      ).addTo(map);
      L.tileLayer(
        'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}',
        {maxZoom: 19, attribution: 'Labels &copy; Esri'}
      ).addTo(map);

      const points = [
        ['Top Left', data.top_left],
        ['Top Right', data.top_right],
        ['Bottom Right', data.bottom_right],
        ['Bottom Left', data.bottom_left],
      ];
      const polygon = points.map(([, point]) => [point.lat, point.lon]);
      L.polygon(polygon, {
        color: '#00a5ff',
        weight: 4,
        opacity: 1,
        fillColor: '#0085ad',
        fillOpacity: 0.18,
      }).addTo(map);

      points.forEach(([label, point]) => {
        L.marker([point.lat, point.lon], {icon: pointIcon(false)})
          .addTo(map)
          .bindTooltip(`${label}<br>${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`, {
            permanent: true,
            direction: 'top',
            offset: [0, -9],
          });
      });
      L.marker([data.home.lat, data.home.lon], {icon: pointIcon(true)})
        .addTo(map)
        .bindTooltip(`Home<br>${data.home.lat.toFixed(6)}, ${data.home.lon.toFixed(6)}`, {
          permanent: true,
          direction: 'bottom',
          offset: [0, 11],
        });

      map.fitBounds(L.latLngBounds(polygon).pad(0.16));
      coordinatesEl.innerHTML =
        coordinateItem('Home', data.home) +
        coordinateItem('Top Left', data.top_left) +
        coordinateItem('Top Right', data.top_right) +
        coordinateItem('Bottom Left', data.bottom_left) +
        coordinateItem('Bottom Right', data.bottom_right);
      statusEl.textContent = 'Satellite view uses the current saved bounding box. Download the KML to open the same overlay in Google Earth.';
    } catch (error) {
      statusEl.textContent = `Unable to load bounding box: ${error.message}`;
    }
  }

  loadMap();
</script>
</body>
</html>
