


let map, drawingManager, activeShape;

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

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

// --------------------
// 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.addListener(s, "radius_changed", () => {
      const radiusInput = document.getElementById("radiusMeters");
      if (radiusInput) radiusInput.value = s.getRadius().toFixed(2);
    });
  }

  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 alert("Select geofence type first");

  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 alert("Select geometric type first");

  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) {
    // alert("Please enter a name for the geofence");
        controller.showToastMsg("Please enter a name for the geofence", "#ff6666");

    return;
  }

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

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

  switch (category) {
    case "REGULAR": fenceType = fenceTypeRegular?.value; break;
    case "STATION": fenceType = fenceTypeStation?.value; break;
    case "ROUTE":
      fenceType = fenceTypeRoute?.value;
      isRoute = true;
      routeStatus = document.getElementById('routeStatus')?.value || "ACTIVE";
      break;
    case "HOTSPOT": fenceType = fenceTypeHotspot?.value; break;
  }

  // Base payload
  let payload = {
    name: namevalue,
    description: document.getElementById('description')?.value || "",
    colorHex: document.getElementById('colorHex')?.value || "#3B82F6",
    fenceType: fenceType,
    isRoute: isRoute,
    routeStatus: routeStatus
  };

  // REGULAR CIRCLE
  if (category === "REGULAR" && 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;
  }

  // Other shapes
  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() }
      ];
    }
    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;
    }


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

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


// Initial call
updateGeofenceFields();




// Load tabs views

loadRoutes();
loadStations();
loadHotspots();




// 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) { // DONE
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                // Ensure global state
                window.state = window.state || {};
                window.state.routes = data.content || []; // Assuming paged response

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


// // Example button handlers
// function viewGeofence(id) { console.log('View', id); }
// function editGeofence(id) { console.log('Edit', id); }
function deleteGeofence(id) { console.log('Delete', id); }

