     // ==================== ENHANCED GEO UPLOAD & MAP EDIT ====================
        
        // File upload elements
        const fileInput = document.getElementById('fileUpload');
        const parseFileBtn = document.getElementById('parseFileBtn');
        const fileParseStatus = document.getElementById('fileParseStatus');

        // Attach file handler
        parseFileBtn.addEventListener('click', handleFileUpload);

        async function handleFileUpload() {
            const file = fileInput.files[0];
            if (!file) {
                showMessage('Please select a file', 'error');
                return;
            }

            fileParseStatus.textContent = 'Processing file...';
            fileParseStatus.style.color = '#856404';
            fileParseStatus.style.background = '#fff3cd';

            try {
                const extension = file.name.split('.').pop().toLowerCase();
                let geojson;

                if (extension === 'kmz') {
                    // Unzip KMZ
                    const zip = new JSZip();
                    const zipContent = await zip.loadAsync(file);
                    // Find the first .kml file (usually doc.kml)
                    const kmlFile = Object.values(zipContent.files).find(f => f.name.endsWith('.kml'));
                    if (!kmlFile) throw new Error('No KML file found inside KMZ');
                    const kmlText = await kmlFile.async('string');
                    const parser = new DOMParser();
                    const kmlDoc = parser.parseFromString(kmlText, 'text/xml');
                    geojson = toGeoJSON.kml(kmlDoc);
                } else {
                    // GPX or KML: read as text
                    const text = await file.text();
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(text, 'text/xml');
                    if (extension === 'gpx') {
                        geojson = toGeoJSON.gpx(doc);
                    } else {
                        geojson = toGeoJSON.kml(doc);
                    }
                }

                // Extract coordinates from GeoJSON and determine geometry type
                const { coordinates, geometryType } = extractGeometryFromGeoJSON(geojson);
                if (coordinates.length === 0) {
                    throw new Error('No coordinates found in file');
                }

                // Set appropriate geofence category and fence type based on geometry
                setCategoryAndFenceTypeFromGeometry(geometryType);

                // Draw on map as editable layer
                drawUploadedGeometry(coordinates, geometryType);

                fileParseStatus.textContent = `Loaded ${coordinates.length} points as ${geometryType}. You can now edit on map using the edit button (top-right of map).`;
                fileParseStatus.style.color = '#155724';
                fileParseStatus.style.background = '#d5edda';
            } catch (error) {
                console.error('Error parsing file:', error);
                fileParseStatus.textContent = 'Error: ' + error.message;
                fileParseStatus.style.color = '#721c24';
                fileParseStatus.style.background = '#f8d7da';
            }
        }

        function extractGeometryFromGeoJSON(geojson) {
            let coordinates = [];
            let geometryType = 'LineString'; // default

            const extract = (geom) => {
                if (!geom) return;
                geometryType = geom.type;
                switch (geom.type) {
                    case 'Point':
                        coordinates.push({ lat: geom.coordinates[1], lng: geom.coordinates[0] });
                        break;
                    case 'LineString':
                    case 'MultiPoint':
                        geom.coordinates.forEach(coord => {
                            coordinates.push({ lat: coord[1], lng: coord[0] });
                        });
                        break;
                    case 'Polygon':
                        // Take outer ring
                        geom.coordinates[0].forEach(coord => {
                            coordinates.push({ lat: coord[1], lng: coord[0] });
                        });
                        break;
                    case 'MultiLineString':
                        geom.coordinates.forEach(line => {
                            line.forEach(coord => {
                                coordinates.push({ lat: coord[1], lng: coord[0] });
                            });
                        });
                        break;
                    case 'MultiPolygon':
                        geom.coordinates.forEach(poly => {
                            poly[0].forEach(coord => {
                                coordinates.push({ lat: coord[1], lng: coord[0] });
                            });
                        });
                        break;
                    default:
                        // ignore
                        break;
                }
            };

            if (geojson.type === 'FeatureCollection') {
                geojson.features.forEach(feature => extract(feature.geometry));
            } else if (geojson.type === 'Feature') {
                extract(geojson.geometry);
            } else if (geojson.type === 'GeometryCollection') {
                geojson.geometries.forEach(geom => extract(geom));
            } else {
                extract(geojson);
            }

            return { coordinates, geometryType };
        }

        function setCategoryAndFenceTypeFromGeometry(geometryType) {
            // Map GeoJSON types to our fence types and categories
            let fenceType = 'LINE';
            let category = 'ROUTE'; // default for lines

            if (geometryType === 'Point') {
                fenceType = 'CIRCLE';
                category = 'STATION';
            } else if (geometryType === 'Polygon' || geometryType === 'MultiPolygon') {
                fenceType = 'POLYGON';
                category = 'STATION'; // treat polygons as stations (zones)
            } else if (geometryType === 'LineString' || geometryType === 'MultiLineString') {
                fenceType = 'LINE';
                category = 'ROUTE';
            }

            // Set radio button
            document.querySelector(`input[name="geofenceCategory"][value="${category}"]`).checked = true;
            handleGeofenceCategoryChange({ target: { value: category } });

            // Set fence type in the appropriate select
            const fenceSelect = document.getElementById(category === 'STATION' ? 'fenceTypeStation' : 
                                                        (category === 'ROUTE' ? 'fenceTypeRoute' : 'fenceTypeHotspot'));
            if (fenceSelect) {
                fenceSelect.value = fenceType;
                fenceSelect.dispatchEvent(new Event('change'));
            }
        }

        function drawUploadedGeometry(coordinates, geometryType) {
            // Clear any existing drawings
            drawnItems.clearLayers();

            if (coordinates.length === 0) return;

            const latlngs = coordinates.map(c => [c.lat, c.lng]);

            let layer;
            if (geometryType === 'Point') {
                // For a single point, create a small circle (or marker)
                layer = L.circle(latlngs[0], { radius: 50, color: '#3B82F6', fillOpacity: 0.3 });
            } else if (geometryType === 'Polygon' || geometryType === 'MultiPolygon') {
                layer = L.polygon(latlngs, { color: '#3B82F6', fillOpacity: 0.3 });
            } else {
                // LineString or MultiLineString
                layer = L.polyline(latlngs, { color: '#3B82F6', weight: 3 });
            }

            drawnItems.addLayer(layer);

            // Zoom to bounds
            map.fitBounds(layer.getBounds().pad(0.1));

            // Update hidden fields based on geometry
            updateGeometryFromDrawnLayer();

            // Enable submit button
            elements.submitBtn.disabled = false;
        }

        // Ensure updateGeometryFromDrawnLayer exists (should be defined later)
        if (typeof updateGeometryFromDrawnLayer !== 'function') {
            function updateGeometryFromDrawnLayer() {
                const layers = drawnItems.getLayers();
                if (layers.length === 0) return;
                // Basic implementation: just log for now
                console.log('Geometry updated from drawn layer');
            }
        }

        // ==================== EXISTING CODE (continued) ====================
        // Enhanced State management
        const state = {
            geofences: [],
            routes: [],
            stations: [],
            hotspots: [],
            devices: [],
            selectedGeofence: null,
            mapLayers: new Map(),
            editMode: false
        };
        
        // Initialize map centered on Nairobi
        const map = L.map('map').setView([11.5721, 43.1456], 10);
        
        // Add OpenStreetMap tiles
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        // Variables for drawing
        let drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
        let drawControl = null;
        let currentDrawing = false;
        
        // DOM Elements
        const elements = {
            form: document.getElementById('geofenceForm'),
            geofenceId: document.getElementById('geofenceId'),
            mode: document.getElementById('mode'),
            fenceTypeStation: document.getElementById('fenceTypeStation'),
            fenceTypeRoute: document.getElementById('fenceTypeRoute'),
            fenceTypeHotspot: document.getElementById('fenceTypeHotspot'),
            drawBtn: document.getElementById('drawBtn'),
            cancelDrawBtn: document.getElementById('cancelDrawBtn'),
            submitBtn: document.getElementById('submitBtn'),
            cancelEditBtn: document.getElementById('cancelEditBtn'),
            responseMessage: document.getElementById('responseMessage'),
            circleFields: document.getElementById('circleFields'),
            coordinatesSection: document.getElementById('coordinatesSection'),
            coordinatesContainer: document.getElementById('coordinatesContainer'),
            stationConfig: document.getElementById('stationConfig'),
            routeConfig: document.getElementById('routeConfig'),
            hotspotConfig: document.getElementById('hotspotConfig'),
            colorHex: document.getElementById('colorHex'),
            colorValue: document.getElementById('colorValue'),
            radiusMeters: document.getElementById('radiusMeters'),
            routeBufferWidth: document.getElementById('routeBufferWidth'),
            parentRoute: document.getElementById('parentRoute'),
            assignedStations: document.getElementById('assignedStations'),
            selectDevice: document.getElementById('selectDevice'),
            selectRoute: document.getElementById('selectRoute'),
            routeStations: document.getElementById('routeStations'),
            assignDeviceBtn: document.getElementById('assignDeviceBtn'),
            isAutoAssigned: document.getElementById('isAutoAssigned'),
            searchAllGeofences: document.getElementById('searchAllGeofences'),
            searchRoutes: document.getElementById('searchRoutes'),
            searchStations: document.getElementById('searchStations'),
            searchHotspots: document.getElementById('searchHotspots'),
            showRoutes: document.getElementById('showRoutes'),
            showStations: document.getElementById('showStations'),
            showHotspots: document.getElementById('showHotspots'),
            showAllBtn: document.getElementById('showAllBtn'),
            showRoutesBtn: document.getElementById('showRoutesBtn'),
            showStationsBtn: document.getElementById('showStationsBtn'),
            showHotspotsBtn: document.getElementById('showHotspotsBtn'),
            clearMapBtn: document.getElementById('clearMapBtn'),
            zoomToBoundsBtn: document.getElementById('zoomToBoundsBtn')
        };
        
        // Initialize event listeners
        function initEventListeners() {
            // Tab switching
            document.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', handleTabSwitch);
            });
            
            // Geofence type radio buttons
            document.querySelectorAll('input[name="geofenceCategory"]').forEach(radio => {
                radio.addEventListener('change', handleGeofenceCategoryChange);
            });
            
            // Fence type change events
            elements.fenceTypeStation.addEventListener('change', handleStationFenceTypeChange);
            elements.fenceTypeRoute.addEventListener('change', handleRouteFenceTypeChange);
            elements.fenceTypeHotspot.addEventListener('change', handleHotspotFenceTypeChange);
            
            // Color picker
            elements.colorHex.addEventListener('input', updateColorValue);
            
            // Draw buttons
            elements.drawBtn.addEventListener('click', startDrawing);
            elements.cancelDrawBtn.addEventListener('click', cancelDrawing);
            
            // Form submission
            elements.form.addEventListener('submit', handleFormSubmit);
            
            // Device assignment
            elements.selectRoute.addEventListener('change', loadRouteStations);
            elements.assignDeviceBtn.addEventListener('click', assignDeviceToRoute);
            
            // Map drawing events
            map.on(L.Draw.Event.CREATED, handleDrawCreated);
            map.on(L.Draw.Event.DRAWSTART, () => currentDrawing = true);
            map.on(L.Draw.Event.DRAWSTOP, () => currentDrawing = false);
            
            // Map click events
            map.on('click', handleMapClick);
            
            // Search events
            elements.searchAllGeofences.addEventListener('input', debounce(filterAllGeofences, 300));
            elements.searchRoutes.addEventListener('input', debounce(filterRoutes, 300));
            elements.searchStations.addEventListener('input', debounce(filterStations, 300));
            elements.searchHotspots.addEventListener('input', debounce(filterHotspots, 300));
            
            // Filter events
            elements.showRoutes.addEventListener('change', filterAllGeofences);
            elements.showStations.addEventListener('change', filterAllGeofences);
            elements.showHotspots.addEventListener('change', filterAllGeofences);
            
            // Map control events
            elements.showAllBtn.addEventListener('click', showAllOnMap);
            elements.showRoutesBtn.addEventListener('click', showRoutesOnMap);
            elements.showStationsBtn.addEventListener('click', showStationsOnMap);
            elements.showHotspotsBtn.addEventListener('click', showHotspotsOnMap);
            elements.clearMapBtn.addEventListener('click', clearMap);
            elements.zoomToBoundsBtn.addEventListener('click', zoomToBounds);
            
            // Cancel edit
            elements.cancelEditBtn.addEventListener('click', cancelEdit);
        }
        
        // Search and Filter Functions
        function filterAllGeofences() {
            const searchTerm = elements.searchAllGeofences.value.toLowerCase();
            const showRoutes = elements.showRoutes.checked;
            const showStations = elements.showStations.checked;
            const showHotspots = elements.showHotspots.checked;
            
            const filtered = state.geofences.filter(geofence => {
                // Filter by search term
                const matchesSearch = searchTerm === '' || 
                    geofence.name.toLowerCase().includes(searchTerm) ||
                    (geofence.description && geofence.description.toLowerCase().includes(searchTerm));
                
                // Filter by type
                let matchesType = false;
                if (geofence.route && showRoutes) matchesType = true;
                if (geofence.station && showStations) matchesType = true;
                if (geofence.hotspot && showHotspots) matchesType = true;
                
                return matchesSearch && matchesType;
            });
            
            renderGeofenceList('allGeofencesList', filtered);
        }
        
        function filterRoutes() {
            const searchTerm = elements.searchRoutes.value.toLowerCase();
            const filtered = state.routes.filter(route => 
                searchTerm === '' || 
                route.name.toLowerCase().includes(searchTerm) ||
                (route.description && route.description.toLowerCase().includes(searchTerm))
            );
            renderGeofenceList('routesList', filtered, true);
        }
        
        function filterStations() {
            const searchTerm = elements.searchStations.value.toLowerCase();
            const filtered = state.stations.filter(station => 
                searchTerm === '' || 
                station.name.toLowerCase().includes(searchTerm) ||
                (station.description && station.description.toLowerCase().includes(searchTerm))
            );
            renderGeofenceList('stationsList', filtered, true);
        }
        
        function filterHotspots() {
            const searchTerm = elements.searchHotspots.value.toLowerCase();
            const filtered = state.hotspots.filter(hotspot => 
                searchTerm === '' || 
                hotspot.name.toLowerCase().includes(searchTerm) ||
                (hotspot.description && hotspot.description.toLowerCase().includes(searchTerm))
            );
            renderGeofenceList('hotspotsList', filtered, true);
        }
        
        // Map Control Functions
        function showAllOnMap() {
            clearMap();
            renderGeofencesOnMap();
        }
        
        function showRoutesOnMap() {
            clearMap();
            state.routes.forEach(geofence => {
                createGeofenceLayer(geofence);
            });
        }
        
        function showStationsOnMap() {
            clearMap();
            state.stations.forEach(geofence => {
                createGeofenceLayer(geofence);
            });
        }
        
        function showHotspotsOnMap() {
            clearMap();
            state.hotspots.forEach(geofence => {
                createGeofenceLayer(geofence);
            });
        }
        
        function clearMap() {
            state.mapLayers.forEach(layer => map.removeLayer(layer));
            state.mapLayers.clear();
            drawnItems.clearLayers();
        }
        
        function zoomToBounds() {
            const layers = Array.from(state.mapLayers.values());
            if (layers.length > 0) {
                const group = L.featureGroup(layers);
                map.fitBounds(group.getBounds().pad(0.1));
            }
        }
        
        // Modal Functions
        function openModal(modalId) {
            document.getElementById(modalId).style.display = 'flex';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        // Enhanced Tab Switching
        function handleTabSwitch(e) {
            const tab = e.target.closest('.tab');
            const tabName = tab.dataset.tab;
            
            // Update active tab
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            
            // Show selected tab content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            document.getElementById(`${tabName}Tab`).style.display = 'block';
            
            // Load data for tab
            switch(tabName) {
                case 'routes':
                    loadRoutes();
                    break;
                case 'stations':
                    loadStations();
                    break;
                case 'hotspots':
                    loadHotspots();
                    break;
                case 'assign':
                    loadDevices();
                    loadRoutesForAssignment();
                    break;
            }
        }
        
        // Enhanced Form Handling
        function handleGeofenceCategoryChange(e) {
            const category = e.target.value;
            
            // Hide all config sections
            elements.stationConfig.style.display = 'none';
            elements.routeConfig.style.display = 'none';
            elements.hotspotConfig.style.display = 'none';
            
            // Remove required attribute from all fenceType selects
            elements.fenceTypeStation.removeAttribute('required');
            elements.fenceTypeRoute.removeAttribute('required');
            elements.fenceTypeHotspot.removeAttribute('required');
            
            // Show appropriate config section and set required
            switch(category) {
                case 'STATION':
                    elements.stationConfig.style.display = 'block';
                    elements.fenceTypeStation.setAttribute('required', 'required');
                    loadRoutesForParentSelection();
                    handleStationFenceTypeChange();
                    break;
                case 'ROUTE':
                    elements.routeConfig.style.display = 'block';
                    elements.fenceTypeRoute.setAttribute('required', 'required');
                    loadStationsForRouteAssignment();
                    handleRouteFenceTypeChange();
                    break;
                case 'HOTSPOT':
                    elements.hotspotConfig.style.display = 'block';
                    elements.fenceTypeHotspot.setAttribute('required', 'required');
                    handleHotspotFenceTypeChange();
                    break;
            }
            
            // Clear any existing drawings
            cancelDrawing();
        }
        
        function updateColorValue() {
            elements.colorValue.textContent = elements.colorHex.value;
        }
        
        // Enhanced Drawing Functions
        function startDrawing() {
            const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
            let fenceType;
            
            // Get the appropriate fence type based on category
            switch(category) {
                case 'STATION':
                    fenceType = elements.fenceTypeStation.value;
                    break;
                case 'ROUTE':
                    fenceType = elements.fenceTypeRoute.value;
                    break;
                case 'HOTSPOT':
                    fenceType = elements.fenceTypeHotspot.value;
                    break;
                default:
                    fenceType = '';
            }
            
            if (!fenceType) {
                showMessage('Please select a geometric type first', 'error');
                return;
            }
            
            // Remove existing draw control
            if (drawControl) {
                map.removeControl(drawControl);
            }
            
            // Clear any previous drawings
            drawnItems.clearLayers();
            
            // Configure draw options
            const drawOptions = {
                position: 'topright',
                draw: {
                    polygon: fenceType === 'POLYGON',
                    circle: fenceType === 'CIRCLE',
                    rectangle: fenceType === 'RECTANGLE',
                    polyline: fenceType === 'LINE' || fenceType === 'CORRIDOR',
                    marker: false,
                    circlemarker: false
                },
                edit: {
                    featureGroup: drawnItems,
                    remove: true
                }
            };
            
            // Enable the appropriate drawing tool
            let drawTool;
            switch(fenceType) {
                case 'POLYGON':
                    drawTool = new L.Draw.Polygon(map, drawOptions.draw);
                    break;
                case 'CIRCLE':
                    drawTool = new L.Draw.Circle(map, drawOptions.draw);
                    break;
                case 'RECTANGLE':
                    drawTool = new L.Draw.Rectangle(map, drawOptions.draw);
                    break;
                case 'LINE':
                case 'CORRIDOR':
                    drawTool = new L.Draw.Polyline(map, drawOptions.draw);
                    break;
            }
            
            if (drawTool) {
                drawTool.enable();
                elements.drawBtn.textContent = 'Drawing...';
                elements.drawBtn.disabled = true;
                elements.drawBtn.classList.add('active');
            }
        }
        
        function cancelDrawing() {
            if (drawControl) {
                map.removeControl(drawControl);
                drawControl = null;
            }
            
            // Disable any active drawing
            map.fire('draw:drawstop');
            
            drawnItems.clearLayers();
            elements.drawBtn.textContent = 'Start Drawing';
            elements.drawBtn.disabled = false;
            elements.drawBtn.classList.remove('active');
            elements.submitBtn.disabled = true;
            showMessage('Drawing cancelled', 'info');
        }


        
        
        function handleDrawCreated(e) {
            const layer = e.layer;
            drawnItems.clearLayers();
            drawnItems.addLayer(layer);
            
            // Extract data based on layer type
            const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
            let fenceType;
            
            // Get the appropriate fence type based on category
            switch(category) {
                case 'STATION':
                    fenceType = elements.fenceTypeStation.value;
                    break;
                case 'ROUTE':
                    fenceType = elements.fenceTypeRoute.value;
                    break;
                case 'HOTSPOT':
                    fenceType = elements.fenceTypeHotspot.value;
                    break;
            }
            
            switch(fenceType) {
                case 'CIRCLE':
                    if (layer instanceof L.Circle) {
                        const center = layer.getLatLng();
                        const radius = layer.getRadius();
                        
                        document.getElementById('centerLat').value = center.lat;
                        document.getElementById('centerLng').value = center.lng;
                        elements.radiusMeters.value = radius.toFixed(2);
                    }
                    break;
                    
                case 'RECTANGLE':
                    if (layer instanceof L.Rectangle) {
                        const bounds = layer.getBounds();
                        document.getElementById('minLat').value = bounds.getSouth();
                        document.getElementById('minLng').value = bounds.getWest();
                        document.getElementById('maxLat').value = bounds.getNorth();
                        document.getElementById('maxLng').value = bounds.getEast();
                    }
                    break;
                    
                case 'POLYGON':
                    if (layer instanceof L.Polygon) {
                        const latlngs = layer.getLatLngs()[0];
                        displayCoordinates(latlngs);
                    }
                    break;
                    
                case 'LINE':
                case 'CORRIDOR':
                    if (layer instanceof L.Polyline) {
                        const latlngs = layer.getLatLngs();
                        displayCoordinates(latlngs);
                    }
                    break;
            }
            
            // Reset draw button
            elements.drawBtn.textContent = 'Start Drawing';
            elements.drawBtn.disabled = false;
            elements.drawBtn.classList.remove('active');
            
            // Enable submit button
            elements.submitBtn.disabled = false;
            
            showMessage('Geofence drawn successfully. Fill remaining details and submit.', 'info');
        }
        
        function displayCoordinates(latlngs) {
            elements.coordinatesContainer.innerHTML = '';
            
            latlngs.forEach((latlng, index) => {
                const div = document.createElement('div');
                div.className = 'coordinate-item';
                div.textContent = `Point ${index + 1}: ${latlng.lat.toFixed(6)}, ${latlng.lng.toFixed(6)}`;
                elements.coordinatesContainer.appendChild(div);
            });
        }
        
        // Enhanced Form Submission with Edit/Update
        async function handleFormSubmit(e) {
            e.preventDefault();
            
            // Disable submit button
            elements.submitBtn.disabled = true;
            elements.submitBtn.textContent = state.editMode ? 'Updating...' : 'Creating...';
            
            // Build request payload
            const payload = buildPayload();
            
            // Log payload for debugging
            console.log('Payload to send:', JSON.stringify(payload, null, 2));
            
            // Validate payload
            if (!validatePayload(payload)) {
                elements.submitBtn.disabled = false;
                elements.submitBtn.textContent = state.editMode ? 'Update Geofence' : 'Create Geofence';
                return;
            }
            
            try {
                let url, method;
                
                if (state.editMode) {
                    // Update existing geofence
                    url = `https://demo2.bsl.co.ke/api/v1/geofences/${elements.geofenceId.value}`;
                    method = 'PUT';
                } else {
                    // Create new geofence
                    url = 'https://demo2.bsl.co.ke/api/v1/geofences';
                    method = 'POST';
                }
                
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });
                
                const data = await response.json();
                console.log('Response from server:', data);
                
                if (response.ok) {
                    showMessage(`Geofence ${state.editMode ? 'updated' : 'created'} successfully! ID: ${data.id}`, 'success');
                    resetForm();
                    loadAllGeofences();
                    loadRoutes();
                    loadStations();
                    loadHotspots();
                } else {
                    const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
                    showMessage(`Error: ${errorMsg}`, 'error');
                    
                    // Log detailed error information
                    if (data.errors) {
                        console.error('Validation errors:', data.errors);
                    }
                }
            } catch (error) {
                showMessage(`Error: ${error.message}`, 'error');
                console.error('Fetch error:', error);
            } finally {
                elements.submitBtn.disabled = false;
                elements.submitBtn.textContent = state.editMode ? 'Update Geofence' : 'Create Geofence';
            }
        }
        
        function buildPayload() {
            const formData = new FormData(elements.form);
            const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
            
            // Build base payload
            const payload = {
                name: formData.get('name'),
                description: formData.get('description') || null,
                colorHex: formData.get('colorHex')
            };
            
            // Set category-specific properties
            switch(category) {
                case 'STATION':
                    payload.isStation = true;
                    payload.fenceType = elements.fenceTypeStation.value;
                    payload.stationType = formData.get('stationType') || null;
                    payload.dwellTimeSeconds = parseInt(formData.get('dwellTimeSeconds')) || 60;
                    payload.isFinalDestination = document.getElementById('isFinalDestination').checked;

                    const parentRouteId = formData.get('parentRouteId');
                    if (parentRouteId) {
                        payload.parentRouteId = parseInt(parentRouteId);
                    }
                    break;
                    
                case 'ROUTE':
                    payload.isRoute = true;
                    payload.fenceType = elements.fenceTypeRoute.value;
                    payload.routeStatus = formData.get('routeStatus') || 'ACTIVE';
                    
                    // Add buffer width for corridors
                    if (payload.fenceType === 'CORRIDOR') {
                        const bufferWidth = parseFloat(formData.get('bufferWidthMeters'));
                        if (!isNaN(bufferWidth) && bufferWidth > 0) {
                            payload.bufferWidthMeters = bufferWidth;
                        }
                    }
                    
                    // Get selected stations
                    const stationIds = Array.from(elements.assignedStations.selectedOptions).map(opt => parseInt(opt.value));
                    if (stationIds.length > 0) {
                        payload.stationIds = stationIds;
                    }
                    break;
                    
                case 'HOTSPOT':
                    payload.isHotspot = true;
                    payload.fenceType = elements.fenceTypeHotspot.value;
                    payload.isAutoAssigned = elements.isAutoAssigned.checked;
                    break;
            }
            
            // Extract geometry from drawn layer
            const layers = drawnItems.getLayers();
            if (layers.length > 0) {
                const layer = layers[0];
                const fenceType = payload.fenceType;
                
                switch(fenceType) {
                    case 'CIRCLE':
                        if (layer instanceof L.Circle) {
                            const center = layer.getLatLng();
                            payload.centerLat = center.lat;
                            payload.centerLng = center.lng;
                            const radius = parseFloat(formData.get('radiusMeters'));
                            if (!isNaN(radius) && radius > 0) {
                                payload.radiusMeters = radius;
                            }
                        }
                        break;
                        
                    case 'RECTANGLE':
                        if (layer instanceof L.Rectangle) {
                            const bounds = layer.getBounds();
                            payload.minLat = bounds.getSouth();
                            payload.minLng = bounds.getWest();
                            payload.maxLat = bounds.getNorth();
                            payload.maxLng = bounds.getEast();
                        }
                        break;
                        
                    case 'POLYGON':
                    case 'LINE':
                    case 'CORRIDOR':
                        if (layer instanceof L.Polygon || layer instanceof L.Polyline) {
                            const latlngs = layer instanceof L.Polygon ? 
                                layer.getLatLngs()[0] : 
                                layer.getLatLngs();
                            payload.coordinates = latlngs.map(latlng => ({
                                lat: latlng.lat,
                                lng: latlng.lng
                            }));
                            
                            // For corridors, ensure buffer width is set
                            if (fenceType === 'CORRIDOR' && !payload.bufferWidthMeters) {
                                payload.bufferWidthMeters = 30; // default
                            }
                        }
                        break;
                }
            }
            
            // Clean up payload - remove undefined or null values for optional fields
            Object.keys(payload).forEach(key => {
                if (payload[key] === undefined || payload[key] === null || payload[key] === '') {
                    delete payload[key];
                }
            });
            
            return payload;
        }
        
        function validatePayload(payload) {
            console.log('Validating payload:', payload);
            
            // Check name
            if (!payload.name || payload.name.trim() === '') {
                showMessage('Geofence name is required', 'error');
                return false;
            }
            
            // Check that exactly one type flag is set
            const typeFlags = [payload.isStation, payload.isRoute, payload.isHotspot].filter(Boolean).length;
            if (typeFlags !== 1) {
                showMessage('Geofence must be exactly one type: station, route, or hotspot', 'error');
                return false;
            }
            
            // Check fence type
            const validFenceTypes = ['POLYGON', 'CIRCLE', 'RECTANGLE', 'LINE', 'CORRIDOR'];
            if (!payload.fenceType || !validFenceTypes.includes(payload.fenceType)) {
                showMessage('Valid geometric type is required', 'error');
                return false;
            }
            
            // Validate geometry
            const layers = drawnItems.getLayers();
            if (layers.length === 0) {
                showMessage('Please draw a geofence on the map first', 'error');
                return false;
            }
            
            // Type-specific validations
            switch(payload.fenceType) {
                case 'CIRCLE':
                    if (!payload.radiusMeters || payload.radiusMeters <= 0) {
                        showMessage('Radius must be a positive number', 'error');
                        return false;
                    }
                    if (!payload.centerLat || !payload.centerLng) {
                        showMessage('Circle center coordinates are required', 'error');
                        return false;
                    }
                    break;
                    
                case 'LINE':
                case 'CORRIDOR':
                    if (!payload.coordinates || payload.coordinates.length < 2) {
                        showMessage('Line/Corridor must have at least 2 points', 'error');
                        return false;
                    }
                    if (payload.fenceType === 'CORRIDOR' && (!payload.bufferWidthMeters || payload.bufferWidthMeters <= 0)) {
                        showMessage('Corridor buffer width must be a positive number', 'error');
                        return false;
                    }
                    break;
                    
                case 'POLYGON':
                    if (!payload.coordinates || payload.coordinates.length < 3) {
                        showMessage('Polygon must have at least 3 points', 'error');
                        return false;
                    }
                    break;
                    
                case 'RECTANGLE':
                    if (!payload.minLat || !payload.minLng || !payload.maxLat || !payload.maxLng) {
                        showMessage('Rectangle bounds are required', 'error');
                        return false;
                    }
                    break;
            }
            
            return true;
        }
        
        function resetForm() {
            // Reset form fields
            elements.form.reset();
            
            // Reset category to station (default)
            document.getElementById('typeStation').checked = true;
            
            // Reset color
            elements.colorHex.value = '#3B82F6';
            elements.colorValue.textContent = '#3B82F6';
            
            // Reset auto-assigned checkbox
            elements.isAutoAssigned.checked = true;
            
            // Show station config
            elements.stationConfig.style.display = 'block';
            elements.routeConfig.style.display = 'none';
            elements.hotspotConfig.style.display = 'none';
            
            // Remove required attributes from all except station
            elements.fenceTypeStation.setAttribute('required', 'required');
            elements.fenceTypeRoute.removeAttribute('required');
            elements.fenceTypeHotspot.removeAttribute('required');
            
            // Clear map drawings
            drawnItems.clearLayers();
            
            // Hide dynamic fields
            elements.circleFields.style.display = 'none';
            elements.coordinatesSection.style.display = 'none';
            
            // Clear coordinates display
            elements.coordinatesContainer.innerHTML = '';
            
            // Disable submit button
            elements.submitBtn.disabled = true;
            
            // Reset fence type dropdowns
            elements.fenceTypeStation.selectedIndex = 0;
            updateInstructions('', 'station');
            
            // Cancel any active drawing
            cancelDrawing();
            
            // Reset edit mode
            state.editMode = false;
            elements.geofenceId.value = '';
            elements.mode.value = 'create';
            elements.submitBtn.textContent = 'Create Geofence';
            elements.cancelEditBtn.style.display = 'none';
        }
        
        function cancelEdit() {
            resetForm();
        }

        function updateInstructions(type) {
            const instructions = document.getElementById('instructions');
            const messages = {
                'POLYGON': 'Click "Start Drawing", then click on map to create polygon vertices. Double-click to finish.',
                'CIRCLE': 'Click "Start Drawing", then click and drag on map to create a circle.',
                'RECTANGLE': 'Click "Start Drawing", then click and drag on map to create a rectangle.',
                'LINE': 'Click "Start Drawing", then click on map to create line points. Double-click to finish.',
                'CORRIDOR': 'Click "Start Drawing", then click on map to create corridor path. Double-click to finish.',
                '': 'Select geofence type above, then click "Start Drawing" and draw on the map'
            };
            
            instructions.textContent = messages[type] || messages[''];
        }

        function handleRouteFenceTypeChange() {
            const type = elements.fenceTypeRoute.value;
            updateDrawingUI(type);
            updateInstructions(type);
        }

        function handleStationFenceTypeChange() {
            const type = elements.fenceTypeStation.value;
            updateDrawingUI(type);
            updateInstructions(type);
        }
        
        function handleHotspotFenceTypeChange() {
            const type = elements.fenceTypeHotspot.value;
            updateDrawingUI(type);
            updateInstructions(type);
        }

        function updateDrawingUI(fenceType) {
            // Reset all fields
            elements.circleFields.style.display = 'none';
            elements.coordinatesSection.style.display = 'none';
            elements.radiusMeters.value = '';
            elements.coordinatesContainer.innerHTML = '';
            
            // Clear any existing drawings
            drawnItems.clearLayers();
            elements.submitBtn.disabled = true;
            
            // Show/hide fields based on type
            switch(fenceType) {
                case 'CIRCLE':
                    elements.circleFields.style.display = 'block';
                    break;
                case 'LINE':
                case 'CORRIDOR':
                    elements.coordinatesSection.style.display = 'block';
                    break;
                case 'POLYGON':
                    elements.coordinatesSection.style.display = 'block';
                    break;
                case 'RECTANGLE':
                    // Rectangle uses hidden fields, no extra UI needed
                    break;
            }
        }
        
        // Enhanced API Functions
        async function loadAllGeofences() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences?size=1000');
                const data = await response.json();
                
                if (response.ok) {
                    state.geofences = data.content || data;
                    filterAllGeofences();
                    renderGeofencesOnMap();
                }
            } catch (error) {
                console.error('Error loading geofences:', error);
            }
        }
        
        async function loadRoutes() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/routes?size=1000');
                const data = await response.json();
                
                if (response.ok) {
                    state.routes = data.content || data;
                    filterRoutes();
                }
            } catch (error) {
                console.error('Error loading routes:', error);
            }
        }
        
        async function loadStations() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/stations?size=1000');
                const data = await response.json();
                
                if (response.ok) {
                    state.stations = data.content || data;
                    filterStations();
                }
            } catch (error) {
                console.error('Error loading stations:', error);
            }
        }
        
        async function loadHotspots() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/hotspots?size=1000');
                const data = await response.json();
                
                if (response.ok) {
                    state.hotspots = data.content || data;
                    filterHotspots();
                }
            } catch (error) {
                console.error('Error loading hotspots:', error);
            }
        }
        
        async function loadDevices() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/devices?size=1000');
                const data = await response.json();
                
                if (response.ok) {
                    state.devices = data.content || data;
                    elements.selectDevice.innerHTML = '<option value="">Select device</option>';
                    
                    state.devices.forEach(device => {
                        const option = document.createElement('option');
                        option.value = device.deviceId || device.id;
                        option.textContent = device.name || device.serialNo;
                        elements.selectDevice.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading devices:', error);
            }
        }
        
        async function loadRoutesForParentSelection() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/routes?size=50');
                const data = await response.json();
                
                if (response.ok) {
                    const routes = data.content || data;
                    elements.parentRoute.innerHTML = '<option value="">Select parent route (optional)</option>';
                    
                    routes.forEach(route => {
                        const option = document.createElement('option');
                        option.value = route.id;
                        option.textContent = route.name;
                        elements.parentRoute.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading routes:', error);
            }
        }
        
        async function loadStationsForRouteAssignment() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/stations?size=50');
                const data = await response.json();
                
                if (response.ok) {
                    const stations = data.content || data;
                    elements.assignedStations.innerHTML = '';
                    
                    stations.forEach(station => {
                        const option = document.createElement('option');
                        option.value = station.id;
                        option.textContent = `${station.name} (${station.stationType || 'Station'})`;
                        elements.assignedStations.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading stations:', error);
            }
        }
        
        async function loadRoutesForAssignment() {
            try {
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/routes?size=50');
                const data = await response.json();
                
                if (response.ok) {
                    elements.selectRoute.innerHTML = '<option value="">Select route</option>';
                    
                    const routes = data.content || data;
                    routes.forEach(route => {
                        const option = document.createElement('option');
                        option.value = route.id;
                        option.textContent = route.name;
                        elements.selectRoute.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading routes:', error);
            }
        }
        
        async function loadRouteStations() {
            const routeId = elements.selectRoute.value;
            if (!routeId) return;
            
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/routes/${routeId}/stations`);
                const data = await response.json();
                
                if (response.ok) {
                    elements.routeStations.innerHTML = '';
                    
                    if (data.length === 0) {
                        elements.routeStations.innerHTML = '<div class="station-item">No stations assigned to this route</div>';
                    } else {
                        data.forEach(station => {
                            const div = document.createElement('div');
                            div.className = 'station-item';
                            div.innerHTML = `
                                <div class="station-info">
                                    <span class="station-type">${station.stationType || 'Station'}</span>
                                    <span>${station.name}</span>
                                </div>
                            `;
                            elements.routeStations.appendChild(div);
                        });
                    }
                }
            } catch (error) {
                console.error('Error loading route stations:', error);
            }
        }
        
        async function assignDeviceToRoute() {
            const deviceId = elements.selectDevice.value;
            const routeId = elements.selectRoute.value;
            
            if (!deviceId || !routeId) {
                showMessage('Please select both device and route', 'error');
                return;
            }
            
            try {
                const payload = {
                    deviceId: parseInt(deviceId),
                    routeId: parseInt(routeId)
                };
                
                const response = await fetch('https://demo2.bsl.co.ke/api/v1/geofences/routes/assign-device', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });
                
                if (response.ok) {
                    showMessage(`Device successfully assigned to route! All stations on this route are now assigned to the device.`, 'success');
                } else {
                    const data = await response.json();
                    const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
                    showMessage(`Error: ${errorMsg}`, 'error');
                }
            } catch (error) {
                showMessage(`Error: ${error.message}`, 'error');
                console.error('Fetch error:', error);
            }
        }
        
        // Enhanced Rendering Functions
        function renderGeofenceList(containerId, geofences, showActions = false) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            container.innerHTML = '';
            
            if (geofences.length === 0) {
                container.innerHTML = '<div class="geofence-item">No geofences found</div>';
                return;
            }
            
            geofences.forEach(geofence => {
                const div = document.createElement('div');
                div.className = `geofence-item ${state.selectedGeofence?.id === geofence.id ? 'selected' : ''}`;
                div.dataset.id = geofence.id;
                
                // Determine type
                let typeClass = 'type-regular';
                let typeText = 'Geofence';
                let icon = 'fas fa-shapes';
                
                if (geofence.route) {
                    typeClass = 'type-route';
                    typeText = 'Route';
                    icon = 'fas fa-route';
                } else if (geofence.station) {
                    typeClass = 'type-station';
                    typeText = 'Station';
                    icon = 'fas fa-map-marker-alt';
                } else if (geofence.hotspot) {
                    typeClass = 'type-hotspot';
                    typeText = 'Hotspot';
                    icon = 'fas fa-fire';
                }
                
                // Status badge for routes
                let statusBadge = '';
                if (geofence.route && geofence.routeStatus) {
                    statusBadge = `<span class="status-badge status-${geofence.routeStatus.toLowerCase()}">${geofence.routeStatus}</span>`;
                }
                
                div.innerHTML = `
                    <div class="geofence-name">
                        <div>
                            <span class="geofence-type ${typeClass}"><i class="${icon}"></i> ${typeText}</span>
                            ${geofence.name} ${statusBadge}
                        </div>
                        <div class="action-icons">
                            <i class="fas fa-eye action-icon" title="View Details" onclick="viewGeofenceDetails(${geofence.id}, event)"></i>
                            <i class="fas fa-edit action-icon" title="Edit" onclick="editGeofence(${geofence.id}, event)"></i>
                            <i class="fas fa-trash action-icon delete" title="Delete" onclick="deleteGeofence(${geofence.id}, event)"></i>
                        </div>
                    </div>
                    <div class="geofence-description">${geofence.description || ''}</div>
                    <div class="geofence-description">
                        <small>Type: ${geofence.fenceType || 'N/A'} | Created: ${new Date(geofence.createdAt).toLocaleDateString()}</small>
                    </div>
                `;
                
                if (showActions) {
                    const actionsDiv = document.createElement('div');
                    actionsDiv.className = 'geofence-actions';
                    
                    if (geofence.route) {
                        const viewBtn = document.createElement('button');
                        viewBtn.className = 'action-btn view';
                        viewBtn.innerHTML = '<i class="fas fa-map-marker-alt"></i> View Stations';
                        viewBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            viewRouteStations(geofence.id);
                        });
                        actionsDiv.appendChild(viewBtn);
                    }
                    
                    if (geofence.station && !geofence.parentRouteId) {
                        const assignBtn = document.createElement('button');
                        assignBtn.className = 'action-btn assign';
                        assignBtn.innerHTML = '<i class="fas fa-link"></i> Assign to Route';
                        assignBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            assignStationToRoute(geofence.id);
                        });
                        actionsDiv.appendChild(assignBtn);
                    }
                    
                    if (geofence.hotspot) {
                        const autoAssignBtn = document.createElement('button');
                        autoAssignBtn.className = 'action-btn assign';
                        autoAssignBtn.innerHTML = '<i class="fas fa-bolt"></i> Auto-Assign';
                        autoAssignBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            autoAssignHotspot(geofence.id);
                        });
                        actionsDiv.appendChild(autoAssignBtn);
                    }
                    
                    const mapBtn = document.createElement('button');
                    mapBtn.className = 'action-btn';
                    mapBtn.innerHTML = '<i class="fas fa-map"></i> Show on Map';
                    mapBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        highlightGeofenceOnMap(geofence.id);
                    });
                    actionsDiv.appendChild(mapBtn);
                    
                    div.appendChild(actionsDiv);
                }
                
                div.addEventListener('click', (e) => {
                    if (!e.target.closest('.action-icon') && !e.target.closest('.action-btn')) {
                        selectGeofence(geofence);
                    }
                });
                
                container.appendChild(div);
            });
        }
        
        // Enhanced Map Rendering
        function renderGeofencesOnMap() {
            // Clear existing layers
            state.mapLayers.forEach(layer => map.removeLayer(layer));
            state.mapLayers.clear();
            
            // Add geofences to map
            state.geofences.forEach(geofence => {
                createGeofenceLayer(geofence);
            });
        }

        function createGeofenceLayer(geofence) {
            console.log("Rendering geofence:", geofence);

            let layer = null;

            // ----------------------------
            // Normalize coordinates
            // ----------------------------
            if (!geofence.coordinates && geofence.coordinatesJson) {
                try {
                    geofence.coordinates = JSON.parse(geofence.coordinatesJson);
                } catch (e) {
                    console.error("Invalid coordinatesJson for geofence:", geofence.id);
                    return;
                }
            }

            // ----------------------------
            // Determine color
            // ----------------------------
            let color = geofence.colorHex || '#3B82F6';
            if (geofence.route) color = '#3498db';
            if (geofence.station) color = '#9b59b6';
            if (geofence.hotspot) color = '#e74c3c';

            // ----------------------------
            // Create geometry (priority-based)
            // ----------------------------

            // ROUTES / LINES / CORRIDORS
            if (
                (geofence.route ||
                    geofence.fenceType === 'LINE' ||
                    geofence.fenceType === 'CORRIDOR') &&
                geofence.coordinates?.length
            ) {
                layer = L.polyline(
                    geofence.coordinates.map(c => [c.lat, c.lng]),
                    {
                        color: color,
                        weight: geofence.fenceType === 'CORRIDOR' ? 8 : 4,
                        opacity: 0.7
                    }
                );
            }

            // POLYGONS
            else if (
                geofence.fenceType === 'POLYGON' &&
                geofence.coordinates?.length
            ) {
                layer = L.polygon(
                    geofence.coordinates.map(c => [c.lat, c.lng]),
                    {
                        color: color,
                        fillColor: color,
                        fillOpacity: 0.3,
                        weight: 2
                    }
                );
            }

            // RECTANGLES
            else if (
                geofence.fenceType === 'RECTANGLE' &&
                geofence.minLat != null &&
                geofence.minLng != null &&
                geofence.maxLat != null &&
                geofence.maxLng != null
            ) {
                layer = L.rectangle(
                    [
                        [geofence.minLat, geofence.minLng],
                        [geofence.maxLat, geofence.maxLng]
                    ],
                    {
                        color: color,
                        fillColor: color,
                        fillOpacity: 0.3,
                        weight: 2
                    }
                );
            }

            // CIRCLES / STATIONS / HOTSPOTS
            else if (
                geofence.centerLat != null &&
                geofence.centerLng != null &&
                (geofence.fenceType === 'CIRCLE' ||
                    geofence.station ||
                    geofence.hotspot)
            ) {
                layer = L.circle(
                    [geofence.centerLat, geofence.centerLng],
                    {
                        radius: geofence.radiusMeters || 100,
                        color: color,
                        fillColor: color,
                        fillOpacity: 0.5,
                        weight: 2
                    }
                );
            }

            // ----------------------------
            // Add to map + popup
            // ----------------------------
            if (layer) {
                const popupContent = `
                    <b>${geofence.name}</b><br>
                    Type: ${
                        geofence.route
                            ? 'Route'
                            : geofence.station
                            ? 'Station'
                            : geofence.hotspot
                            ? 'Hotspot'
                            : geofence.fenceType
                    }<br>
                    ${geofence.description || ''}<br>
                    <div style="margin-top:10px;">
                        <button onclick="viewGeofenceDetails(${geofence.id})"
                            style="background:${color};color:white;border:none;
                                   padding:5px 10px;border-radius:3px;
                                   cursor:pointer;margin-right:5px;">
                            <i class="fas fa-info-circle"></i> Details
                        </button>
                        <button onclick="editGeofence(${geofence.id})"
                            style="background:#3498db;color:white;border:none;
                                   padding:5px 10px;border-radius:3px;
                                   cursor:pointer;">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                    </div>
                `;

                layer.bindPopup(popupContent);
                layer.addTo(map);

                // Store reference
                state.mapLayers.set(geofence.id, layer);

                // Auto-extend bounds (optional but recommended)
                if (layer.getBounds) {
                    state.allBounds = state.allBounds || L.latLngBounds();
                    state.allBounds.extend(layer.getBounds());
                }
            } else {
                console.warn("No layer created for geofence:", geofence.id);
            }
        }
        
        // Edit Geofence Function
        async function editGeofence(id, event) {
            if (event) event.stopPropagation();
            
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/${id}`);
                const geofence = await response.json();
                
                if (response.ok) {
                    // Switch to create tab
                    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    document.querySelector('[data-tab="create"]').classList.add('active');
                    document.querySelectorAll('.tab-content').forEach(c => c.style.display = 'none');
                    document.getElementById('createTab').style.display = 'block';
                    
                    // Set edit mode
                    state.editMode = true;
                    elements.geofenceId.value = id;
                    elements.mode.value = 'edit';
                    elements.submitBtn.textContent = 'Update Geofence';
                    elements.cancelEditBtn.style.display = 'block';
                    
                    // Populate form
                    populateEditForm(geofence);
                    
                    // Draw existing geofence
                    drawExistingGeofence(geofence);
                    
                    showMessage(`Editing geofence: ${geofence.name}`, 'info');
                }
            } catch (error) {
                console.error('Error loading geofence:', error);
                showMessage('Error loading geofence for editing', 'error');
            }
        }
        
        function populateEditForm(geofence) {
            // Basic information
            document.getElementById('name').value = geofence.name;
            document.getElementById('description').value = geofence.description || '';
            document.getElementById('colorHex').value = geofence.colorHex || '#3B82F6';
            document.getElementById('colorValue').textContent = geofence.colorHex || '#3B82F6';
            
            // Set geofence category
            let category = 'STATION';
            if (geofence.route) category = 'ROUTE';
            else if (geofence.station) category = 'STATION';
            else if (geofence.hotspot) category = 'HOTSPOT';
            
            document.querySelector(`input[name="geofenceCategory"][value="${category}"]`).checked = true;
            handleGeofenceCategoryChange({ target: { value: category } });
            
            // Set fence type
            const fenceTypeElement = document.getElementById(category === 'STATION' ? 'fenceTypeStation' : 
                                                            (category === 'ROUTE' ? 'fenceTypeRoute' : 'fenceTypeHotspot'));
            if (fenceTypeElement) {
                fenceTypeElement.value = geofence.fenceType;
                fenceTypeElement.dispatchEvent(new Event('change'));
            }
            
            // Category-specific fields
            if (category === 'STATION') {
                document.getElementById('stationType').value = geofence.stationType || '';
                document.getElementById('dwellTimeSeconds').value = geofence.dwellTimeSeconds || 60;
                document.getElementById('isFinalDestination').checked = geofence.isFinalDestination || false;

                if (geofence.parentRouteId) {
                    document.getElementById('parentRoute').value = geofence.parentRouteId;
                }
            } else if (category === 'ROUTE') {
                document.getElementById('routeStatus').value = geofence.routeStatus || 'ACTIVE';
                document.getElementById('routeBufferWidth').value = geofence.bufferWidthMeters || 30;
                
                // Load assigned stations
                loadAssignedStationsForEdit(geofence.id);
            } else if (category === 'HOTSPOT') {
                document.getElementById('isAutoAssigned').checked = geofence.isAutoAssigned || false;
            }
        }
        
        async function loadAssignedStationsForEdit(routeId) {
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/routes/${routeId}/stations`);
                const stations = await response.json();
                
                if (response.ok) {
                    // Select the assigned stations
                    Array.from(elements.assignedStations.options).forEach(option => {
                        option.selected = stations.some(station => station.id == option.value);
                    });
                }
            } catch (error) {
                console.error('Error loading assigned stations:', error);
            }
        }
        
        function drawExistingGeofence(geofence) {
            drawnItems.clearLayers();
            
            let layer = null;
            
            switch(geofence.fenceType) {
                case 'CIRCLE':
                    if (geofence.centerLat && geofence.centerLng) {
                        layer = L.circle([geofence.centerLat, geofence.centerLng], {
                            radius: geofence.radiusMeters || 100
                        });
                    }
                    break;
                    
                case 'RECTANGLE':
                    if (geofence.minLat && geofence.minLng && geofence.maxLat && geofence.maxLng) {
                        const bounds = [
                            [geofence.minLat, geofence.minLng],
                            [geofence.maxLat, geofence.maxLng]
                        ];
                        layer = L.rectangle(bounds);
                    }
                    break;
                    
                case 'POLYGON':
                    if (geofence.coordinates && geofence.coordinates.length > 0) {
                        const latlngs = geofence.coordinates.map(coord => [coord.lat, coord.lng]);
                        layer = L.polygon(latlngs);
                    }
                    break;
                    
                case 'LINE':
                case 'CORRIDOR':
                    if (geofence.coordinates && geofence.coordinates.length > 0) {
                        const latlngs = geofence.coordinates.map(coord => [coord.lat, coord.lng]);
                        layer = L.polyline(latlngs);
                    }
                    break;
            }
            
            if (layer) {
                drawnItems.addLayer(layer);
                map.fitBounds(layer.getBounds());
                
                // Update form fields with geometry
                updateGeometryFields(layer, geofence.fenceType, geofence);
            }
        }
        
        function updateGeometryFields(layer, fenceType, geofence) {
            switch(fenceType) {
                case 'CIRCLE':
                    const center = layer.getLatLng();
                    document.getElementById('centerLat').value = center.lat;
                    document.getElementById('centerLng').value = center.lng;
                    document.getElementById('radiusMeters').value = geofence.radiusMeters || layer.getRadius();
                    break;
                case 'RECTANGLE':
                    const bounds = layer.getBounds();
                    document.getElementById('minLat').value = bounds.getSouth();
                    document.getElementById('minLng').value = bounds.getWest();
                    document.getElementById('maxLat').value = bounds.getNorth();
                    document.getElementById('maxLng').value = bounds.getEast();
                    break;
                case 'POLYGON':
                case 'LINE':
                case 'CORRIDOR':
                    const latlngs = layer.getLatLngs();
                    displayCoordinates(latlngs[0] || latlngs);
                    break;
            }
        }
        
        // Delete Geofence Function
        async function deleteGeofence(id, event) {
            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(`https://demo2.bsl.co.ke/api/v1/geofences/${id}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    showMessage('Geofence deleted successfully', 'success');
                    
                    // Remove from state
                    state.geofences = state.geofences.filter(g => g.id !== id);
                    state.routes = state.routes.filter(r => r.id !== id);
                    state.stations = state.stations.filter(s => s.id !== id);
                    state.hotspots = state.hotspots.filter(h => h.id !== id);
                    
                    // Remove from map
                    const layer = state.mapLayers.get(id);
                    if (layer) {
                        map.removeLayer(layer);
                        state.mapLayers.delete(id);
                    }
                    
                    // Reload lists
                    filterAllGeofences();
                    filterRoutes();
                    filterStations();
                    filterHotspots();
                } else {
                    const data = await response.json();
                    showMessage(`Error: ${data.message || 'Failed to delete geofence'}`, 'error');
                }
            } catch (error) {
                console.error('Error deleting geofence:', error);
                showMessage('Error deleting geofence', 'error');
            }
        }
        
        // View Route Stations Function
        async function viewRouteStations(routeId) {
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/routes/${routeId}/stations`);
                const stations = await response.json();
                
                if (response.ok) {
                    const route = state.routes.find(r => r.id == routeId);
                    let stationsHtml = `
                        <h3>${route?.name || 'Route'} Stations</h3>
                        <p>Total Stations: ${stations.length}</p>
                        <div class="station-list">
                    `;
                    
                    stations.forEach((station, index) => {
                        stationsHtml += `
                            <div class="station-item">
                                <div class="station-info">
                                    <span style="font-weight: bold; color: #666;">${index + 1}.</span>
                                    <span class="station-type">${station.stationType || 'Station'}</span>
                                    <span>${station.name}</span>
                                </div>
                                <div>
                                    <button class="action-btn" onclick="highlightGeofenceOnMap(${station.id})" style="margin-right: 5px;">
                                        <i class="fas fa-map-marker-alt"></i>
                                    </button>
                                    <button class="action-btn" onclick="viewGeofenceDetails(${station.id})">
                                        <i class="fas fa-info-circle"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                    
                    stationsHtml += `</div>`;
                    
                    document.getElementById('modalRouteStations').innerHTML = stationsHtml;
                    openModal('routeStationsModal');
                    
                    // Highlight route and stations on map
                    highlightRouteAndStations(routeId);
                }
            } catch (error) {
                console.error('Error loading route stations:', error);
                showMessage('Error loading route stations', 'error');
            }
        }
        
        // View Geofence Details Function
        async function viewGeofenceDetails(id, event) {
            if (event) event.stopPropagation();
            
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/${id}/details`);
                const geofence = await response.json();
                
                if (response.ok) {
                    let detailsHtml = `
                        <div style="max-width: 500px;">
                            <h3 style="color: ${geofence.colorHex || '#3B82F6'}">
                                ${geofence.name}
                            </h3>
                            <p><strong>ID:</strong> ${geofence.id}</p>
                            <p><strong>Type:</strong> ${geofence.fenceType}</p>
                            ${geofence.description ? `<p><strong>Description:</strong> ${geofence.description}</p>` : ''}
                            <p><strong>Created:</strong> ${new Date(geofence.createdAt).toLocaleString()}</p>
                            <p><strong>Updated:</strong> ${new Date(geofence.updatedAt).toLocaleString()}</p>
                    `;
                    
                    if (geofence.route) {
                        detailsHtml += `
                            <p><strong>Route Status:</strong> <span class="status-badge status-${geofence.routeStatus.toLowerCase()}">${geofence.routeStatus}</span></p>
                            ${geofence.bufferWidthMeters ? `<p><strong>Buffer Width:</strong> ${geofence.bufferWidthMeters}m</p>` : ''}
                        `;
                    }
                    
                    if (geofence.station) {
                        detailsHtml += `
                            <p><strong>Station Type:</strong> ${geofence.stationType || 'N/A'}</p>
                            <p><strong>Dwell Time:</strong> ${geofence.dwellTimeSeconds || 0} seconds</p>
                        `;
                    }
                    
                    if (geofence.hotspot) {
                        detailsHtml += `
                            <p><strong>Auto-assigned:</strong> ${geofence.isAutoAssigned ? 'Yes' : 'No'}</p>
                        `;
                    }
                    
                    detailsHtml += `
                        <div style="margin-top: 20px; display: flex; gap: 10px;">
                            <button onclick="editGeofence(${geofence.id})" style="background: #3498db; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button onclick="highlightGeofenceOnMap(${geofence.id})" style="background: #2ecc71; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">
                                <i class="fas fa-map-marker-alt"></i> Show on Map
                            </button>
                        </div>
                    </div>
                    `;
                    
                    document.getElementById('modalGeofenceDetails').innerHTML = detailsHtml;
                    openModal('geofenceDetailsModal');
                }
            } catch (error) {
                console.error('Error loading geofence details:', error);
                showMessage('Error loading geofence details', 'error');
            }
        }
        
        // Highlight Geofence on Map
        function highlightGeofenceOnMap(id) {
            const layer = state.mapLayers.get(id);
            if (layer) {
                map.fitBounds(layer.getBounds());
                layer.openPopup();
                
                // Add highlight effect
                if (layer.setStyle) {
                    const originalStyle = {
                        weight: layer.options.weight || 2,
                        opacity: layer.options.opacity || 0.7,
                        fillOpacity: layer.options.fillOpacity || 0.3
                    };
                    
                    layer.setStyle({
                        weight: 5,
                        opacity: 1,
                        fillOpacity: 0.5
                    });
                    
                    // Reset after 3 seconds
                    setTimeout(() => {
                        layer.setStyle(originalStyle);
                    }, 3000);
                }
            }
        }
        
        function highlightRouteAndStations(routeId) {
            // Highlight route
            const routeLayer = state.mapLayers.get(parseInt(routeId));
            if (routeLayer) {
                map.fitBounds(routeLayer.getBounds().pad(0.2));
                routeLayer.openPopup();
            }
        }
        
        // Assign Station to Route
        async function assignStationToRoute(stationId) {
            const routeId = prompt('Enter the Route ID to assign this station to:');
            if (!routeId) return;
            
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/routes/${routeId}/stations/${stationId}`, {
                    method: 'POST'
                });
                
                if (response.ok) {
                    showMessage('Station assigned to route successfully', 'success');
                    loadStations();
                } else {
                    const data = await response.json();
                    showMessage(`Error: ${data.message || 'Failed to assign station'}`, 'error');
                }
            } catch (error) {
                console.error('Error assigning station to route:', error);
                showMessage('Error assigning station to route', 'error');
            }
        }
        
        // Auto-assign Hotspot
        async function autoAssignHotspot(hotspotId) {
            try {
                const response = await fetch(`https://demo2.bsl.co.ke/api/v1/geofences/hotspots/assign-all?deviceId=${hotspotId}`, {
                    method: 'POST'
                });
                
                if (response.ok) {
                    showMessage('Hotspot auto-assigned to all devices', 'success');
                } else {
                    const data = await response.json();
                    showMessage(`Error: ${data.message || 'Failed to auto-assign hotspot'}`, 'error');
                }
            } catch (error) {
                console.error('Error auto-assigning hotspot:', error);
                showMessage('Error auto-assigning hotspot', 'error');
            }
        }
        
        // Utility Functions
        function selectGeofence(geofence) {
            state.selectedGeofence = geofence;
            
            // Update UI
            document.querySelectorAll('.geofence-item').forEach(item => {
                item.classList.remove('selected');
                if (parseInt(item.dataset.id) === geofence.id) {
                    item.classList.add('selected');
                }
            });
            
            // Zoom to geofence on map
            highlightGeofenceOnMap(geofence.id);
        }
        
        function handleMapClick(e) {
            // Handle map clicks if needed
        }
        
        function showMessage(message, type) {
            elements.responseMessage.textContent = message;
            elements.responseMessage.className = `response-message ${type}`;
            elements.responseMessage.style.display = 'block';
            
            const hideDelay = type === 'success' ? 5000 : 3000;
            
            setTimeout(() => {
                elements.responseMessage.style.display = 'none';
            }, hideDelay);
        }
        
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        // Initialize the application
        function init() {
            initEventListeners();
            updateColorValue();
            
            // Load initial data
            loadAllGeofences();
            loadRoutesForParentSelection();
            loadStationsForRouteAssignment();
            loadDevices();
            loadRoutesForAssignment();
            
            console.log('Enhanced Geofence & Route Management UI initialized');
        }
        
        // Start the application when DOM is loaded
        document.addEventListener('DOMContentLoaded', init);
        
        // Make functions available globally
        window.viewGeofenceDetails = viewGeofenceDetails;
        window.editGeofence = editGeofence;
        window.deleteGeofence = deleteGeofence;
        window.highlightGeofenceOnMap = highlightGeofenceOnMap;
        window.closeModal = closeModal;





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




