// When map is loaded it should display all the available routes, hostspots, and stations for all the shapes // Removed TypeScript 'declare global' block for plain JS compatibility

// Initialize
// --------------------
// Initialize custom window properties
// --------------------
window.editingGeofenceId = window.editingGeofenceId || null;
window.state = window.state || {};
window.state.mapLayers = window.state.mapLayers || new Map(); // Store map layers for cleanup



let map, drawingManager, activeShape;

// --------------------
// MAP INIT
// --------------------
function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -1.286389, lng: 36.817223 },
    zoom: 14,

     // UI Controls
  disableDefaultUI: true,
  zoomControl: true,
  streetViewControl: true,
  mapTypeControl: true,
  fullscreenControl: true,

  // Extra clutter removal
  clickableIcons: true,       // removes POI clicks
  // keyboardShortcuts: false,    // disables keyboard help
  gestureHandling: "greedy",   // smoother touch interaction

  // Make map look minimal
  styles: [
    { elementType: "labels.icon", stylers: [{ visibility: "off" }] },
    { featureType: "poi", stylers: [{ visibility: "off" }] },
    { featureType: "transit", stylers: [{ visibility: "off" }] }
  ]
  });

  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: null,
    drawingControl: false
  });
  drawingManager.setMap(map);

  google.maps.event.addListener(drawingManager, "overlaycomplete", e => {
    if (activeShape) activeShape.setMap(null);
    activeShape = e.overlay;
    activeShape.type = e.type;
    drawingManager.setDrawingMode(null);
    enableEdit(activeShape);
    syncGeometry();
    updateGeofenceFields();

    // Auto-fill radius if circle
    if (activeShape.type === "circle") {
      const radiusInput = document.getElementById("radiusMeters");
      if (radiusInput) radiusInput.value = activeShape.getRadius().toFixed(2);
    }
  });
  
  // Load all geofences after map is initialized
  loadAllGeofencesForMap();
}

// --------------------
// LOAD ALL GEOFENCES FOR MAP DISPLAY
// --------------------
function loadAllGeofencesForMap() {
  // Clear existing layers
  if (window.state.mapLayers) {
    window.state.mapLayers.forEach(layer => {
      if (layer && layer.setMap) {
        layer.setMap(null);
      }
    });
    window.state.mapLayers.clear();
  }
  
  // Load routes, stations, and hotspots
  loadRoutesForMap();
  loadStationsForMap();
  loadHotspotsForMap();
}

// --------------------
// LOAD ROUTES FOR MAP
// --------------------
function loadRoutesForMap() {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', API_BASE + 'geofences/routes?size=1000', true);
  xhr.setRequestHeader('Content-Type', 'application/json');

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        const data = JSON.parse(xhr.responseText);
        const routes = data.content || [];
        
        // Display each route on the map
        routes.forEach(route => {
          displayGeofenceOnMap(route);
        });
        
        console.log('Routes displayed on map:', routes.length);
      } else {
        console.error('Error loading routes for map:', xhr.responseText);
      }
    }
  };
  xhr.send();
}

// --------------------
// LOAD STATIONS FOR MAP
// --------------------
function loadStationsForMap() {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', API_BASE + 'geofences/stations?size=1000', true);
  xhr.setRequestHeader('Content-Type', 'application/json');

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        const data = JSON.parse(xhr.responseText);
        const stations = data.content || [];
        
        // Display each station on the map
        stations.forEach(station => {
          displayGeofenceOnMap(station);
        });
        
        console.log('Stations displayed on map:', stations.length);
      } else {
        console.error('Error loading stations for map:', xhr.responseText);
      }
    }
  };
  xhr.send();
}

// --------------------
// LOAD HOTSPOTS FOR MAP
// --------------------
function loadHotspotsForMap() {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', API_BASE + 'geofences/hotspots?size=1000', true);
  xhr.setRequestHeader('Content-Type', 'application/json');

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        const data = JSON.parse(xhr.responseText);
        const hotspots = data.content || [];
        
        // Display each hotspot on the map
        hotspots.forEach(hotspot => {
          displayGeofenceOnMap(hotspot);
        });
        
        console.log('Hotspots displayed on map:', hotspots.length);
      } else {
        console.error('Error loading hotspots for map:', xhr.responseText);
      }
    }
  };
  xhr.send();
}

// --------------------
// DISPLAY GEOFENCE ON MAP
// --------------------
function displayGeofenceOnMap(g) {
  if (!map) return;
  
  const color = g.colorHex || "#3B82F6";
  const commonStyle = {
    fillColor: color,
    fillOpacity: 0.2, // Lower opacity for background display
    strokeColor: color,
    strokeWeight: 2,
    map: map,
    clickable: true,
    zIndex: 0 // Lower zIndex than active shapes
  };
  
  let shape = null;
  
  // ================= CIRCLE =================
  if (g.fenceType === "CIRCLE" && g.centerLat && g.centerLng) {
    const center = new google.maps.LatLng(g.centerLat, g.centerLng);
    
    shape = new google.maps.Circle({
      ...commonStyle,
      center: center,
      radius: g.radiusMeters || 50
    });
  }
  // ================= POLYGON =================
  else if (g.fenceType === "POLYGON" && g.coordinatesJson) {
    try {
      const coords = JSON.parse(g.coordinatesJson);
      shape = new google.maps.Polygon({
        ...commonStyle,
        paths: coords
      });
    } catch (e) {
      console.error('Error parsing polygon coordinates:', e);
    }
  }
  // ================= RECTANGLE =================
  else if (g.fenceType === "RECTANGLE" && g.coordinatesJson) {
    try {
      const coords = JSON.parse(g.coordinatesJson);
      if (coords.length >= 2) {
        const sw = new google.maps.LatLng(coords[0].lat, coords[0].lng);
        const ne = new google.maps.LatLng(coords[2].lat, coords[2].lng);
        
        shape = new google.maps.Rectangle({
          ...commonStyle,
          bounds: { south: sw.lat(), west: sw.lng(), north: ne.lat(), east: ne.lng() }
        });
      }
    } catch (e) {
      console.error('Error parsing rectangle coordinates:', e);
    }
  }
  // ================= LINE / ROUTE =================
  else if ((g.fenceType === "LINE" || g.fenceType === "CORRIDOR" || g.route) && g.coordinatesJson) {
    try {
      const coords = JSON.parse(g.coordinatesJson);
      shape = new google.maps.Polyline({
        strokeColor: color,
        strokeWeight: 3,
        map: map,
        path: coords,
        zIndex: 0
      });
    } catch (e) {
      console.error('Error parsing line coordinates:', e);
    }
  }
  
  if (shape) {
    // Store shape for later cleanup
    if (!window.state.mapLayers) {
      window.state.mapLayers = new Map();
    }
    window.state.mapLayers.set(g.id, shape);
    
    // Add click listener to show info
    shape.addListener('click', () => {
      showGeofenceInfo(g);
    });
  }
}

