function allcreatedRoutes() {
    $(".tab_routesmanagement").html("");
    $(".crud_section").html("");

    // Use your configured server URL
    const API_BASE = serverURL; // assumed to be defined globally
    const GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'; // <-- REPLACE WITH YOUR KEY

    var htmlcontent = `<div class="container" style="margin-top: 20px; margin-bottom: 20px; overflow: hidden;">
    <div class="left-panel">
        <div class="form-panel">
            <h4>Enhanced Geofence & Route Management</h4>
            <div class="tab-container">
                <div class="tab active" data-tab="create"><i class="fas fa-plus"></i> Create</div>
                <div class="tab" data-tab="routes"><i class="fas fa-route"></i> Routes</div>
                <div class="tab" data-tab="stations"><i class="fas fa-map-marker-alt"></i> Stations</div>
                <div class="tab" data-tab="hotspots"><i class="fas fa-fire"></i> Hotspots</div>
                <div class="tab" data-tab="assign"><i class="fas fa-mobile-alt"></i> Assign</div>
            </div>

            <!-- CREATE TAB -->
            <div id="createTab" class="tab-content">
                <form id="geofenceForm" novalidate>
                    <input type="hidden" id="geofenceId" name="id">
                    <input type="hidden" id="mode" name="mode" value="create">
                    <div class="form-section">
                        <div class="section-title">Basic Information</div>
                        <div class="form-group">
                            <label for="name" class="required">Name</label>
                            <input type="text" id="name" name="name" required placeholder="Enter geofence name" maxlength="200">
                        </div>
                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea id="description" name="description" placeholder="Enter description" maxlength="500"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="colorHex">Color</label>
                            <div class="color-picker">
                                <input type="color" id="colorHex" name="colorHex" value="#3B82F6">
                                <span id="colorValue">#3B82F6</span>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="section-title">Geofence Type</div>
                        <div class="form-group">
                            <div class="radio-group">
                                <div class="radio-option">
                                    <input type="radio" id="typeStation" name="geofenceCategory" value="STATION" checked>
                                    <label for="typeStation">Station</label>
                                </div>
                                <div class="radio-option">
                                    <input type="radio" id="typeRoute" name="geofenceCategory" value="ROUTE">
                                    <label for="typeRoute">Route</label>
                                </div>
                                <div class="radio-option">
                                    <input type="radio" id="typeHotspot" name="geofenceCategory" value="HOTSPOT">
                                    <label for="typeHotspot">Hotspot</label>
                                </div>
                            </div>
                        </div>
                        <!-- Station Configuration -->
                        <div id="stationConfig">
                            <div class="form-group">
                                <label for="stationType">Station Type</label>
                                <select id="stationType" name="stationType">
                                    <option value="">Select station type</option>
                                    <option value="BUS_STOP">Bus Stop</option>
                                    <option value="PORT">Port</option>
                                    <option value="DEPOT">Depot</option>
                                    <option value="PARKING">Parking</option>
                                    <option value="CHECKPOINT">Checkpoint</option>
                                    <option value="TERMINAL">Terminal</option>
                                    <option value="HOTSPOT">Hotspot</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="fenceTypeStation" class="required">Geometric Type</label>
                                <select id="fenceTypeStation" name="fenceType" required>
                                    <option value="">Select geometric type</option>
                                    <option value="CIRCLE">Circle (default for stations)</option>
                                    <option value="POLYGON">Polygon</option>
                                    <option value="RECTANGLE">Rectangle</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="dwellTimeSeconds">Dwell Time (seconds)</label>
                                <input type="number" id="dwellTimeSeconds" name="dwellTimeSeconds" min="1" value="60" placeholder="Enter dwell time">
                            </div>
                            <div class="form-group">
                                <div class="checkbox-group">
                                    <input type="checkbox" id="isFinalDestination" name="isFinalDestination">
                                    <label for="isFinalDestination">is Final Destination?</label>
                                </div>
                            </div>
                            <div class="form-group" style="display: none;">
                                <label for="parentRoute">Parent Route (optional)</label>
                                <select id="parentRoute" name="parentRouteId">
                                    <option value="">Select parent route</option>
                                </select>
                            </div>
                        </div>
                        <!-- Route Configuration -->
                        <div id="routeConfig" style="display: none;">
                            <div class="form-group">
                                <label for="routeStatus">Route Status</label>
                                <select id="routeStatus" name="routeStatus">
                                    <option value="ACTIVE">Active</option>
                                    <option value="INACTIVE">Inactive</option>
                                    <option value="MAINTENANCE">Maintenance</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="fenceTypeRoute" class="required">Geometric Type for Path</label>
                                <select id="fenceTypeRoute" name="fenceType" required>
                                    <option value="">Select geometric type</option>
                                    <option value="LINE">Line (default for routes)</option>
                                    <option value="CORRIDOR">Corridor</option>
                                    <option value="POLYGON">Polygon</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="bufferWidthMeters">Buffer/Corridor Width (meters)</label>
                                <input type="number" id="routeBufferWidth" name="bufferWidthMeters" min="1" value="30" placeholder="Enter width for corridor">
                            </div>
                            <div class="form-group">
                                <label for="assignedStations">Assign Stations to Route</label>
                                <select id="assignedStations" name="stationIds" multiple style="height: 120px;"></select>
                                <small style="color: #666; font-size: 12px;">Hold Ctrl/Cmd to select multiple stations</small>
                            </div>
                        </div>
                        <!-- Hotspot Configuration -->
                        <div id="hotspotConfig" style="display: none;">
                            <div class="form-group">
                                <label for="fenceTypeHotspot" class="required">Geometric Type</label>
                                <select id="fenceTypeHotspot" name="fenceType" required>
                                    <option value="">Select geometric type</option>
                                    <option value="CIRCLE">Circle (default for hotspots)</option>
                                    <option value="POLYGON">Polygon</option>
                                    <option value="RECTANGLE">Rectangle</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <div class="checkbox-group">
                                    <input type="checkbox" id="isAutoAssigned" name="isAutoAssigned" checked>
                                    <label for="isAutoAssigned">Auto-assign to all devices</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="section-title">Draw Geofence</div>
                        <div class="draw-controls">
                            <div class="draw-buttons">
                                <button type="button" id="drawBtn">Start Drawing</button>
                                <button type="button" id="cancelDrawBtn" class="cancel">Cancel</button>
                            </div>
                            <div class="instructions" id="instructions">
                                Select geofence type above, then click "Start Drawing" and draw on the map.
                            </div>
                        </div>
                        <div id="circleFields" style="display: none;">
                            <div class="form-group">
                                <label for="radiusMeters" class="required">Radius (meters)</label>
                                <input type="number" id="radiusMeters" name="radiusMeters" min="1" step="0.1" placeholder="Enter radius in meters">
                            </div>
                        </div>
                        <div id="coordinatesSection" style="display: none;">
                            <label>Coordinates</label>
                            <div class="coordinates-container" id="coordinatesContainer"></div>
                        </div>
                    </div>
                    <!-- File Upload Section -->
                    <div class="form-section">
                        <div class="section-title">Upload from File (GPX/KML/KMZ)</div>
                        <div class="form-group">
                            <label for="fileUpload" class="required">Select File</label>
                            <input type="file" id="fileUpload" accept=".gpx,.kml,.kmz" />
                        </div>
                        <div class="draw-buttons" style="grid-template-columns:1fr;">
                            <button type="button" id="parseFileBtn" class="btn-secondary">Load & Draw on Map</button>
                        </div>
                        <div id="fileParseStatus" class="instructions" style="margin-top:10px;"></div>
                    </div>
                    <!-- Hidden fields -->
                    <input type="hidden" id="centerLat" name="centerLat">
                    <input type="hidden" id="centerLng" name="centerLng">
                    <input type="hidden" id="minLat" name="minLat">
                    <input type="hidden" id="minLng" name="minLng">
                    <input type="hidden" id="maxLat" name="maxLat">
                    <input type="hidden" id="maxLng" name="maxLng">

                    <button type="submit" class="submit-btn" id="submitBtn" disabled>Create Geofence</button>
                    <button type="button" class="btn-secondary" id="cancelEditBtn" style="display: none;">Cancel Edit</button>
                </form>
            </div>

            <!-- ROUTES TAB -->
            <div id="routesTab" class="tab-content" style="display: none;">
                <h4><i class="fas fa-route"></i> Route Management</h4>
                <div class="search-box">
                    <input type="text" id="searchRoutes" placeholder="Search routes...">
                </div>
                <div class="geofence-list" id="routesList"></div>
            </div>

            <!-- STATIONS TAB -->
            <div id="stationsTab" class="tab-content" style="display: none;">
                <h4><i class="fas fa-map-marker-alt"></i> Station Management</h4>
                <div class="form-section">
                    <div class="form-group">
                        <label for="selectStation" class="required">Select Station</label>
                        <select id="selectStation" name="stationId" required>
                            <option value="">Select Station</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="selectPrRoute" class="required">Select Route</label>
                        <select id="selectPrRoute" name="parentId" required>
                            <option value="">Select Route</option>
                        </select>
                    </div>
                    <button type="button" class="submit-btn" id="assignStationToRoutes">Assign Station to Route</button>
                </div>
                <div class="search-box">
                    <input type="text" id="searchStations" placeholder="Search stations...">
                </div>
                <div class="geofence-list" id="stationsList"></div>
            </div>

            <!-- HOTSPOTS TAB -->
            <div id="hotspotsTab" class="tab-content" style="display: none;">
                <h4><i class="fas fa-fire"></i> Hotspot Management</h4>
                <div class="form-section">
                    <div class="form-group">
                        <label for="selectShotspot" class="required">Select Hotspot</label>
                        <select id="selectShotspot" name="selectShotspotId" required>
                            <option value="">Select Hotspot</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="selectPrhtspotRoute" class="required">Select Route</label>
                        <select id="selectPrhtspotRoute" name="selectPrhtspotRouteId" required>
                            <option value="">Select Route</option>
                        </select>
                    </div>
                    <button type="button" class="submit-btn" id="assignHotspotsToRoutes">Assign Hotspot to Route</button>
                </div>
                <div class="search-box">
                    <input type="text" id="searchHotspots" placeholder="Search hotspots...">
                </div>
                <div class="geofence-list" id="hotspotsList"></div>
            </div>

            <!-- ASSIGN DEVICE TAB -->
            <div id="assignTab" class="tab-content" style="display: none;">
                <h4><i class="fas fa-mobile-alt"></i> Device Assignment</h4>
                <div class="form-section">
                    <div class="form-group">
                        <label for="selectDevice" class="required">Select Device</label>
                        <select id="selectDevice" name="deviceId" required>
                            <option value="">Select device</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="selectRoute" class="required">Select Route</label>
                        <select id="selectRoute" name="routeId" required>
                            <option value="">Select route</option>
                        </select>
                    </div>
                    <div class="device-assignment">
                        <h3>Route Stations</h3>
                        <div id="routeStations" class="station-list"></div>
                        <small>When you assign a device to a route, it will automatically be assigned to all stations on this route.</small>
                    </div>
                    <button type="button" class="submit-btn" id="assignDeviceBtn">Assign Device to Route</button>
                </div>
            </div>

            <div id="responseMessage" class="response-message"></div>
        </div>

        <div class="list-panel">
            <h4><i class="fas fa-list"></i> All Geofences</h4>
            <div class="search-box">
                <input type="text" id="searchAllGeofences" placeholder="Search all geofences...">
            </div>
            <div class="filter-controls">
                <div class="filter-options">
                    <div class="filter-option">
                        <input type="checkbox" id="showRoutes" checked>
                        <label for="showRoutes">Routes</label>
                    </div>
                    <div class="filter-option">
                        <input type="checkbox" id="showStations" checked>
                        <label for="showStations">Stations</label>
                    </div>
                    <div class="filter-option">
                        <input type="checkbox" id="showHotspots" checked>
                        <label for="showHotspots">Hotspots</label>
                    </div>
                </div>
            </div>
            <div class="geofence-list" id="allGeofencesList"></div>
        </div>
    </div>

    <div class="map-panel">
        <div id="map"></div>
        <div class="map-controls">
            <button id="showAllBtn"><i class="fas fa-globe"></i> Show All</button>
            <button id="showRoutesBtn"><i class="fas fa-route"></i> Show Routes</button>
            <button id="showStationsBtn"><i class="fas fa-map-marker-alt"></i> Show Stations</button>
            <button id="showHotspotsBtn"><i class="fas fa-fire"></i> Show Hotspots</button>
            <button id="clearMapBtn"><i class="fas fa-broom"></i> Clear Map</button>
            <button id="zoomToBoundsBtn"><i class="fas fa-search"></i> Zoom to Bounds</button>
        </div>
        <div class="legend">
            <div class="legend-item"><div class="legend-color legend-route"></div><span>Routes</span></div>
            <div class="legend-item"><div class="legend-color legend-station"></div><span>Stations</span></div>
            <div class="legend-item"><div class="legend-color legend-hotspot"></div><span>Hotspots</span></div>
        </div>
    </div>
</div>
<div id="routeStationsModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Route Stations</h3>
            <button class="close-modal" onclick="closeModal('routeStationsModal')">&times;</button>
        </div>
        <div id="modalRouteStations"></div>
    </div>
</div>
<div id="geofenceDetailsModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Geofence Details</h3>
            <button class="close-modal" onclick="closeModal('geofenceDetailsModal')">&times;</button>
        </div>
        <div id="modalGeofenceDetails"></div>
    </div>
</div>`;

    $(".tab_routesmanagement").html(htmlcontent);

    // ==================== GOOGLE MAPS DYNAMIC LOADER ====================
    let map;
    let drawingManager;
    let currentOverlay = null;
    const mapOverlays = new Map();

    const state = {
        geofences: [],
        routes: [],
        stations: [],
        hotspots: [],
        devices: [],
        selectedGeofence: null,
        editMode: 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')
    };

    // Load Google Maps API dynamically if not already present
    function loadGoogleMapsAPI() {
        return new Promise((resolve, reject) => {
            if (window.google && window.google.maps && window.google.maps.drawing) {
                resolve();
                return;
            }
            // Set a temporary callback that resolves the promise
            window.initMap = function() {
                resolve();
            };
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=drawing&callback=initMap`;
            script.async = true;
            script.defer = true;
            script.onerror = () => reject(new Error('Failed to load Google Maps API'));
            document.head.appendChild(script);
        });
    }

    // Initialize map after API is ready
    function initializeMap() {
        // const center = { lat: 11.5721, lng: 43.1456 }; // Djibouti
        const center = { lat: -1.286389, lng: 36.817223 }; // Djibouti

        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: center,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
                gestureHandling: "greedy",
                zoomControl: true,
                streetViewControl: true,
                mapTypeControl: true,
                fullscreenControl: true,
        });

        drawingManager = new google.maps.drawing.DrawingManager({
            drawingMode: null,
            drawingControl: false,
            polygonOptions: { editable: true, draggable: true, fillColor: '#3B82F6', strokeColor: '#3B82F6', fillOpacity: 0.3 },
            circleOptions: { editable: true, draggable: true, fillColor: '#3B82F6', strokeColor: '#3B82F6', fillOpacity: 0.3 },
            rectangleOptions: { editable: true, draggable: true, fillColor: '#3B82F6', strokeColor: '#3B82F6', fillOpacity: 0.3 },
            polylineOptions: { editable: true, draggable: true, strokeColor: '#3B82F6', strokeWeight: 3 }
        });
        drawingManager.setMap(map);

        google.maps.event.addListener(drawingManager, 'overlaycomplete', handleOverlayComplete);

        // Start the application
        initApplication();
    }

    // Start loading
    loadGoogleMapsAPI()
        .then(() => {
            initializeMap();
        })
        .catch(error => {
            console.error('Google Maps failed to load:', error);
            showMessage('Failed to load Google Maps. Check API key and network.', 'error');
        });

    // ==================== CORE FUNCTIONS ====================
    function handleOverlayComplete(event) {
        if (currentOverlay) {
            currentOverlay.setMap(null);
        }

        currentOverlay = event.overlay;

        const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
        let fenceType;
        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 (event.type === 'circle' && fenceType === 'CIRCLE') {
            const center = event.overlay.getCenter();
            const radius = event.overlay.getRadius();
            document.getElementById('centerLat').value = center.lat();
            document.getElementById('centerLng').value = center.lng();
            elements.radiusMeters.value = radius.toFixed(2);
        } else if (event.type === 'rectangle' && fenceType === 'RECTANGLE') {
            const bounds = event.overlay.getBounds();
            const ne = bounds.getNorthEast();
            const sw = bounds.getSouthWest();
            document.getElementById('minLat').value = sw.lat();
            document.getElementById('minLng').value = sw.lng();
            document.getElementById('maxLat').value = ne.lat();
            document.getElementById('maxLng').value = ne.lng();
        } else if (event.type === 'polygon' && fenceType === 'POLYGON') {
            const path = event.overlay.getPath();
            displayCoordinatesGoogle(path.getArray());
        } else if (event.type === 'polyline' && (fenceType === 'LINE' || fenceType === 'CORRIDOR')) {
            const path = event.overlay.getPath();
            displayCoordinatesGoogle(path.getArray());
        } else {
            event.overlay.setMap(null);
            currentOverlay = null;
            showMessage('Drawn shape does not match selected geometric type', 'error');
            return;
        }

        elements.submitBtn.disabled = false;
        drawingManager.setDrawingMode(null);
        elements.drawBtn.textContent = 'Start Drawing';
        elements.drawBtn.disabled = false;
        elements.drawBtn.classList.remove('active');

        showMessage('Geofence drawn successfully. Fill remaining details and submit.', 'info');
    }

    function displayCoordinatesGoogle(path) {
        elements.coordinatesContainer.innerHTML = '';
        path.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);
        });
    }

    function startDrawing() {
        const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
        let fenceType;
        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;
        }

        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }

        let mode = null;
        switch(fenceType) {
            case 'CIRCLE': mode = google.maps.drawing.OverlayType.CIRCLE; break;
            case 'POLYGON': mode = google.maps.drawing.OverlayType.POLYGON; break;
            case 'RECTANGLE': mode = google.maps.drawing.OverlayType.RECTANGLE; break;
            case 'LINE':
            case 'CORRIDOR': mode = google.maps.drawing.OverlayType.POLYLINE; break;
        }
        drawingManager.setDrawingMode(mode);

        elements.drawBtn.textContent = 'Drawing...';
        elements.drawBtn.disabled = true;
        elements.drawBtn.classList.add('active');
    }

    function cancelDrawing() {
        drawingManager.setDrawingMode(null);
        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }
        elements.drawBtn.textContent = 'Start Drawing';
        elements.drawBtn.disabled = false;
        elements.drawBtn.classList.remove('active');
        elements.submitBtn.disabled = true;
        showMessage('Drawing cancelled', 'info');
    }

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

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

        let color = geofence.colorHex || '#000';
        if (geofence.route) color = '#000';
        if (geofence.station) color = '#9b59b6';
        if (geofence.hotspot) color = '#e74c3c';

        let overlay = null;

        if ((geofence.route || geofence.fenceType === 'LINE' || geofence.fenceType === 'CORRIDOR') && geofence.coordinates?.length) {
            const path = geofence.coordinates.map(c => ({ lat: c.lat, lng: c.lng }));
            overlay = new google.maps.Polyline({
                path: path,
                strokeColor: color,
                strokeWeight: geofence.fenceType === 'CORRIDOR' ? 8 : 4,
                strokeOpacity: 0.7,
                map: map
            });
        }
        else if (geofence.fenceType === 'POLYGON' && geofence.coordinates?.length) {
            const path = geofence.coordinates.map(c => ({ lat: c.lat, lng: c.lng }));
            overlay = new google.maps.Polygon({
                paths: path,
                strokeColor: color,
                fillColor: color,
                fillOpacity: 0.3,
                strokeWeight: 2,
                map: map
            });
        }
        else if (geofence.fenceType === 'RECTANGLE' && geofence.minLat != null && geofence.minLng != null && geofence.maxLat != null && geofence.maxLng != null) {
            const bounds = {
                north: geofence.maxLat,
                south: geofence.minLat,
                east: geofence.maxLng,
                west: geofence.minLng
            };
            overlay = new google.maps.Rectangle({
                bounds: bounds,
                strokeColor: color,
                fillColor: color,
                fillOpacity: 0.3,
                strokeWeight: 2,
                map: map
            });
        }
        else if (geofence.centerLat != null && geofence.centerLng != null && (geofence.fenceType === 'CIRCLE' || geofence.station || geofence.hotspot)) {
            overlay = new google.maps.Circle({
                center: { lat: geofence.centerLat, lng: geofence.centerLng },
                radius: geofence.radiusMeters || 100,
                strokeColor: color,
                fillColor: color,
                fillOpacity: 0.5,
                strokeWeight: 2,
                map: map
            });
        }

        if (overlay) {
            const infoContent = `
                <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;">Details</button>
                    <button onclick="editGeofence(${geofence.id})" style="background:#3498db;color:white;border:none;padding:5px 10px;border-radius:3px;cursor:pointer;">Edit</button>
                </div>
            `;
            const infoWindow = new google.maps.InfoWindow({ content: infoContent });
            overlay.addListener('click', (e) => {
                infoWindow.setPosition(e.latLng);
                infoWindow.open(map);
            });

            mapOverlays.set(geofence.id, overlay);
        } else {
            console.warn("No overlay created for geofence:", geofence.id);
        }
    }

    function clearMap() {
        mapOverlays.forEach(overlay => overlay.setMap(null));
        mapOverlays.clear();
        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }
    }

    function renderGeofencesOnMap() {
        clearMap();
        state.geofences.forEach(geofence => createGeofenceLayer(geofence));
    }

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

    function zoomToBounds() {
        if (mapOverlays.size === 0) return;
        const bounds = new google.maps.LatLngBounds();
        mapOverlays.forEach(overlay => {
            if (overlay instanceof google.maps.Circle) {
                bounds.union(overlay.getBounds());
            } else if (overlay instanceof google.maps.Rectangle) {
                bounds.union(overlay.getBounds());
            } else if (overlay instanceof google.maps.Polygon || overlay instanceof google.maps.Polyline) {
                const path = overlay.getPath();
                path.forEach(latLng => bounds.extend(latLng));
            }
        });
        map.fitBounds(bounds);
    }

    function highlightGeofenceOnMap(id) {
        const overlay = mapOverlays.get(id);
        if (!overlay) return;

        if (overlay instanceof google.maps.Circle || overlay instanceof google.maps.Rectangle) {
            map.fitBounds(overlay.getBounds());
        } else if (overlay instanceof google.maps.Polygon || overlay instanceof google.maps.Polyline) {
            const bounds = new google.maps.LatLngBounds();
            overlay.getPath().forEach(latLng => bounds.extend(latLng));
            map.fitBounds(bounds);
        }
        google.maps.event.trigger(overlay, 'click', { latLng: overlay.getCenter ? overlay.getCenter() : overlay.getPath().getAt(0) });
    }

    // ==================== FILE UPLOAD ====================
    const fileInput = document.getElementById('fileUpload');
    const parseFileBtn = document.getElementById('parseFileBtn');
    const fileParseStatus = document.getElementById('fileParseStatus');

    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') {
                const zip = new JSZip();
                const zipContent = await zip.loadAsync(file);
                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 {
                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);
                }
            }

            const { coordinates, geometryType } = extractGeometryFromGeoJSON(geojson);
            if (coordinates.length === 0) {
                throw new Error('No coordinates found in file');
            }

            setCategoryAndFenceTypeFromGeometry(geometryType);
            drawUploadedGeometryGoogle(coordinates, geometryType);

            fileParseStatus.textContent = `Loaded ${coordinates.length} points as ${geometryType}. You can now edit on map using the edit handles.`;
            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';

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

        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) {
        let fenceType = 'LINE';
        let category = 'ROUTE';

        if (geometryType === 'Point') {
            fenceType = 'CIRCLE';
            category = 'STATION';
        } else if (geometryType === 'Polygon' || geometryType === 'MultiPolygon') {
            fenceType = 'POLYGON';
            category = 'STATION';
        } else if (geometryType === 'LineString' || geometryType === 'MultiLineString') {
            fenceType = 'LINE';
            category = 'ROUTE';
        }

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

        const fenceSelect = document.getElementById(category === 'STATION' ? 'fenceTypeStation' : 
                                                    (category === 'ROUTE' ? 'fenceTypeRoute' : 'fenceTypeHotspot'));
        if (fenceSelect) {
            fenceSelect.value = fenceType;
            fenceSelect.dispatchEvent(new Event('change'));
        }
    }

    function drawUploadedGeometryGoogle(coordinates, geometryType) {
        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }

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

        const path = coordinates.map(c => ({ lat: c.lat, lng: c.lng }));

        if (geometryType === 'Point') {
            currentOverlay = new google.maps.Circle({
                center: path[0],
                radius: 50,
                strokeColor: '#3B82F6',
                fillColor: '#3B82F6',
                fillOpacity: 0.3,
                editable: true,
                draggable: true,
                map: map
            });
            map.setCenter(path[0]);
            map.setZoom(15);
        } else if (geometryType === 'Polygon' || geometryType === 'MultiPolygon') {
            currentOverlay = new google.maps.Polygon({
                paths: path,
                strokeColor: '#3B82F6',
                fillColor: '#3B82F6',
                fillOpacity: 0.3,
                editable: true,
                draggable: true,
                map: map
            });
            const bounds = new google.maps.LatLngBounds();
            path.forEach(p => bounds.extend(p));
            map.fitBounds(bounds);
        } else {
            currentOverlay = new google.maps.Polyline({
                path: path,
                strokeColor: '#3B82F6',
                strokeWeight: 3,
                editable: true,
                draggable: true,
                map: map
            });
            const bounds = new google.maps.LatLngBounds();
            path.forEach(p => bounds.extend(p));
            map.fitBounds(bounds);
        }

        elements.submitBtn.disabled = false;
    }

    // ==================== EVENT HANDLERS & UI LOGIC ====================
    function initEventListeners() {
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', handleTabSwitch);
        });
        document.querySelectorAll('input[name="geofenceCategory"]').forEach(radio => {
            radio.addEventListener('change', handleGeofenceCategoryChange);
        });
        elements.fenceTypeStation.addEventListener('change', handleStationFenceTypeChange);
        elements.fenceTypeRoute.addEventListener('change', handleRouteFenceTypeChange);
        elements.fenceTypeHotspot.addEventListener('change', handleHotspotFenceTypeChange);
        elements.colorHex.addEventListener('input', updateColorValue);
        elements.drawBtn.addEventListener('click', startDrawing);
        elements.cancelDrawBtn.addEventListener('click', cancelDrawing);
        elements.form.addEventListener('submit', handleFormSubmit);
        elements.selectRoute.addEventListener('change', loadRouteStations);
        elements.assignDeviceBtn.addEventListener('click', assignDeviceToRoute);
        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));
        elements.showRoutes.addEventListener('change', filterAllGeofences);
        elements.showStations.addEventListener('change', filterAllGeofences);
        elements.showHotspots.addEventListener('change', filterAllGeofences);
        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);
        elements.cancelEditBtn.addEventListener('click', cancelEdit);
    }

    function handleTabSwitch(e) {
        const tab = e.target.closest('.tab');
        const tabName = tab.dataset.tab;
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        tab.classList.add('active');
        document.querySelectorAll('.tab-content').forEach(content => {
            content.style.display = 'none';
        });
        document.getElementById(`${tabName}Tab`).style.display = 'block';
        switch(tabName) {
            case 'routes': loadRoutes(); break;
            case 'stations': loadStations(); break;
            case 'hotspots': loadHotspots(); break;
            case 'assign': loadDevices(); loadRoutesForAssignment(); break;
        }
    }

    function handleGeofenceCategoryChange(e) {
        const category = e.target.value;
        elements.stationConfig.style.display = 'none';
        elements.routeConfig.style.display = 'none';
        elements.hotspotConfig.style.display = 'none';
        elements.fenceTypeStation.removeAttribute('required');
        elements.fenceTypeRoute.removeAttribute('required');
        elements.fenceTypeHotspot.removeAttribute('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;
        }
        cancelDrawing();
    }

    function updateColorValue() {
        elements.colorValue.textContent = elements.colorHex.value;
    }

    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) {
        elements.circleFields.style.display = 'none';
        elements.coordinatesSection.style.display = 'none';
        elements.radiusMeters.value = '';
        elements.coordinatesContainer.innerHTML = '';

        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }
        elements.submitBtn.disabled = false;

        switch(fenceType) {
            case 'CIRCLE':
                elements.circleFields.style.display = 'block';
                break;
            case 'LINE':
            case 'CORRIDOR':
            case 'POLYGON':
                elements.coordinatesSection.style.display = 'block';
                break;
            case 'RECTANGLE':
                break;
        }
    }

    function buildPayload() {
        const formData = new FormData(elements.form);
        const category = document.querySelector('input[name="geofenceCategory"]:checked').value;
        const payload = {
            name: formData.get('name'),
            description: formData.get('description') || null,
            colorHex: formData.get('colorHex')
        };

        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';
                if (payload.fenceType === 'CORRIDOR') {
                    const bufferWidth = parseFloat(formData.get('bufferWidthMeters'));
                    if (!isNaN(bufferWidth) && bufferWidth > 0) payload.bufferWidthMeters = bufferWidth;
                }
                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;
        }

        if (currentOverlay) {
            const fenceType = payload.fenceType;
            if (fenceType === 'CIRCLE' && currentOverlay instanceof google.maps.Circle) {
                const center = currentOverlay.getCenter();
                payload.centerLat = center.lat();
                payload.centerLng = center.lng();
                const radius = parseFloat(formData.get('radiusMeters'));
                if (!isNaN(radius) && radius > 0) payload.radiusMeters = radius;
            } else if (fenceType === 'RECTANGLE' && currentOverlay instanceof google.maps.Rectangle) {
                const bounds = currentOverlay.getBounds();
                const ne = bounds.getNorthEast();
                const sw = bounds.getSouthWest();
                payload.minLat = sw.lat();
                payload.minLng = sw.lng();
                payload.maxLat = ne.lat();
                payload.maxLng = ne.lng();
            } else if ((fenceType === 'POLYGON' || fenceType === 'LINE' || fenceType === 'CORRIDOR') &&
                       (currentOverlay instanceof google.maps.Polygon || currentOverlay instanceof google.maps.Polyline)) {
                const path = currentOverlay.getPath().getArray();
                payload.coordinates = path.map(latLng => ({ lat: latLng.lat(), lng: latLng.lng() }));
                if (fenceType === 'CORRIDOR' && !payload.bufferWidthMeters) payload.bufferWidthMeters = 30;
            }
        }

        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);
        if (!payload.name || payload.name.trim() === '') {
            showMessage('Geofence name is required', 'error'); return false;
        }
        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;
        }
        const validFenceTypes = ['POLYGON', 'CIRCLE', 'RECTANGLE', 'LINE', 'CORRIDOR'];
        if (!payload.fenceType || !validFenceTypes.includes(payload.fenceType)) {
            showMessage('Valid geometric type is required', 'error'); return false;
        }
        if (!currentOverlay) {
            showMessage('Please draw a geofence on the map first', 'error'); return false;
        }
        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;
    }

    async function handleFormSubmit(e) {
        e.preventDefault();
        elements.submitBtn.disabled = true;
        elements.submitBtn.textContent = state.editMode ? 'Updating...' : 'Creating...';
        const payload = buildPayload();
        console.log('Payload to send:', JSON.stringify(payload, null, 2));
        if (!validatePayload(payload)) {
            elements.submitBtn.disabled = false;
            elements.submitBtn.textContent = state.editMode ? 'Update Geofence' : 'Create Geofence';
            return;
        }
        try {
            let url, method;
            if (state.editMode) {
                url = `${API_BASE}geofences/${elements.geofenceId.value}`;
                method = 'PUT';
            } else {
                url = `${API_BASE}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');
                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 resetForm() {
        elements.form.reset();
        document.getElementById('typeStation').checked = true;
        elements.colorHex.value = '#3B82F6';
        elements.colorValue.textContent = '#3B82F6';
        elements.isAutoAssigned.checked = true;
        elements.stationConfig.style.display = 'block';
        elements.routeConfig.style.display = 'none';
        elements.hotspotConfig.style.display = 'none';
        elements.fenceTypeStation.setAttribute('required', 'required');
        elements.fenceTypeRoute.removeAttribute('required');
        elements.fenceTypeHotspot.removeAttribute('required');
        if (currentOverlay) {
            currentOverlay.setMap(null);
            currentOverlay = null;
        }
        elements.circleFields.style.display = 'none';
        elements.coordinatesSection.style.display = 'none';
        elements.coordinatesContainer.innerHTML = '';
        elements.submitBtn.disabled = true;
        elements.fenceTypeStation.selectedIndex = 0;
        updateInstructions('');
        cancelDrawing();
        state.editMode = false;
        elements.geofenceId.value = '';
        elements.mode.value = 'create';
        elements.submitBtn.textContent = 'Create Geofence';
        elements.cancelEditBtn.style.display = 'none';
    }

    function cancelEdit() {
        resetForm();
    }

    // ==================== API CALLS ====================
    async function loadAllGeofences() {
        try {
            const response = await fetch(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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(`${API_BASE}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();
                showMessage(`Error: ${data.message || response.statusText}`, 'error');
            }
        } catch (error) {
            showMessage(`Error: ${error.message}`, 'error');
            console.error('Fetch error:', error);
        }
    }

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

    function selectGeofence(geofence) {
        state.selectedGeofence = geofence;
        document.querySelectorAll('.geofence-item').forEach(item => {
            item.classList.remove('selected');
            if (parseInt(item.dataset.id) === geofence.id) item.classList.add('selected');
        });
        highlightGeofenceOnMap(geofence.id);
    }


    async function editGeofence(id, event) {
    if (event) event.stopPropagation();
    try {
        const response = await fetch(`${API_BASE}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';

            state.editMode = true;
            elements.geofenceId.value = id;
            elements.mode.value = 'edit';
            elements.submitBtn.textContent = 'Update Geofence';
            elements.cancelEditBtn.style.display = 'block';

            // Wait a tiny bit for any pending async operations (like station loading)
            setTimeout(() => {
                populateEditForm(geofence);
                drawExistingGeofence(geofence);
            }, 100);

            showMessage(`Editing geofence: ${geofence.name}`, 'info');
        }
    } catch (error) {
        console.error('Error loading geofence:', error);
        showMessage('Error loading geofence for editing', 'error');
    }
}
    // async function editGeofence(id, event) {
    //     if (event) event.stopPropagation();
    //     try {
    //         const response = await fetch(`${API_BASE}geofences/${id}`);
    //         const geofence = await response.json();
    //         if (response.ok) {
    //             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';
    //             state.editMode = true;
    //             elements.geofenceId.value = id;
    //             elements.mode.value = 'edit';
    //             elements.submitBtn.textContent = 'Update Geofence';
    //             elements.cancelEditBtn.style.display = 'block';
    //             populateEditForm(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) {
        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';
        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 } });
        const fenceTypeElement = document.getElementById(category === 'STATION' ? 'fenceTypeStation' : 
                                                        (category === 'ROUTE' ? 'fenceTypeRoute' : 'fenceTypeHotspot'));
        if (fenceTypeElement) {
            fenceTypeElement.value = geofence.fenceType;
            fenceTypeElement.dispatchEvent(new Event('change'));
        }
        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;
            loadAssignedStationsForEdit(geofence.id);
        } else if (category === 'HOTSPOT') {
            document.getElementById('isAutoAssigned').checked = geofence.isAutoAssigned || false;
        }
    }

    async function loadAssignedStationsForEdit(routeId) {
        try {
            const response = await fetch(`${API_BASE}geofences/routes/${routeId}/stations`);
            const stations = await response.json();
            if (response.ok) {
                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) {
    if (currentOverlay) currentOverlay.setMap(null);

    // Parse coordinates if stored as JSON string
    let coords = geofence.coordinates;
    if (!coords && geofence.coordinatesJson) {
        try {
            coords = JSON.parse(geofence.coordinatesJson);
        } catch (e) {
            console.error('Failed to parse coordinatesJson:', e);
        }
    }

    let overlay = null;
    switch(geofence.fenceType) {
        case 'CIRCLE':
            if (geofence.centerLat && geofence.centerLng) {
                overlay = new google.maps.Circle({
                    center: { lat: geofence.centerLat, lng: geofence.centerLng },
                    radius: geofence.radiusMeters || 100,
                    editable: true,
                    draggable: true,
                    map: map
                });
            }
            break;
        case 'RECTANGLE':
            if (geofence.minLat && geofence.minLng && geofence.maxLat && geofence.maxLng) {
                overlay = new google.maps.Rectangle({
                    bounds: {
                        north: geofence.maxLat,
                        south: geofence.minLat,
                        east: geofence.maxLng,
                        west: geofence.minLng
                    },
                    editable: true,
                    draggable: true,
                    map: map
                });
            }
            break;
        case 'POLYGON':
        case 'LINE':
        case 'CORRIDOR':
            if (coords && coords.length > 0) {
                const path = coords.map(c => ({ lat: c.lat, lng: c.lng }));
                if (geofence.fenceType === 'POLYGON') {
                    overlay = new google.maps.Polygon({
                        paths: path,
                        editable: true,
                        draggable: true,
                        map: map
                    });
                } else {
                    overlay = new google.maps.Polyline({
                        path: path,
                        editable: true,
                        draggable: true,
                        map: map
                    });
                }
            }
            break;
    }

    if (overlay) {
        currentOverlay = overlay;
        // Fit map to bounds
        const bounds = new google.maps.LatLngBounds();
        if (overlay instanceof google.maps.Circle) {
            bounds.union(overlay.getBounds());
        } else if (overlay instanceof google.maps.Rectangle) {
            bounds.union(overlay.getBounds());
        } else if (overlay instanceof google.maps.Polygon || overlay instanceof google.maps.Polyline) {
            overlay.getPath().forEach(latLng => bounds.extend(latLng));
        }
        map.fitBounds(bounds);
        updateGeometryFields(overlay, geofence.fenceType, geofence);
        attachOverlayListeners(currentOverlay, fenceType);

    } else {
        console.warn('Could not create overlay for geofence:', geofence);
    }
}

function attachOverlayListeners(overlay, fenceType) {
    if (!overlay) return;

    if (fenceType === 'CIRCLE') {
        // Update radius input when circle is resized
        overlay.addListener('radius_changed', () => {
            if (overlay === currentOverlay) {
                document.getElementById('radiusMeters').value = overlay.getRadius().toFixed(2);
            }
        });
        // Update center coordinates (optional, but good for completeness)
        overlay.addListener('center_changed', () => {
            if (overlay === currentOverlay) {
                const center = overlay.getCenter();
                document.getElementById('centerLat').value = center.lat();
                document.getElementById('centerLng').value = center.lng();
            }
        });
    } else if (fenceType === 'RECTANGLE') {
        overlay.addListener('bounds_changed', () => {
            if (overlay === currentOverlay) {
                const bounds = overlay.getBounds();
                const ne = bounds.getNorthEast();
                const sw = bounds.getSouthWest();
                document.getElementById('minLat').value = sw.lat();
                document.getElementById('minLng').value = sw.lng();
                document.getElementById('maxLat').value = ne.lat();
                document.getElementById('maxLng').value = ne.lng();
            }
        });
    } else if (fenceType === 'POLYGON' || fenceType === 'LINE' || fenceType === 'CORRIDOR') {
        // For polylines and polygons, listen to changes in the path
        const path = overlay.getPath();
        // When a point is moved or the path is modified
        google.maps.event.addListener(path, 'set_at', () => {
            if (overlay === currentOverlay) {
                updateCoordinatesDisplay(overlay);
            }
        });
        google.maps.event.addListener(path, 'insert_at', () => {
            if (overlay === currentOverlay) {
                updateCoordinatesDisplay(overlay);
            }
        });
        google.maps.event.addListener(path, 'remove_at', () => {
            if (overlay === currentOverlay) {
                updateCoordinatesDisplay(overlay);
            }
        });
        // Also listen to the overlay's own event for when editing finishes (optional)
        overlay.addListener('mouseup', () => {
            if (overlay === currentOverlay) {
                updateCoordinatesDisplay(overlay);
            }
        });
    }
}

// Helper to update the coordinates display for polylines/polygons
function updateCoordinatesDisplay(overlay) {
    const path = overlay.getPath().getArray();
    displayCoordinatesGoogle(path);
}


    // function drawExistingGeofence(geofence) {
    //     if (currentOverlay) currentOverlay.setMap(null);
    //     let overlay = null;
    //     switch(geofence.fenceType) {
    //         case 'CIRCLE':
    //             if (geofence.centerLat && geofence.centerLng) {
    //                 overlay = new google.maps.Circle({
    //                     center: { lat: geofence.centerLat, lng: geofence.centerLng },
    //                     radius: geofence.radiusMeters || 100,
    //                     editable: true,
    //                     draggable: true,
    //                     map: map
    //                 });
    //             }
    //             break;
    //         case 'RECTANGLE':
    //             if (geofence.minLat && geofence.minLng && geofence.maxLat && geofence.maxLng) {
    //                 overlay = new google.maps.Rectangle({
    //                     bounds: {
    //                         north: geofence.maxLat, south: geofence.minLat,
    //                         east: geofence.maxLng, west: geofence.minLng
    //                     },
    //                     editable: true,
    //                     draggable: true,
    //                     map: map
    //                 });
    //             }
    //             break;
    //         case 'POLYGON':
    //             if (geofence.coordinates && geofence.coordinates.length > 0) {
    //                 const path = geofence.coordinates.map(c => ({ lat: c.lat, lng: c.lng }));
    //                 overlay = new google.maps.Polygon({
    //                     paths: path,
    //                     editable: true,
    //                     draggable: true,
    //                     map: map
    //                 });
    //             }
    //             break;
    //         case 'LINE':
    //         case 'CORRIDOR':
    //             if (geofence.coordinates && geofence.coordinates.length > 0) {
    //                 const path = geofence.coordinates.map(c => ({ lat: c.lat, lng: c.lng }));
    //                 overlay = new google.maps.Polyline({
    //                     path: path,
    //                     editable: true,
    //                     draggable: true,
    //                     map: map
    //                 });
    //             }
    //             break;
    //     }
    //     if (overlay) {
    //         currentOverlay = overlay;
    //         const bounds = new google.maps.LatLngBounds();
    //         if (overlay instanceof google.maps.Circle) {
    //             bounds.union(overlay.getBounds());
    //         } else if (overlay instanceof google.maps.Rectangle) {
    //             bounds.union(overlay.getBounds());
    //         } else if (overlay instanceof google.maps.Polygon || overlay instanceof google.maps.Polyline) {
    //             overlay.getPath().forEach(latLng => bounds.extend(latLng));
    //         }
    //         map.fitBounds(bounds);
    //         updateGeometryFields(overlay, geofence.fenceType, geofence);
    //     }
    // }

    function updateGeometryFields(overlay, fenceType, geofence) {
        if (fenceType === 'CIRCLE') {
            const center = overlay.getCenter();
            document.getElementById('centerLat').value = center.lat();
            document.getElementById('centerLng').value = center.lng();
            document.getElementById('radiusMeters').value = geofence.radiusMeters || overlay.getRadius();
        } else if (fenceType === 'RECTANGLE') {
            const bounds = overlay.getBounds();
            const ne = bounds.getNorthEast();
            const sw = bounds.getSouthWest();
            document.getElementById('minLat').value = sw.lat();
            document.getElementById('minLng').value = sw.lng();
            document.getElementById('maxLat').value = ne.lat();
            document.getElementById('maxLng').value = ne.lng();
        } else if (fenceType === 'POLYGON' || fenceType === 'LINE' || fenceType === 'CORRIDOR') {
            const path = overlay.getPath().getArray();
            displayCoordinatesGoogle(path);
        }
    }

    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(`${API_BASE}geofences/${id}`, { method: 'DELETE' });
            if (response.ok) {
                showMessage('Geofence deleted successfully', 'success');
                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);
                const overlay = mapOverlays.get(id);
                if (overlay) { overlay.setMap(null); mapOverlays.delete(id); }
                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');
        }
    }

    async function viewRouteStations(routeId) {
        try {
            const response = await fetch(`${API_BASE}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');
                highlightRouteAndStations(routeId);
            }
        } catch (error) {
            console.error('Error loading route stations:', error);
            showMessage('Error loading route stations', 'error');
        }
    }

   async function viewGeofenceDetails(id, event) {
    if (event) event.stopPropagation();
    try {
        const response = await fetch(`${API_BASE}geofences/${id}/details`);
        const geofence = await response.json();
        if (response.ok) {
            const formatDate = (dateStr) => new Date(dateStr).toLocaleString();
            const typeIcon = geofence.fenceType === 'LINE' ? 'fa-route' :
                             geofence.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';

            const htmlContent = `
                <style>
                    .geo-detail-card { font-family: 'Inter', system-ui, sans-serif; max-width: 550px; margin: 0 auto; }
                    .geo-header { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 2px solid ${geofence.colorHex || '#e2e8f0'}; }
                    .geo-header i { font-size: 2rem; color: ${geofence.colorHex || '#3b82f6'}; }
                    .geo-header h2 { margin: 0; font-weight: 600; color: ${geofence.colorHex || '#1e293b'}; }
                    .geo-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px 20px; margin: 16px 0; }
                    .geo-item { display: flex; flex-direction: column; }
                    .geo-item .label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; font-weight: 500; }
                    .geo-item .value { font-size: 1rem; font-weight: 500; color: #0f172a; word-break: break-word; }
                    .status-badge { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; background: #e2e8f0; color: #334155; }
                    .status-badge.active { background: #dbeafe; color: #1e40af; }
                    .status-badge.inactive { background: #fee2e2; color: #b91c1c; }
                    .section-title { font-size: 0.9rem; font-weight: 600; margin: 20px 0 10px 0; color: #334155; border-left: 4px solid ${geofence.colorHex || '#3b82f6'}; padding-left: 10px; }
                    .compact-list { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
                    .compact-item { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 20px; padding: 4px 12px; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 4px; color: #1e293b; }
                    .compact-item i { font-size: 0.75rem; color: ${geofence.colorHex || '#3b82f6'}; }
                    .action-buttons { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; border-top: 1px solid #e2e8f0; padding-top: 20px; }
                    .action-btn { border: none; padding: 8px 18px; border-radius: 8px; font-size: 0.9rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: 0.2s; }
                    .action-btn.edit { background: #3b82f6; color: white; }
                    .action-btn.edit:hover { background: #2563eb; }
                    .action-btn.map { background: #10b981; color: white; }
                    .action-btn.map:hover { background: #059669; }
                </style>
                <div class="geo-detail-card">
                    <div class="geo-header">
                        <i class="fas ${typeIcon}"></i>
                        <h2>${geofence.name}</h2>
                    </div>
                    
                    <div class="geo-grid">
                        <div class="geo-item">
                            <span class="label">ID</span>
                            <span class="value">${geofence.id}</span>
                        </div>
                        <div class="geo-item">
                            <span class="label">Type</span>
                            <span class="value">${geofence.fenceType} ${geofence.route ? '· Route' : geofence.station ? '· Station' : geofence.hotspot ? '· Hotspot' : ''}</span>
                        </div>
                        <div class="geo-item">
                            <span class="label">Status</span>
                            <span class="value"><span class="status-badge ${geofence.isActive ? 'active' : 'inactive'}">${geofence.isActive ? 'Active' : 'Inactive'}</span></span>
                        </div>
                        <div class="geo-item">
                            <span class="label">Route Status</span>
                            <span class="value"><span class="status-badge" style="background:#e0f2fe; color:#0369a1;">${geofence.routeStatus || 'N/A'}</span></span>
                        </div>
                        <div class="geo-item">
                            <span class="label">Created</span>
                            <span class="value">${formatDate(geofence.createdAt)}</span>
                        </div>
                        <div class="geo-item">
                            <span class="label">Updated</span>
                            <span class="value">${formatDate(geofence.updatedAt)}</span>
                        </div>
                        ${geofence.deviceCount !== undefined ? `
                        <div class="geo-item">
                            <span class="label">Devices</span>
                            <span class="value">${geofence.deviceCount}</span>
                        </div>` : ''}
                        ${geofence.stationCount !== undefined ? `
                        <div class="geo-item">
                            <span class="label">Stations</span>
                            <span class="value">${geofence.stationCount}</span>
                        </div>` : ''}
                        ${geofence.description ? `
                        <div class="geo-item" style="grid-column: span 2;">
                            <span class="label">Description</span>
                            <span class="value">${geofence.description}</span>
                        </div>` : ''}
                    </div>

                    ${geofence.stations && geofence.stations.length > 0 ? `
                    <div class="section-title">Stations in this route</div>
                    <div class="compact-list">
                        ${geofence.stations.map(s => `
                            <span class="compact-item" title="${s.description || ''}">
                                <i class="fas fa-map-pin"></i> ${s.name}
                            </span>
                        `).join('')}
                    </div>` : ''}

                    ${geofence.hotspots && geofence.hotspots.length > 0 ? `
                    <div class="section-title">Hotspots in this route</div>
                    <div class="compact-list">
                        ${geofence.hotspots.map(h => `
                            <span class="compact-item" title="${h.description || ''}">
                                <i class="fas fa-fire"></i> ${h.name}
                            </span>
                        `).join('')}
                    </div>` : ''}

                    <div class="action-buttons">
                        <button class="action-btn edit" onclick="Swal.close(); editGeofence(${geofence.id})">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button class="action-btn map" onclick="Swal.close(); highlightGeofenceOnMap(${geofence.id})">
                            <i class="fas fa-map-marker-alt"></i> Show on Map
                        </button>
                    </div>
                </div>
            `;

            await Swal.fire({
                title: null,
                html: htmlContent,
                showConfirmButton: false,
                showCloseButton: true,
                width: '650px',
                padding: '1.5rem',
                background: '#ffffff',
                customClass: { popup: 'geo-popup' }
            });
        }
    } catch (error) {
        console.error('Error loading geofence details:', error);
        showMessage('Error loading geofence details', 'error');
    }
}

    function highlightRouteAndStations(routeId) {
        const overlay = mapOverlays.get(parseInt(routeId));
        if (overlay) {
            const bounds = new google.maps.LatLngBounds();
            if (overlay instanceof google.maps.Circle) {
                bounds.union(overlay.getBounds());
            } else if (overlay instanceof google.maps.Rectangle) {
                bounds.union(overlay.getBounds());
            } else if (overlay instanceof google.maps.Polygon || overlay instanceof google.maps.Polyline) {
                overlay.getPath().forEach(latLng => bounds.extend(latLng));
            }
            map.fitBounds(bounds);
            google.maps.event.trigger(overlay, 'click', { latLng: overlay.getCenter ? overlay.getCenter() : overlay.getPath().getAt(0) });
        }
    }

    async function assignStationToRoute(stationId) {
        const routeId = prompt('Enter the Route ID to assign this station to:');
        if (!routeId) return;
        try {
            const response = await fetch(`${API_BASE}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');
        }
    }

    async function autoAssignHotspot(hotspotId) {
        try {
            const response = await fetch(`${API_BASE}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');
        }
    }

    function handleMapClick(e) {}

    function showMessage(message, type) {
        elements.responseMessage.textContent = message;
        elements.responseMessage.className = `response-message ${type}`;
        elements.responseMessage.style.display = 'block';
        setTimeout(() => { elements.responseMessage.style.display = 'none'; }, type === 'success' ? 5000 : 3000);
    }

    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    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 => {
            const matchesSearch = searchTerm === '' || geofence.name.toLowerCase().includes(searchTerm) || (geofence.description && geofence.description.toLowerCase().includes(searchTerm));
            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);
    }

    function openModal(modalId) {
        document.getElementById(modalId).style.display = 'flex';
    }

    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }

    function initApplication() {
        initEventListeners();
        updateColorValue();
        loadAllGeofences();
        loadRoutesForParentSelection();
        loadStationsForRouteAssignment();
        loadDevices();
        loadRoutesForAssignment();
        console.log('Enhanced Geofence & Route Management UI initialized with Google Maps');
    }

    // Make functions globally accessible for onclick handlers
    window.viewGeofenceDetails = viewGeofenceDetails;
    window.editGeofence = editGeofence;
    window.deleteGeofence = deleteGeofence;
    window.highlightGeofenceOnMap = highlightGeofenceOnMap;
    window.closeModal = closeModal;

    // Station assignment button
    document.getElementById('assignStationToRoutes').onclick = async () => {
        $("#assignStationToRoutes").html("Assigning... Please Wait!").prop("disabled", true);
        const stationId = $("#selectStation").val();
        const routeId = $("#selectPrRoute").val();
        if (!stationId || !routeId) {
            showMessage("Please select both station and route", "error");
            return;
        }
        try {
            const response = await fetch(`${API_BASE}geofences/routes/${routeId}/stations/${stationId}`, { method: 'POST' });
            if (response.ok) {
                showMessage("Station successfully assigned to route!", "success");
            } else {
                const data = await response.json();
                showMessage(`Error: ${data.message || response.statusText}`, "error");
            }
        } catch (error) {
            showMessage(`Error: ${error.message}`, "error");
            console.error("Fetch error:", error);
        } finally {
            setTimeout(() => {
                $("#assignStationToRoutes").html("Assign Station to Route").prop("disabled", false);
            }, 1000);
        }
    };

    // Hotspot assignment button
    document.getElementById('assignHotspotsToRoutes').onclick = async () => {
        $("#assignHotspotsToRoutes").html("Assigning... Please Wait!").prop("disabled", true);
        const hotspotsId = $("#selectShotspot").val();
        const routeId = $("#selectPrhtspotRoute").val();
        if (!hotspotsId || !routeId) {
            showMessage("Please select both hotspot and route", "error");
            return;
        }
        try {
            const response = await fetch(`${API_BASE}geofences/routes/${routeId}/hotspots/${hotspotsId}`, { method: 'POST' });
            if (response.ok) {
                showMessage("Hotspot successfully assigned to route!", "success");
            } else {
                const data = await response.json();
                showMessage(`Error: ${data.message || response.statusText}`, "error");
            }
        } catch (error) {
            showMessage(`Error: ${error.message}`, "error");
            console.error("Fetch error:", error);
        } finally {
            setTimeout(() => {
                $("#assignHotspotsToRoutes").html("Assign Hotspot to Route").prop("disabled", false);
            }, 1000);
        }
    };

    // Load dropdowns
    loadParentRoutes();
    function loadParentRoutes() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `${API_BASE}geofences/routes?size=500`, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                const contentdata = data.content || [];
                let option = '<option selected value="" >-Select Parent Route-</option>';
                for (let i = 0; i < contentdata.length; i++) {
                    option += `<option value="${contentdata[i].id}">${contentdata[i].name}</option>`;
                }
                $("#selectPrRoute").html(option);
                $("#selectPrhtspotRoute").html(option);
            }
        };
        xhr.send();
    }

    loadMystations();
    function loadMystations() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `${API_BASE}geofences/stations?size=1000`, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                const contentdata = data.content || [];
                let option = '<option selected value="" >-Select Station-</option>';
                for (let i = 0; i < contentdata.length; i++) {
                    option += `<option value="${contentdata[i].id}">${contentdata[i].name}</option>`;
                }
                $("#selectStation").html(option);
            }
        };
        xhr.send();
    }

    loadMyhostspots();
    function loadMyhostspots() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `${API_BASE}geofences/hotspots?size=1000`, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                const contentdata = data.content || [];
                let option = '<option selected value="" >-Select Hotspot-</option>';
                for (let i = 0; i < contentdata.length; i++) {
                    option += `<option value="${contentdata[i].id}">${contentdata[i].name}</option>`;
                }
                $("#selectShotspot").html(option);
            }
        };
        xhr.send();
    }

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