loadParentRoutes();
function loadParentRoutes() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://demo2.bsl.co.ke/api/v1/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 || []; // Assuming paged response

                console.log('Devices 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>`;
                    }
                }

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

                
                

            

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

    xhr.send();
}



loadMystations();
function loadMystations() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://demo2.bsl.co.ke/api/v1/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 || []; // Assuming paged response

                console.log('Devices 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>`;
                    }
                }

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


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

    xhr.send();
}


loadMyhostspots();
function loadMyhostspots() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://demo2.bsl.co.ke/api/v1/geofences/hotspots?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 option = "";

                option += '<option selected value="" >-Select Hotspot-</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
                $("#selectShotspot").html(option);
                


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

    xhr.send();
}


assignHotspotsToRoutes.onclick = async () => {

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

    const hotspotsId = $("#selectShotspot").val();
    const routeId = $("#selectPrhtspotRoute").val();

    if (!hotspotsId || !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}/hotspots/${hotspotsId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });

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

              setTimeout(function () {
              
                  $("#assignHotspotsToRoutes").html("Assign Hotspot to Route");
                    $("#assignHotspotsToRoutes").prop("disabled", false);
                    $("#assignHotspotsToRoutes").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 () {
                  $("#assignHotspotsToRoutes").html("Assign Hotspot to Route");
                    $("#assignHotspotsToRoutes").prop("disabled", false);
                    $("#assignHotspotsToRoutes").attr("disabled", false);
            }, 1000);
        }
    } catch (error) {
          setTimeout(function () {
              
                  $("#assignHotspotsToRoutes").html("Assign Hotspot to Route");
                    $("#assignHotspotsToRoutes").prop("disabled", false);
                    $("#assignHotspotsToRoutes").attr("disabled", false);
            }, 1000);
        controller.showToastMsg(`Error: ${error.message}`, "#ff6666");
        console.error("Fetch error:", error);
    }
};


function logoutUser() {
    // clear session / token
    console.log("Logging out...");
    window.location.href = "login.html";
    localStorage.removeItem("userObj");
}