// --------------------
// SHOW GEOFENCE INFO
// --------------------
function showGeofenceInfo(g) {
  // Create info window content
  const content = `
    <div style="padding: 10px; max-width: 250px;">
      <h3 style="margin: 0 0 5px 0; color: ${g.colorHex || '#3B82F6'};">${g.name}</h3>
      <p style="margin: 5px 0;">${g.description || 'No description'}</p>
      <p style="margin: 5px 0;">
        <strong>Type:</strong> ${g.fenceType}<br>
        <strong>Category:</strong> ${g.route ? 'Route' : g.station ? 'Station' : g.hotspot ? 'Hotspot' : 'Regular'}
      </p>
    </div>
  `;
  
  const infoWindow = new google.maps.InfoWindow({
    content: content
  });
  
  // Get position for info window
  let position;
  if (g.fenceType === "CIRCLE" && g.centerLat && g.centerLng) {
    position = { lat: g.centerLat, lng: g.centerLng };
  } else if (g.coordinatesJson) {
    try {
      const coords = JSON.parse(g.coordinatesJson);
      if (coords && coords.length > 0) {
        position = coords[0];
      }
    } catch (e) {
      console.error('Error parsing coordinates for info window:', e);
    }
  }
  
  if (position) {
    infoWindow.setPosition(position);
    infoWindow.open(map);
  }
}

// --------------------
// STYLE
// --------------------
function style() {
  return {
      fillColor: colorHex.value,
    fillOpacity: 0.3,
    strokeColor: colorHex.value,
    strokeWeight: 2,
    editable: true,
    draggable: true,
    clickable: true,
    zIndex: 1
  };
}

// --------------------
// ENABLE EDIT
// --------------------
function enableEdit(s) {
  s.setEditable?.(true);
  s.setDraggable?.(true);

  if (s.getPath) {
    s.getPath().addListener("set_at", syncGeometry);
    s.getPath().addListener("insert_at", syncGeometry);
  }

  if (s.type === "circle") {
    // Update radius field while resizing
    google.maps.event.clearListeners(s, "radius_changed"); // remove old listeners
    google.maps.event.addListener(s, "radius_changed", () => {
      const radiusInput = document.getElementById("radiusMeters");
      if (radiusInput) radiusInput.value = s.getRadius().toFixed(2);
      syncGeometry(); // update bounds and center
    });

    google.maps.event.clearListeners(s, "center_changed"); // remove old listeners
    google.maps.event.addListener(s, "center_changed", () => {
      const center = s.getCenter();
      document.getElementById("centerLat").value = center.lat();
      document.getElementById("centerLng").value = center.lng();
      syncGeometry(); // update bounds
    });
  }

  google.maps.event.clearListeners(s, "dragend");
  google.maps.event.addListener(s, "dragend", syncGeometry);
}


// --------------------
// SYNC COORDINATES
// --------------------
function syncGeometry() {
  const container = document.getElementById("coordinatesContainer");
  if (!container) return;
  container.innerHTML = "";

  const bounds = new google.maps.LatLngBounds();

  if (activeShape.type === "circle") {
    const c = activeShape.getCenter();
    document.getElementById("centerLat").value = c.lat();
    document.getElementById("centerLng").value = c.lng();
  }

  if (activeShape.getPath) {
    activeShape.getPath().forEach(p => {
      bounds.extend(p);
      addCoord(p.lat(), p.lng());
    });
  }

  if (activeShape.getBounds) {
    const b = activeShape.getBounds();
    bounds.extend(b.getSouthWest());
    bounds.extend(b.getNorthEast());
  }

  document.getElementById("minLat").value = bounds.getSouthWest().lat();
  document.getElementById("minLng").value = bounds.getSouthWest().lng();
  document.getElementById("maxLat").value = bounds.getNorthEast().lat();
  document.getElementById("maxLng").value = bounds.getNorthEast().lng();

  document.getElementById("coordinatesSection").style.display = "block";
}

function addCoord(lat, lng) {
  const container = document.getElementById("coordinatesContainer");
  if (!container) return;
  const d = document.createElement("div");
  d.textContent = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
  container.appendChild(d);
}

// --------------------
// DRAWING LOGIC
// --------------------
drawBtn.onclick = () => {
  let category = document.querySelector('input[name="geofenceCategory"]:checked')?.value;

  if (!category) return controller.showToastMsg("Select geofence type first", "#ff6666");

  let type;
  switch (category) {
    case "REGULAR": type = fenceTypeRegular.value; break;
    case "STATION": type = fenceTypeStation.value; break;
    case "ROUTE": type = fenceTypeRoute.value; break;
    case "HOTSPOT": type = fenceTypeHotspot.value; break;
  }

  if (!type) return controller.showToastMsg("Select geofence type first", "#ff6666");

  drawBtn.innerText = "Drawing...";

  drawingManager.setOptions({
    drawingMode: {
      CIRCLE: google.maps.drawing.OverlayType.CIRCLE,
      POLYGON: google.maps.drawing.OverlayType.POLYGON,
      RECTANGLE: google.maps.drawing.OverlayType.RECTANGLE,
      LINE: google.maps.drawing.OverlayType.POLYLINE,
      CORRIDOR: google.maps.drawing.OverlayType.POLYLINE
    }[type],
    circleOptions: style(),
    polygonOptions: style(),
    rectangleOptions: style(),
    polylineOptions: { strokeColor: colorHex.value, strokeWeight: 3, editable: true }
  });
};

cancelDrawBtn.onclick = () => drawingManager.setDrawingMode(null);

// --------------------
// COLOR PICKER
// --------------------
colorHex.oninput = () => colorValue.textContent = colorHex.value;

// --------------------
// TAB SWITCHING
// --------------------
document.querySelectorAll(".tab").forEach(t => {
  t.onclick = () => {
    document.querySelectorAll(".tab").forEach(x => x.classList.remove("active"));
    document.querySelectorAll(".tab-content").forEach(c => c.classList.remove("active"));
    t.classList.add("active");
    document.getElementById(t.dataset.tab + "Tab")?.classList.add("active");
  };
});

