let map;
let aircraftMarker;
let routeLine;
let trackLine;
let departureCircle;
let arrivalCircle;
const trackPoints = [];

function initializeMap(departure, arrival, rules) {
  departure = parsePayload(departure);
  arrival = parsePayload(arrival);
  rules = parsePayload(rules);
  const tileUrl = rules?.tileUrl || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  if (map) {
    map.remove();
    trackPoints.length = 0;
  }
  map = L.map('map', { zoomControl: true });
  L.tileLayer(tileUrl, { maxZoom: 18, attribution: '&copy; OpenStreetMap contributors' }).addTo(map);

  const dep = [departure.latitude, departure.longitude];
  const arr = [arrival.latitude, arrival.longitude];
  L.marker(dep).addTo(map).bindPopup(`${departure.icao} ${departure.name}`);
  L.marker(arr).addTo(map).bindPopup(`${arrival.icao} ${arrival.name}`);
  routeLine = L.polyline([dep, arr], { color: '#ffb703', weight: 3, dashArray: '8 7' }).addTo(map);
  trackLine = L.polyline(trackPoints, { color: '#4cc9f0', weight: 4 }).addTo(map);
  showDepartureRadius(departure.latitude, departure.longitude, rules?.departureRadiusNm || 3);
  showArrivalRadius(arrival.latitude, arrival.longitude, rules?.arrivalRadiusNm || 3);
  fitRoute();
}

const aircraftIcon = L.divIcon({
  className: 'aircraft-icon',
  html: '<svg viewBox="0 0 24 24" width="28" height="28"><path fill="#087D95" stroke="#fff" stroke-width="1" d="M12 1 L15 9 L23 13 L23 15 L15 13 L15 18 L19 21 L19 23 L12 21.5 L5 23 L5 21 L9 18 L9 13 L1 15 L1 13 L9 9 Z"/></svg>',
  iconSize: [28, 28],
  iconAnchor: [14, 14],
});

function updateAircraftPosition(lat, lon, heading, altitude) {
  const pos = [lat, lon];
  if (!aircraftMarker) {
    aircraftMarker = L.marker(pos, { icon: aircraftIcon }).addTo(map);
  }
  aircraftMarker.setLatLng(pos).bindPopup(`HDG ${Math.round(heading)} ALT ${Math.round(altitude)} ft`);
  const iconEl = aircraftMarker.getElement();
  if (iconEl) {
    iconEl.style.transform += ` rotate(${heading}deg)`;
    iconEl.style.transformOrigin = 'center';
  }
}

function appendTrackPoint(lat, lon) {
  trackPoints.push([lat, lon]);
  if (trackLine) {
    trackLine.setLatLngs(trackPoints);
  }
}

function setFlightPhase(phase) {
  document.body.dataset.phase = phase;
}

function showDepartureRadius(lat, lon, radiusNm) {
  if (departureCircle) departureCircle.remove();
  departureCircle = L.circle([lat, lon], { radius: radiusNm * 1852, color: '#2a9d8f', fillOpacity: 0.08 }).addTo(map);
}

function showArrivalRadius(lat, lon, radiusNm) {
  if (arrivalCircle) arrivalCircle.remove();
  arrivalCircle = L.circle([lat, lon], { radius: radiusNm * 1852, color: '#e76f51', fillOpacity: 0.08 }).addTo(map);
}

function fitRoute() {
  if (routeLine) {
    map.fitBounds(routeLine.getBounds(), { padding: [28, 28] });
  }
}

function parsePayload(value) {
  if (typeof value === 'string') {
    return JSON.parse(value);
  }

  return value;
}