// 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) {

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

        bounds.extend(activeShape.getCenter());

        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 all = window.state?.allGeofences || [];
    const g = all.find(x => x.id === id);
    if (!g) return alert("Geofence not found");

    // Draw shape on map first
    viewGeofence(id);
    window.editingGeofenceId = id;   // 👈 THIS is critical

    // ================= FORM MODE =================
    document.getElementById("mode").value = "edit";
    document.getElementById("geofenceId").value = g.id;

    // Change button text
    document.getElementById("saveGeofenceBtn").style.display = "none";

    // ================= BASIC INFO =================
    document.getElementById("name").value = g.name || "";
    document.getElementById("description").value = g.description || "";
    document.getElementById("colorHex").value = g.colorHex || "#3B82F6";
    document.getElementById("colorValue").innerText = g.colorHex || "#3B82F6";

    // ================= CATEGORY =================
    const category = g.geofenceCategory || "REGULAR";
    document.querySelector(`input[name="geofenceCategory"][value="${category}"]`).checked = true;
    toggleGeofenceCategory(); // your existing function to show/hide sections

    // ================= GEOMETRIC TYPE =================
    if (category === "REGULAR") {
        document.getElementById("fenceTypeRegular").value = g.fenceType;
    }
    if (category === "STATION") {
        document.getElementById("fenceTypeStation").value = g.fenceType;
        document.getElementById("stationType").value = g.stationType || "";
        document.getElementById("dwellTimeSeconds").value = g.dwellTimeSeconds || 60;
        document.getElementById("parentRoute").value = g.parentRouteId || "";
    }
    if (category === "ROUTE") {
        document.getElementById("fenceTypeRoute").value = g.fenceType;
        document.getElementById("routeStatus").value = g.routeStatus || "ACTIVE";
        document.getElementById("routeBufferWidth").value = g.bufferWidthMeters || 30;

        if (g.stationIds) {
            const select = document.getElementById("assignedStations");
            [...select.options].forEach(o => o.selected = g.stationIds.includes(Number(o.value)));
        }
    }
    if (category === "HOTSPOT") {
        document.getElementById("fenceTypeHotspot").value = g.fenceType;
        document.getElementById("isAutoAssigned").checked = g.isAutoAssigned ?? true;
    }

    // ================= SHAPE DATA =================
    if (g.fenceType === "CIRCLE") {
        document.getElementById("circleFields").style.display = "block";
        document.getElementById("radiusMeters").value = g.radiusMeters || "";
        document.getElementById("centerLat").value = g.centerLat || "";
        document.getElementById("centerLng").value = g.centerLng || "";
    }

    if (g.coordinatesJson) {
        document.getElementById("coordinatesSection").style.display = "block";
    }

    // ================= SCROLL TO FORM =================
    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 saveGeofenceChanges() {

    if (!window.editingGeofenceId || !activeShape) {
        return alert("Nothing to save");
    }

    const id = window.editingGeofenceId;

    const payload = {
        name: document.getElementById("geofenceName").value,
        description: document.getElementById("geofenceDesc").value,
        colorHex: document.getElementById("geofenceColor").value,
        fenceType: activeShape.type
    };

    // ================= SHAPE DATA =================
    if (activeShape.type === "CIRCLE") {
        const c = activeShape.getCenter();
        payload.centerLat = c.lat();
        payload.centerLng = c.lng();
        payload.radiusMeters = activeShape.getRadius();
    }

    if (activeShape.type === "POLYGON") {
        payload.coordinatesJson = JSON.stringify(
            activeShape.getPath().getArray().map(p => ({ lat: p.lat(), lng: p.lng() }))
        );
    }

    if (activeShape.type === "RECTANGLE") {
        const b = activeShape.getBounds();
        payload.coordinatesJson = JSON.stringify([
            { lat: b.getSouthWest().lat(), lng: b.getSouthWest().lng() },
            { lat: b.getNorthEast().lat(), lng: b.getSouthWest().lng() },
            { lat: b.getNorthEast().lat(), lng: b.getNorthEast().lng() },
            { lat: b.getSouthWest().lat(), lng: b.getNorthEast().lng() }
        ]);
    }

    if (activeShape.type === "LINE") {
        payload.coordinatesJson = JSON.stringify(
            activeShape.getPath().getArray().map(p => ({ lat: p.lat(), lng: p.lng() }))
        );
    }

    // ================= API CALL =================
    fetch(serverURL + "geofences/" + id, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + userObj.accessToken
        },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(() => {
        alert("Geofence updated");
        window.editingGeofenceId = null;
        loadAllGeofences(); // reload list
    })
    .catch(() => alert("Failed to update"));
}






// 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) { // DONE
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                // Ensure global state
                window.state = window.state || {};
                window.state.routes = data.content || []; // Assuming paged response

                console.log('Routes loaded:', window.state.routes);

                renderGeofencesStations(window.state.routes, 'Routes');
            } else {
                console.error('Error loading routes:', 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})"></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))
        );

        renderGeofencesStations(filtered, 'Routes');
    });
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) { // DONE
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                // Ensure global state
                window.state = window.state || {};
                window.state.routes = data.content || []; // Assuming paged response

                console.log('Routes loaded:', window.state.routes);

                renderGeofencesHotspots(window.state.routes, 'Routes');
            } else {
                console.error('Error loading routes:', 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 || []; // Assuming paged response

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

                // update DOM once
                $("#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 || []; // Assuming paged response

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

                let option = "";

                option += '<option selected value="" >-Select Device-</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>`;
                    }
                }

                // update DOM once
                $("#selectRoute").html(option);

            } else {
                console.error('Error loading devices:', 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, 'Routes');
});


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) { // DONE
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                // Ensure global state
                window.state = window.state || {};
                window.state.routes = data.content || []; // Assuming paged response

                console.log('Routes loaded:', window.state.routes);

                renderGeofencesloadAllGeofences(window.state.routes, 'Routes');
            } else {
                console.error('Error loading routes:', 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");

                    // alert(`Device successfully assigned to route! All stations on this route are now assigned to the device.`);
                } else {
                    const data = await response.json();
                    const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
                    alert(`Error: ${errorMsg}`);
                }
            } catch (error) {
                // showMessage(`Error: ${error.message}`, 'error');
                // console.error('Fetch error:', error);
            }
};