// --------------------
// SHOW/HIDE FIELDS BASED ON GEOFENCE TYPE
// --------------------
function updateGeofenceFields() {
  const category = document.querySelector('input[name="geofenceCategory"]:checked')?.value;

  document.getElementById("regularConfig").style.display = category === "REGULAR" ? "block" : "none";
  document.getElementById("stationConfig").style.display = category === "STATION" ? "block" : "none";
  document.getElementById("routeConfig").style.display = category === "ROUTE" ? "block" : "none";
  document.getElementById("hotspotConfig").style.display = category === "HOTSPOT" ? "block" : "none";

  let selectedType;
  switch(category) {
    case "REGULAR": selectedType = fenceTypeRegular.value; break;
    case "STATION": selectedType = fenceTypeStation.value; break;
    case "ROUTE": selectedType = fenceTypeRoute.value; break;
    case "HOTSPOT": selectedType = fenceTypeHotspot.value; break;
  }

  document.getElementById("circleFields").style.display = selectedType === "CIRCLE" ? "block" : "none";
}

// Event listeners
document.querySelectorAll('input[name="geofenceCategory"]').forEach(r => r.addEventListener("change", updateGeofenceFields));
fenceTypeRegular?.addEventListener("change", updateGeofenceFields);
fenceTypeStation?.addEventListener("change", updateGeofenceFields);
fenceTypeRoute?.addEventListener("change", updateGeofenceFields);
fenceTypeHotspot?.addEventListener("change", updateGeofenceFields);




