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();
}

function updateAircraftPosition(lat, lon, heading, altitude) {
  const pos = [lat, lon];
  if (!aircraftMarker) {
    aircraftMarker = L.marker(pos).addTo(map);
  }
  aircraftMarker.setLatLng(pos).bindPopup(`HDG ${Math.round(heading)} ALT ${Math.round(altitude)} ft`);
}

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;
}