// --------------------
// SAVE GEOFENCE
// --------------------
saveGeofenceBtn.onclick = async () => {
  const namevalue = document.getElementById('name')?.value?.trim();
  if (!namevalue) {
        controller.showToastMsg("Please enter a name for the geofence", "#ff6666");
    return;
  }

  if (!activeShape) {
    controller.showToastMsg("Please draw a geofence first", "#ff6666");
    return;
  }

  $("#saveGeofenceBtn").html("Creating Please Wait ...");
  $("#saveGeofenceBtn").prop("disabled", true);

  const category = document.querySelector('input[name="geofenceCategory"]:checked')?.value;
  let fenceType, isRoute = false, routeStatus =  "ACTIVE", isStation= false, isHotspot = false;

  console.log("Selected category:", category);

  switch (category) {
    case "STATION": fenceType = fenceTypeStation?.value; 
    isStation = true;
    break;
    case "ROUTE":
      fenceType = fenceTypeRoute?.value;
      isRoute = true;
      routeStatus = "ACTIVE";
      break;
    case "HOTSPOT": 
    fenceType = fenceTypeHotspot?.value;
    isHotspot = true;
    break;
  }

  // Base payload
  let payload = {
    name: namevalue,
    description: document.getElementById('description')?.value || "",
    colorHex: document.getElementById('colorHex')?.value || "#3B82F6",
    fenceType: fenceType,
    isRoute: isRoute,
    isHotspot:isHotspot,
    isStation: isStation,
    routeStatus: "ACTIVE",
    isFinalDestination: document.getElementById('isFinalDestination')?.checked || false,
    stationType: document.getElementById('stationType')?.value || "BUS_STOP",
    dwellTimeSeconds: parseInt(document.getElementById('dwellTimeSeconds')?.value) || 60,
  };

  // =========================
// STATION + CIRCLE
// =========================
if (isStation && fenceType === "CIRCLE") {

  const center = activeShape.getCenter();
  const radius = activeShape.getRadius?.();

  payload.isStation = true;
  payload.stationType = document.getElementById('stationType')?.value || "BUS_STOP";
  payload.dwellTimeSeconds = parseInt(document.getElementById('dwellTimeSeconds')?.value) || 60;
  payload.isFinalDestination = document.getElementById('isFinalDestination')?.checked || false;

  payload.centerLat = center.lat();
  payload.centerLng = center.lng();
  payload.radiusMeters = parseFloat(radius);

  console.log("FINAL STATION PAYLOAD:", payload);

  return sendPayload(payload);
}

if (isRoute && fenceType === "CORRIDOR") {

  let coords = [];

  if (activeShape.getPath) {
    activeShape.getPath().forEach(p => {
      coords.push({ lat: p.lat(), lng: p.lng() });
    });
  }

  if (coords.length < 2) {
    controller.showToastMsg("Corridor must have at least 2 points", "#ff6666");
    return;
  }

  payload.isRoute = true;
  payload.routeStatus = "ACTIVE";
  payload.bufferWidthMeters = parseInt(
    document.getElementById("bufferWidthMeters")?.value
  ) || 30;

  payload.coordinates = coords;

  console.log("FINAL CORRIDOR PAYLOAD:", payload);

  return sendPayload(payload);
}

// =========================
// ROUTE + POLYGON
// =========================
if (isRoute && fenceType === "POLYGON") {

  let coords = [];

  if (activeShape.getPath) {
    activeShape.getPath().forEach(p => {
      coords.push({ lat: p.lat(), lng: p.lng() });
    });
  }

  if (coords.length < 3) {
    controller.showToastMsg("Route polygon must have at least 3 points", "#ff6666");
    return;
  }

  // Remove duplicate closing point if present
  const first = coords[0];
  const last = coords[coords.length - 1];

  if (first.lat === last.lat && first.lng === last.lng) {
    coords.pop();
  }

  payload.isRoute = true;
  payload.routeStatus = "ACTIVE";
  payload.coordinates = coords;

  console.log("FINAL ROUTE POLYGON PAYLOAD:", payload);

  return sendPayload(payload);
}

  // REGULAR CIRCLE
  if (fenceType === "CIRCLE") {
    const center = activeShape.getCenter();
    const radius = activeShape.getRadius?.();
    payload.centerLat = center.lat();
    payload.centerLng = center.lng();
    payload.radiusMeters = parseFloat(radius);
  }

  // HOTSPOT CIRCLE
  else if (category === "HOTSPOT" && fenceType === "CIRCLE") {
    const center = activeShape.getCenter();
    const radius = activeShape.getRadius?.();
    payload.centerLat = center.lat();
    payload.centerLng = center.lng();
    payload.radiusMeters = parseFloat(radius);
    payload.isHotspot = true;
    payload.isAutoAssigned = document.getElementById('isAutoAssigned')?.checked ?? true;
  }
  else if (fenceType === "RECTANGLE") {
    const b = activeShape.getBounds();

    payload.minLat = b.getSouthWest().lat();
    payload.minLng = b.getSouthWest().lng();
    payload.maxLat = b.getNorthEast().lat();
    payload.maxLng = b.getNorthEast().lng();
    } else {
    let coords = [];
    if (activeShape.getPath) {
      activeShape.getPath().forEach(p => coords.push({ lat: p.lat(), lng: p.lng() }));
    } else if (activeShape.getBounds) {
      const b = activeShape.getBounds();
      coords = [
        { lat: b.getSouthWest().lat(), lng: b.getSouthWest().lng() },
        { lat: b.getSouthWest().lat(), lng: b.getNorthEast().lng() },
        { lat: b.getNorthEast().lat(), lng: b.getNorthEast().lng() },
        { lat: b.getNorthEast().lat(), lng: b.getSouthWest().lng() }
      ];
    }

    // ROUTE (LINE)
    if (fenceType === "LINE" && isRoute) {
        if (coords.length < 3) {
        controller.showToastMsg("Route must have at least 3 points", "#ff6666");
        return;
        }
    }

    // POLYGON
   if (fenceType === "POLYGON") {
        if (coords.length < 3) {
            controller.showToastMsg("Polygon needs at least 3 points", "#ff6666");
            return;
        }

        // Remove duplicate closing point if present
        const first = coords[0];
        const last = coords[coords.length - 1];

        if (first.lat === last.lat && first.lng === last.lng) {
            coords.pop();
        }
        }
    payload.coordinates = coords;
  }

  console.log("FINAL PAYLOAD:", payload);

  try {
    const res = await fetch(API_BASE + 'geofences', {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!res.ok) {
      const err = await res.text();
      throw err;
    }

    controller.showToastMsg("Geofence saved successfully", "#1a5589");

    drawBtn.innerText = "Start Drawing";
    
    // Reload map display after save
    setTimeout(() => {
      loadAllGeofencesForMap();
      window.location.reload();
    }, 1000);
  } catch (e) {
    console.error(e);
    controller.showToastMsg("Failed to save geofence", "#ff6666");
  }
};

async function sendPayload(payload) {
  try {
    const res = await fetch(API_BASE + 'geofences', {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!res.ok) {
      const err = await res.text();
      throw err;
    }

    controller.showToastMsg("Geofence saved successfully", "#1a5589");
    drawBtn.innerText = "Start Drawing";
    
    // Reload map display after save
    setTimeout(() => {
      loadAllGeofencesForMap();
      window.location.reload();
    }, 1000);

  } catch (e) {
    console.error(e);
    controller.showToastMsg("Failed to save geofence", "#ff6666");
      $("#saveGeofenceBtn").html("Creating Geofence");
  $("#saveGeofenceBtn").prop("disabled", false);
  }
}

// Initial call
updateGeofenceFields();

// Load tabs views
loadRoutes();
loadStations();
loadHotspots();
loadAllGeofences();

// stations logics
document.getElementById('searchRoutes')
    .addEventListener('input', function () {

        const query = this.value.toLowerCase().trim();
        const allGeofences = window.state?.routes || [];

        const filtered = allGeofences.filter(g =>
            (g.name && g.name.toLowerCase().includes(query)) ||
            (g.description && g.description.toLowerCase().includes(query)) ||
            (g.fenceType && g.fenceType.toLowerCase().includes(query))
        );

        renderGeofences(filtered, 'Routes');
    });

function loadRoutes() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/routes?size=1000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                window.state = window.state || {};
                window.state.routes = data.content || [];

                console.log('Routes loaded:', window.state.routes);
                renderGeofences(window.state.routes, 'Routes');
            } else {
                console.error('Error loading routes:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

// Function to render geofences in a list like your screenshot
function renderGeofences(geofences, typeLabel) {
    const container = document.getElementById('geofenceList');
    if (!container) return;

    if (!geofences || geofences.length === 0) {
        container.innerHTML = `
            <div class="no-notifications">
                No geofences available
            </div>
        `;
        return;
    }

    let html = `
        <div class="notifications-wrapper" style="
            display:flex;
            flex-direction:column;
            gap:15px;
        ">
    `;

    geofences.forEach(g => {

        html += `
        <div class="notification-card" data-id="${g.id}">
            
            <div class="notification-header">
                <span class="notification-title">${g.name}</span>
                <span class="notification-time">
                    ${new Date(g.createdAt).toLocaleDateString()}
                </span>
            </div>

            <div class="notification-body">
                <p>${g.description || g.name}</p>
            </div>

            <div class="notification-footer">
                <span class="priority" style="
                    background:${g.colorHex || '#3B82F6'};
                    color:#fff;
                    padding:3px 8px;
                    border-radius:4px;
                    font-size:12px;">
                    ${g.fenceType || 'N/A'}
                </span>

                <span class="type">${typeLabel || 'Geofence'}</span>

              <div class="notification-actions icon-actions">
                    <i class="fa-solid fa-eye action-icon view"
                    title="View"
                    onclick="viewGeofence(${g.id})"></i>

                    <i class="fa-solid fa-pen action-icon edit"
                    title="Edit"
                    onclick="editGeofence(${g.id})"></i>

                    <i class="fa-solid fa-trash action-icon delete"
                    title="Delete"
                    onclick="deleteGeofence(${g.id})"></i>
                </div>

            </div>

        </div>
        `;
    });

    html += `</div>`;
    container.innerHTML = html;
}

async function deleteGeofence(id, event) { 
    console.log('Delete', id);

    if (event) event.stopPropagation();
            
    if (!confirm('Are you sure you want to delete this geofence? This action cannot be undone.')) {
        return;
    }
            
    try {
        const response = await fetch(API_BASE + `geofences/${id}`, {
            method: 'DELETE'
        });
                
        if (response.ok) {
            controller.showToastMsg("Geofence deleted successfully", "#1a5589");
            
            // Remove from map
            const layer = window.state.mapLayers?.get(id);
            if (layer) {
                layer.setMap(null);
                window.state.mapLayers.delete(id);
            }
            
            setTimeout(() => window.location.reload(), 1000);
        } else {
            const data = await response.json();
            controller.showToastMsg("Failed to delete geofence", "#ff3300");
            setTimeout(() => window.location.reload(), 1000);
        }
    } catch (error) {
        console.error('Error deleting geofence:', error);
        setTimeout(() => window.location.reload(), 1000);
    }
}

// Call the function
function viewGeofence(id) {
    const all = window.state?.routes || [];
    const g = all.find(x => x.id === id);
    if (!g) return console.warn("Geofence not found", id);

    // Remove existing shape
    if (activeShape) activeShape.setMap(null);

    const color = g.colorHex || "#3B82F6";
    const commonStyle = {
        fillColor: color,
        fillOpacity: 0.3,
        strokeColor: color,
        strokeWeight: 2,
        editable: true,
        draggable: true,
        map: map
    };

    let bounds = new google.maps.LatLngBounds();

    // ================= CIRCLE =================
   if (g.fenceType === "CIRCLE" && g.centerLat && g.centerLng) {

    const center = new google.maps.LatLng(g.centerLat, g.centerLng);

    activeShape = new google.maps.Circle({
        ...commonStyle,
        center: center,
        radius: g.radiusMeters || 50
    });

    bounds = activeShape.getBounds();

    document.getElementById("centerLat").value = g.centerLat;
    document.getElementById("centerLng").value = g.centerLng;
    document.getElementById("radiusMeters").value = g.radiusMeters;
}
    // ================= POLYGON =================
    else if (g.fenceType === "POLYGON" && g.coordinatesJson) {

        const coords = JSON.parse(g.coordinatesJson);

        activeShape = new google.maps.Polygon({
            ...commonStyle,
            paths: coords
        });

        coords.forEach(c => bounds.extend(c));
    }
    // ================= RECTANGLE =================
    else if (g.fenceType === "RECTANGLE" && g.coordinatesJson) {

        const coords = JSON.parse(g.coordinatesJson);

        const sw = new google.maps.LatLng(coords[0].lat, coords[0].lng);
        const ne = new google.maps.LatLng(coords[2].lat, coords[2].lng);

        activeShape = new google.maps.Rectangle({
            ...commonStyle,
            bounds: { south: sw.lat(), west: sw.lng(), north: ne.lat(), east: ne.lng() }
        });

        bounds.extend(sw);
        bounds.extend(ne);
    }
    // ================= LINE / ROUTE =================
    else if ((g.fenceType === "LINE" || g.route) && g.coordinatesJson) {

        const coords = JSON.parse(g.coordinatesJson);

        activeShape = new google.maps.Polyline({
            strokeColor: color,
            strokeWeight: 3,
            editable: true,
            draggable: true,
            map: map,
            path: coords
        });

        coords.forEach(c => bounds.extend(c));
    }

    activeShape.type = g.fenceType;
    enableEdit(activeShape);
    map.fitBounds(bounds, { padding: 80 });
}

function editGeofence(id) {

    const all = window.state?.routes || [];
    const g = all.find(x => x.id === Number(id));

    if (!g) {
        controller.showToastMsg("Geofence ID not found", "#ff6666");
        return;
    }

    console.log("Editing geofence:", g);
    console.log("Flags:", g.route, g.station, g.hotspot);

    // 🔥 Disable drawing mode while editing
    if (drawingManager) {
        drawingManager.setDrawingMode(null);
    }

    // Remove existing shape
    if (activeShape) activeShape.setMap(null);

    // Draw shape
    viewGeofence(id);

    window.editingGeofenceId = id;

    setCreateTabActive();

    // Ensure editable & draggable
    if (activeShape) {
        activeShape.setEditable(true);
        activeShape.setDraggable(true);
    }

    enableEdit(activeShape);
    syncGeometry();

    // ================= BUTTON MODE =================
    document.getElementById("saveGeofenceBtn").style.display = "none";
    document.getElementById("saveGeofenceChanges").style.display = "inline-block";

    // ================= BASIC INFO =================
      const nameInput = document.getElementById("name");
    if (nameInput) nameInput.value = g.name || "";

    const descInput = document.getElementById("description");
    if (descInput) descInput.value = g.description || "";

    const colorHexInput = document.getElementById("colorHex");
    if (colorHexInput) colorHexInput.value = g.colorHex || "#3B82F6";

    const colorValueEl = document.getElementById("colorValue");
    if (colorValueEl) colorValueEl.innerText = g.colorHex || "#3B82F6";

    // ================= CATEGORY =================
    const category = g.geofenceCategory || "STATION";
    const radio = document.querySelector(`input[name="geofenceCategory"][value="${category}"]`);
    if (radio) radio.checked = true;
    toggleGeofenceCategory();

    // ================= STATION =================
    if (category === "STATION") {

        fenceTypeStation.value = g.fenceType;

        stationType.value = g.stationType || "BUS_STOP";
        dwellTimeSeconds.value = g.dwellTimeSeconds || 60;
        isFinalDestination.checked = g.isFinalDestination || false;

    }

    // ================= ROUTE =================
    if (category === "ROUTE") {

        fenceTypeRoute.value = g.fenceType;
        routeStatus.value = g.routeStatus || "ACTIVE";
        routeBufferWidth.value = g.bufferWidthMeters || 30;

        if (g.stationIds && assignedStations) {
            Array.from(assignedStations.options).forEach(o => {
                o.selected = g.stationIds.includes(Number(o.value));
            });
        }
    }

    // ================= HOTSPOT =================
    if (category === "HOTSPOT") {

        fenceTypeHotspot.value = g.fenceType;
        isAutoAssigned.checked =
            g.isAutoAssigned !== undefined ? g.isAutoAssigned : true;
    }

    // ====================================================
    // 🔥 SHAPE-SPECIFIC EDITING LISTENERS
    // ====================================================

    if (!activeShape) return;

    // ================= CIRCLE =================
    if (g.fenceType === "CIRCLE") {

        circleFields.style.display = "block";

        centerLat.value = g.centerLat || "";
        centerLng.value = g.centerLng || "";
        radiusMeters.value = g.radiusMeters || 50;

        activeShape.setCenter({
            lat: Number(g.centerLat),
            lng: Number(g.centerLng)
        });

        activeShape.setRadius(Number(g.radiusMeters));

        // Live update inputs when dragging circle
        google.maps.event.addListener(activeShape, "center_changed", () => {
            const c = activeShape.getCenter();
            centerLat.value = c.lat();
            centerLng.value = c.lng();
        });

        google.maps.event.addListener(activeShape, "radius_changed", () => {
            radiusMeters.value = activeShape.getRadius();
        });

        // Update circle when typing radius
        radiusMeters.oninput = () => {
            activeShape.setRadius(Number(radiusMeters.value));
        };
    }

    // ================= POLYGON / LINE =================
    if (g.fenceType === "POLYGON" || g.fenceType === "LINE" || g.fenceType === "CORRIDOR") {

        const path = activeShape.getPath();

        // Sync when vertex added/moved/removed
        google.maps.event.addListener(path, "set_at", syncGeometry);
        google.maps.event.addListener(path, "insert_at", syncGeometry);
        google.maps.event.addListener(path, "remove_at", syncGeometry);
    }

    // ================= RECTANGLE =================
    if (g.fenceType === "RECTANGLE") {

        google.maps.event.addListener(activeShape, "bounds_changed", () => {
            syncGeometry();
        });
    }

    // ================= SCROLL =================
    document.getElementById("geofenceForm")
        ?.scrollIntoView({ behavior: "smooth" });
}

function toggleGeofenceCategory() {
    const val = document.querySelector('input[name="geofenceCategory"]:checked').value;
    document.getElementById("regularConfig").style.display = val === "REGULAR" ? "block" : "none";
    document.getElementById("stationConfig").style.display = val === "STATION" ? "block" : "none";
    document.getElementById("routeConfig").style.display = val === "ROUTE" ? "block" : "none";
    document.getElementById("hotspotConfig").style.display = val === "HOTSPOT" ? "block" : "none";
}

function setCreateTabActive() {
  const createTab = document.querySelector('.tab[data-tab="create"]');
  if (!createTab) return;

  // Remove active class from all tabs
  document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"));
  document.querySelectorAll(".tab-content").forEach(c => c.classList.remove("active"));

  // Set Create tab active
  createTab.classList.add("active");

  // Show the corresponding tab content
  document.getElementById('createTab')?.classList.add("active");
}

cancelDrawBtn.onclick = () => {
  // Stop drawing mode
  drawingManager.setDrawingMode(null);

  // Remove any active shape from the map
  if (activeShape) {
    activeShape.setMap(null);
    activeShape = null;
  }

  // Reset form fields
  const form = document.getElementById("geofenceForm");
  if (form) form.reset();

  // Clear coordinate section
  const coordSection = document.getElementById("coordinatesSection");
  if (coordSection) coordSection.style.display = "none";

  const coordContainer = document.getElementById("coordinatesContainer");
  if (coordContainer) coordContainer.innerHTML = "";

  // Reset editing state
  window.editingGeofenceId = null;

  // Reset tabs: optionally set default tab
  document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"));
  document.querySelectorAll(".tab-content").forEach(c => c.classList.remove("active"));
  const defaultTab = document.querySelector('.tab[data-tab="create"]');
  defaultTab?.classList.add("active");
  document.getElementById('createTab')?.classList.add("active");

  // Refresh page after short delay (optional)
  setTimeout(() => window.location.reload(), 400);
};

saveGeofenceChanges.onclick = async () => {

  const namevalue = document.getElementById('name')?.value?.trim();

  if (!window.editingGeofenceId || !activeShape) {
    controller.showToastMsg("Nothing to save", "#ff6666");
    return;
  }

  if (!namevalue) {
    controller.showToastMsg("Please enter a name for the geofence", "#ff6666");
    return;
  }

  const id = window.editingGeofenceId;

  $("#saveGeofenceChanges").html("Updating Please Wait ...");
  $("#saveGeofenceChanges").prop("disabled", true);

  const category = document.querySelector('input[name="geofenceCategory"]:checked')?.value;

  let fenceType,
      isRoute = false,
      isStation = false,
      isHotspot = false,
      routeStatus = "ACTIVE";

  switch (category) {
    case "STATION":
      fenceType = fenceTypeStation?.value;
      isStation = true;
      break;

    case "ROUTE":
      fenceType = fenceTypeRoute?.value;
      isRoute = true;
      routeStatus = document.getElementById('routeStatus')?.value || "ACTIVE";
      break;

    case "HOTSPOT":
      fenceType = fenceTypeHotspot?.value;
      isHotspot = true;
      break;

    default:
      fenceType = fenceTypeRegular?.value;
  }

  let payload = {
    name: namevalue,
    description: document.getElementById('description')?.value || "",
    colorHex: document.getElementById('colorHex')?.value || "#3B82F6",
    fenceType: fenceType,
    isRoute: isRoute,
    isStation: isStation,
    isHotspot: isHotspot,
    routeStatus: routeStatus,
    isFinalDestination: document.getElementById('isFinalDestination')?.checked || false,
    stationType: document.getElementById('stationType')?.value || "BUS_STOP",
    dwellTimeSeconds: parseInt(document.getElementById('dwellTimeSeconds')?.value) || 60,
  };

  // =========================
  // STATION + CIRCLE
  // =========================
  if (isStation && fenceType === "CIRCLE") {

    const center = activeShape.getCenter();
    const radius = activeShape.getRadius?.();

    payload.centerLat = center.lat();
    payload.centerLng = center.lng();
    payload.radiusMeters = parseFloat(radius);

    return updatePayload(id, payload);
  }

  // =========================
  // ROUTE + CORRIDOR
  // =========================
  if (isRoute && fenceType === "CORRIDOR") {

    let coords = [];

    if (activeShape.getPath) {
      activeShape.getPath().forEach(p =>
        coords.push({ lat: p.lat(), lng: p.lng() })
      );
    }

    if (coords.length < 2) {
      controller.showToastMsg("Corridor must have at least 2 points", "#ff6666");
      return;
    }

    payload.bufferWidthMeters =
      parseInt(document.getElementById("bufferWidthMeters")?.value) || 30;

    payload.coordinates = coords;

    return updatePayload(id, payload);
  }

  // =========================
  // ROUTE + POLYGON
  // =========================
  if (isRoute && fenceType === "POLYGON") {

    let coords = [];

    if (activeShape.getPath) {
      activeShape.getPath().forEach(p =>
        coords.push({ lat: p.lat(), lng: p.lng() })
      );
    }

    if (coords.length < 3) {
      controller.showToastMsg("Route polygon must have at least 3 points", "#ff6666");
      return;
    }

    const first = coords[0];
    const last = coords[coords.length - 1];

    if (first.lat === last.lat && first.lng === last.lng) {
      coords.pop();
    }

    payload.coordinates = coords;

    return updatePayload(id, payload);
  }

  // =========================
  // REGULAR / HOTSPOT CIRCLE
  // =========================
  if (fenceType === "CIRCLE") {

    const center = activeShape.getCenter();
    const radius = activeShape.getRadius?.();

    payload.centerLat = center.lat();
    payload.centerLng = center.lng();
    payload.radiusMeters = parseFloat(radius);

    if (isHotspot) {
      payload.isAutoAssigned =
        document.getElementById('isAutoAssigned')?.checked ?? true;
    }

    return updatePayload(id, payload);
  }

  // =========================
  // RECTANGLE
  // =========================
  if (fenceType === "RECTANGLE") {

    const b = activeShape.getBounds();

    payload.minLat = b.getSouthWest().lat();
    payload.minLng = b.getSouthWest().lng();
    payload.maxLat = b.getNorthEast().lat();
    payload.maxLng = b.getNorthEast().lng();

    return updatePayload(id, payload);
  }

  // =========================
  // LINE / POLYGON (GENERIC)
  // =========================
  let coords = [];

  if (activeShape.getPath) {
    activeShape.getPath().forEach(p =>
      coords.push({ lat: p.lat(), lng: p.lng() })
    );
  }

  if (coords.length < 2) {
    controller.showToastMsg("Shape must have enough points", "#ff6666");
    return;
  }

  if (fenceType === "POLYGON" && coords.length >= 3) {
    const first = coords[0];
    const last = coords[coords.length - 1];

    if (first.lat === last.lat && first.lng === last.lng) {
      coords.pop();
    }
  }

  payload.coordinates = coords;

  return updatePayload(id, payload);
};

async function updatePayload(id, payload) {

  console.log("FINAL UPDATE PAYLOAD:", payload);

  try {
    const res = await fetch(API_BASE + 'geofences/' + id, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!res.ok) {
      const err = await res.text();
      throw err;
    }

    controller.showToastMsg("Geofence updated successfully", "#1a5589");
    drawBtn.innerText = "Start Drawing";
    
    // Reload map display after update
    loadAllGeofencesForMap();
    
    setTimeout(() => window.location.reload(), 1000);

  } catch (e) {
    console.error(e);
    controller.showToastMsg("Failed to update geofence", "#ff6666");
  } finally {
    $("#saveGeofenceChanges").html("Save Changes");
    $("#saveGeofenceChanges").prop("disabled", false);
  }
}

// stations logics
document.getElementById('searchStations')
    .addEventListener('input', function () {

        const query = this.value.toLowerCase().trim();
        const allGeofences = window.state?.routes || [];

        const filtered = allGeofences.filter(g =>
            (g.name && g.name.toLowerCase().includes(query)) ||
            (g.description && g.description.toLowerCase().includes(query)) ||
            (g.fenceType && g.fenceType.toLowerCase().includes(query))
        );

        renderGeofencesStations(filtered, 'Routes');
    });

function loadStations() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/stations?size=1000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                window.state = window.state || {};
                window.state.routes = data.content || [];

                console.log('Stations loaded:', window.state.routes);
                renderGeofencesStations(window.state.routes, 'Stations');
            } else {
                console.error('Error loading stations:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

function renderGeofencesStations(geofences, typeLabel) {
    const container = document.getElementById('stationsList');
    if (!container) return;

    if (!geofences || geofences.length === 0) {
        container.innerHTML = `
            <div class="no-notifications">
                No geofences available
            </div>
        `;
        return;
    }

    let html = `
        <div class="notifications-wrapper" style="
            display:flex;
            flex-direction:column;
            gap:15px;
        ">
    `;

    geofences.forEach(g => {

        html += `
        <div class="notification-card" data-id="${g.id}">
            
            <div class="notification-header">
                <span class="notification-title">${g.name}</span>
                <span class="notification-time">
                    ${new Date(g.createdAt).toLocaleDateString()}
                </span>
            </div>

            <div class="notification-body">
                <p>${g.description || g.name}</p>
            </div>

            <div class="notification-footer">
                <span class="priority" style="
                    background:${g.colorHex || '#3B82F6'};
                    color:#fff;
                    padding:3px 8px;
                    border-radius:4px;
                    font-size:12px;">
                    ${g.fenceType || 'N/A'}
                </span>

                <span class="type">${typeLabel || 'Geofence'}</span>

              <div class="notification-actions icon-actions">
                    <i class="fa-solid fa-eye action-icon view"
                    title="View"
                    onclick="viewGeofence(${g.id})"></i>

                    <i class="fa-solid fa-pen action-icon edit"
                    title="Edit"
                    onclick="editGeofence(${g.id})"></i>

                    <i class="fa-solid fa-trash action-icon delete"
                    title="Delete"
                    onclick="deleteGeofence(${g.id}, event)"></i>
                </div>

            </div>

        </div>
        `;
    });

    html += `</div>`;
    container.innerHTML = html;
}

// load logics
document.getElementById('searchHotspots')
    .addEventListener('input', function () {

        const query = this.value.toLowerCase().trim();
        const allGeofences = window.state?.routes || [];

        const filtered = allGeofences.filter(g =>
            (g.name && g.name.toLowerCase().includes(query)) ||
            (g.description && g.description.toLowerCase().includes(query)) ||
            (g.fenceType && g.fenceType.toLowerCase().includes(query))
        );

        renderGeofencesHotspots(filtered, 'Hotspots');
    });

function loadHotspots() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/hotspots?size=1000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                window.state = window.state || {};
                window.state.routes = data.content || [];

                console.log('Hotspots loaded:', window.state.routes);
                renderGeofencesHotspots(window.state.routes, 'Hotspots');
            } else {
                console.error('Error loading hotspots:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

function renderGeofencesHotspots(geofences, typeLabel) {
    const container = document.getElementById('hotspotsList');
    if (!container) return;

    if (!geofences || geofences.length === 0) {
        container.innerHTML = `
            <div class="no-notifications">
                No geofences available
            </div>
        `;
        return;
    }

    let html = `
        <div class="notifications-wrapper" style="
            display:flex;
            flex-direction:column;
            gap:15px;
        ">
    `;

    geofences.forEach(g => {

        html += `
        <div class="notification-card" data-id="${g.id}">
            
            <div class="notification-header">
                <span class="notification-title">${g.name}</span>
                <span class="notification-time">
                    ${new Date(g.createdAt).toLocaleDateString()}
                </span>
            </div>

            <div class="notification-body">
                <p>${g.description || g.name}</p>
            </div>

            <div class="notification-footer">
                <span class="priority" style="
                    background:${g.colorHex || '#3B82F6'};
                    color:#fff;
                    padding:3px 8px;
                    border-radius:4px;
                    font-size:12px;">
                    ${g.fenceType || 'N/A'}
                </span>

                <span class="type">${typeLabel || 'Geofence'}</span>

              <div class="notification-actions icon-actions">
                    <i class="fa-solid fa-eye action-icon view"
                    title="View"
                    onclick="viewGeofence(${g.id})"></i>

                    <i class="fa-solid fa-pen action-icon edit"
                    title="Edit"
                    onclick="editGeofence(${g.id})"></i>

                    <i class="fa-solid fa-trash action-icon delete"
                    title="Delete"
                    onclick="deleteGeofence(${g.id})"></i>
                </div>

            </div>

        </div>
        `;
    });

    html += `</div>`;
    container.innerHTML = html;
}

loadDevices();

function loadDevices() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'devices?size=1000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {

                const data = JSON.parse(xhr.responseText);
                var contentdata = data.content || [];

                console.log('Devices loaded:', contentdata);

                let options = "";
                options += '<option selected value="" >-Select Device-</option>';

                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        options += `<option value="${contentdata[i].deviceId}">
                                        ${contentdata[i].serialNo}  ${contentdata[i].name ? '- ' + contentdata[i].name : ''}
                                    </option>`;
                    }
                }

                $("#selectDevice").html(options);
            } else {
                console.error('Error loading devices:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

loadAllRoutes();

function loadAllRoutes() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/routes?size=5000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {

                const data = JSON.parse(xhr.responseText);
                var contentdata = data.content || [];

                console.log('Routes loaded for dropdown:', contentdata);

                let option = "";
                option += '<option selected value="" >-Select Route-</option>';

                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        option += `<option value="${contentdata[i].id}">
                                        ${contentdata[i].name}
                                    </option>`;
                    }
                }

                $("#selectRoute").html(option);
            } else {
                console.error('Error loading routes for dropdown:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

loadParentRoutes();

function loadParentRoutes() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/routes?size=500', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {

                const data = JSON.parse(xhr.responseText);
                var contentdata = data.content || [];

                console.log('Parent routes loaded:', contentdata);

                let option = "";
                option += '<option selected value="" >-Select Parent Route-</option>';

                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        option += `<option value="${contentdata[i].id}">
                                        ${contentdata[i].name}
                                    </option>`;
                    }
                }

                $("#parentRoute").html(option);
                $("#selectPrRoute").html(option);

            } else {
                console.error('Error loading parent routes:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

loadMystations();

function loadMystations() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/stations?size=1000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {

                const data = JSON.parse(xhr.responseText);
                var contentdata = data.content || [];

                console.log('Stations loaded for dropdown:', contentdata);

                let option = "";
                option += '<option selected value="" >-Select Station-</option>';

                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        option += `<option value="${contentdata[i].id}">
                                        ${contentdata[i].name}
                                    </option>`;
                    }
                }

                $("#selectStation").html(option);

            } else {
                console.error('Error loading stations for dropdown:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

document.getElementById('searchAllGeofences')
    .addEventListener('input', function () {
        const query = this.value.toLowerCase().trim();
        const allGeofences = window.state?.routes || [];
        const filtered = allGeofences.filter(g =>
            (g.name && g.name.toLowerCase().includes(query)) ||
            (g.description && g.description.toLowerCase().includes(query)) ||
            (g.fenceType && g.fenceType.toLowerCase().includes(query))
        );

        renderGeofencesloadAllGeofences(filtered, 'All Geofences');
});

loadAllGeofences();

function loadAllGeofences() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences?size=10000', true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                window.state = window.state || {};
                window.state.routes = data.content || [];

                console.log('All geofences loaded:', window.state.routes.length);
                renderGeofencesloadAllGeofences(window.state.routes, 'All Geofences');
            } else {
                console.error('Error loading all geofences:', xhr.responseText);
            }
        }
    };
    xhr.send();
}

function renderGeofencesloadAllGeofences(geofences, typeLabel) {
    const container = document.getElementById('allGeofencesList');
    if (!container) return;

    if (!geofences || geofences.length === 0) {
        container.innerHTML = `
            <div class="no-notifications">
                No geofences available
            </div>
        `;
        return;
    }

    let html = `
        <div class="notifications-wrapper" style="
            display:flex;
            flex-direction:column;
            gap:15px;
        ">
    `;

    geofences.forEach(g => {

        html += `
        <div class="notification-card" data-id="${g.id}">
            
            <div class="notification-header">
                <span class="notification-title">${g.name}</span>
                <span class="notification-time">
                    ${new Date(g.createdAt).toLocaleDateString()}
                </span>
            </div>

            <div class="notification-body">
                <p>${g.description || g.name}</p>
            </div>

            <div class="notification-footer">
                <span class="priority" style="
                    background:${g.colorHex || '#3B82F6'};
                    color:#fff;
                    padding:3px 8px;
                    border-radius:4px;
                    font-size:12px;">
                    ${g.fenceType || 'N/A'}
                </span>

                <span class="type">${typeLabel || 'Geofence'}</span>

              <div class="notification-actions icon-actions">
                    <i class="fa-solid fa-eye action-icon view"
                    title="View"
                    onclick="viewGeofence(${g.id})"></i>

                    <i class="fa-solid fa-pen action-icon edit"
                    title="Edit"
                    onclick="editGeofence(${g.id})"></i>

                    <i class="fa-solid fa-trash action-icon delete"
                    title="Delete"
                    onclick="deleteGeofence(${g.id})"></i>
                </div>

            </div>

        </div>
        `;
    });

    html += `</div>`;
    container.innerHTML = html;
}

// assign device to route
assignDeviceToRoute.onclick = async () => {
                   
    var deviceId = $("#selectDevice").val();
    var routeId = $("#selectRoute").val();

    if (!deviceId || !routeId) {
         controller.showToastMsg("Please select both device and route", "#ff6666");
        return;
    }

    try {
        const payload = {
            deviceId: parseInt(deviceId),
            routeId: parseInt(routeId)
        };
                
        const response = await fetch(API_BASE + 'geofences/routes/assign-device', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload)
        });
                
        if (response.ok) {
            controller.showToastMsg("Device successfully assigned to route! All stations on this route are now assigned to the device.", "#1a5589");
        } else {
            const data = await response.json();
            const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
            alert(`Error: ${errorMsg}`);
        }
    } catch (error) {
        console.error('Fetch error:', error);
    }
};

assignStationToRoutes.onclick = async () => {

    $("#assignStationToRoutes").html("Assigning... Please Wait!");
    $("#assignStationToRoutes").prop("disabled", true);
    $("#assignStationToRoutes").attr("disabled", true);

    const stationId = $("#selectStation").val();
    const routeId = $("#selectPrRoute").val();

    if (!stationId || !routeId) {
        controller.showToastMsg("Please select both station and route", "#ff6666");
        return;
    }

    try {
        const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/routes/${routeId}/stations/${stationId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        if (response.ok) {
            controller.showToastMsg(
                "Station successfully assigned to route!",
                "#1a5589"
            );

              setTimeout(function () {
                  $("#assignStationToRoutes").html("Assign Station to Route");
                  $("#assignStationToRoutes").prop("disabled", false);
                  $("#assignStationToRoutes").attr("disabled", false);
            }, 1000);
        } else {
            const data = await response.json();
            const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
            controller.showToastMsg(`Error: ${errorMsg}`, "#ff6666");

              setTimeout(function () {
                  $("#assignStationToRoutes").html("Assign Station to Route");
                  $("#assignStationToRoutes").prop("disabled", false);
                  $("#assignStationToRoutes").attr("disabled", false);
            }, 1000);
        }
    } catch (error) {
          setTimeout(function () {
              $("#assignStationToRoutes").html("Assign Station to Route");
              $("#assignStationToRoutes").prop("disabled", false);
              $("#assignStationToRoutes").attr("disabled", false);
          }, 1000);
        controller.showToastMsg(`Error: ${error.message}`, "#ff6666");
        console.error("Fetch error:", error);
    }
};