function allHotspots() {
    $(".crud_section").html("");

    /***************************************************
     * GLOBALS
     ***************************************************/
    let deviceMap = null;
    let geofenceHoverInfo = null;
    let geofenceInfoWindow = null;
    let heatmapLayer = null;
    let drawingManager = null;
    let drawingEnabled = false;
    let tempPolygon = null;
    let tempCircle = null;
    let tempPoints = [];

    let geofences = [];
    let hotspotShapes = [];
    let selectedHotspot = null;

    const HOTSPOT_COLORS = {
        DEFAULT: '#ef4444',
        SELECTED: '#000000',
        HOVER: '#f97316',
        ACTIVE: '#ef4444',
        INACTIVE: '#94a3b8',
        POLYGON: '#3b82f6'
    };

    /***************************************************
     * INIT
     ***************************************************/
    buildLayout();
    setTimeout(() => initMap(), 100);
    loadHotspots();

    /***************************************************
     * UI LAYOUT - MODERN DESIGN
     ***************************************************/
  function buildLayout() {
    const html = `
        <div class="hotspots-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            
            <!-- Header -->
            <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
                    <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-fire" style="color: #ef4444;"></i>
                        Hotspots Management
                    </h1>
                    <span class="hotspot-count" style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                        Loading...
                    </span>
                </div>
                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    <button onclick="toggleHotspotList()" class="btn-outline" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-list"></i>
                        <span>Show List</span>
                    </button>
                    <button onclick="fitAllHotspots()" class="btn-outline" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-expand-arrows-alt"></i>
                        <span>Fit All</span>
                    </button>
                    <button onclick="toggleHeatmap()" class="btn-outline" id="heatmapBtn" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-fire"></i>
                        <span>Heatmap</span>
                    </button>
                </div>
            </div>

            <!-- Stats Cards -->
            <div class="stats-grid" style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #fee2e2; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                        <i class="fas fa-fire" style="font-size: 20px; color: #ef4444;"></i>
                    </div>
                    <div style="min-width: 0;">
                        <div style="font-size: 13px; color: #5b677c;">Total Hotspots</div>
                        <div class="stat-value" id="totalHotspots" style="font-size: 24px; font-weight: 700; color: #1a1f36;">0</div>
                    </div>
                </div>
                
                <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #fee2e2; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                        <i class="fas fa-circle" style="font-size: 20px; color: #ef4444;"></i>
                    </div>
                    <div style="min-width: 0;">
                        <div style="font-size: 13px; color: #5b677c;">Circle Hotspots</div>
                        <div class="stat-value" id="circleHotspots" style="font-size: 24px; font-weight: 700; color: #ef4444;">0</div>
                    </div>
                </div>
                
                <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #dbeafe; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                        <i class="fas fa-draw-polygon" style="font-size: 20px; color: #3b82f6;"></i>
                    </div>
                    <div style="min-width: 0;">
                        <div style="font-size: 13px; color: #5b677c;">Polygon Hotspots</div>
                        <div class="stat-value" id="polygonHotspots" style="font-size: 24px; font-weight: 700; color: #3b82f6;">0</div>
                    </div>
                </div>
                
                <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #f3e8ff; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                        <i class="fas fa-chart-line" style="font-size: 20px; color: #a855f7;"></i>
                    </div>
                    <div style="min-width: 0;">
                        <div style="font-size: 13px; color: #5b677c;">Risk Score</div>
                        <div class="stat-value" id="avgRiskScore" style="font-size: 24px; font-weight: 700; color: #a855f7;">0</div>
                    </div>
                </div>
            </div>


            <!-- Main Content: Map and Side Panel -->
            <div class="main-content" style="display: grid; gap: 20px; min-height: 800px;">
                <!-- Map Container -->
                <div class="map-container" style="flex: 2; position: relative; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden; min-height: 400px;">
                    <div id="all_hotspots_map" style="height: 100%; width: 100%;"></div>
                    
                    <!-- Map Controls Overlay -->
                    <div style="position: absolute; top: 16px; right: 16px; z-index: 10; display: flex; flex-direction: column; gap: 8px;">
                        <button onclick="zoomIn()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                            <i class="fas fa-plus"></i>
                        </button>
                        <button onclick="zoomOut()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                            <i class="fas fa-minus"></i>
                        </button>
                        <button onclick="fitAllHotspots()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                            <i class="fas fa-expand"></i>
                        </button>
                        <button onclick="toggleDrawingMode()" id="drawBtn" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                            <i class="fas fa-pencil-alt"></i>
                        </button>
                    </div>
                    
                    <!-- Coordinates Display -->
                    <div class="coords-display" style="position: absolute; bottom: 16px; left: 16px; z-index: 10; background: rgba(255,255,255,0.9); padding: 8px 16px; border-radius: 40px; border: 1px solid #eaeef2; font-size: 12px; color: #5b677c; max-width: calc(100% - 32px); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                        <span id="mouseCoordinates">Hover on map to see coordinates</span>
                    </div>
                    
                    <!-- Risk Legend -->
                    <div style="position: absolute; bottom: 16px; right: 16px; z-index: 10; background: white; padding: 12px; border-radius: 12px; border: 1px solid #eaeef2; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                        <div style="font-size: 12px; font-weight: 600; margin-bottom: 8px; color: #1a1f36;">Risk Levels</div>
                        <div style="display: flex; flex-direction: column; gap: 4px;">
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <span style="width: 12px; height: 12px; background: #ef4444; border-radius: 3px;"></span>
                                <span style="font-size: 11px; color: #5b677c;">High Risk</span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <span style="width: 12px; height: 12px; background: #f97316; border-radius: 3px;"></span>
                                <span style="font-size: 11px; color: #5b677c;">Medium Risk</span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <span style="width: 12px; height: 12px; background: #3b82f6; border-radius: 3px;"></span>
                                <span style="font-size: 11px; color: #5b677c;">Low Risk</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Side Panel - Hotspot List -->
                <div id="hotspotListPanel" class="side-panel" style="flex: 1; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden; display: flex; flex-direction: column; min-width: 280px;">
                    <div style="padding: 16px; border-bottom: 1px solid #eaeef2; background: #f8fafc;">
                        <h3 style="margin: 0; font-size: 16px; color: #1a1f36; display: flex; align-items: center; gap: 8px;">
                            <i class="fas fa-fire"></i>
                            Hotspots List
                        </h3>
                    </div>
                    
                    <div id="hotspotsList" style="flex: 1; overflow-y: auto; padding: 12px;">
                        <div style="text-align: center; color: #94a3b8; padding: 40px;">
                            <i class="fas fa-spinner fa-spin" style="font-size: 24px; margin-bottom: 12px;"></i>
                            <div>Loading hotspots...</div>
                        </div>
                    </div>
                    
                    <div style="padding: 12px; border-top: 1px solid #eaeef2; background: #f8fafc;">
                        <button onclick="exportHotspots()" style="width: 100%; padding: 10px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-download"></i> Export Hotspots Data
                        </button>
                    </div>
                </div>
            </div>

            <!-- Selected Hotspot Details Panel -->
            <div id="selectedHotspotPanel" style="display: none; margin-top: 20px; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;"></div>

            <style>
                .stat-card {
                    transition: transform 0.2s, box-shadow 0.2s;
                }
                .stat-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 8px 16px rgba(0,0,0,0.05);
                }
                
                .hotspot-list-item {
                    padding: 12px;
                    border-bottom: 1px solid #eaeef2;
                    cursor: pointer;
                    transition: all 0.2s;
                }
                .hotspot-list-item:hover { background: #fff5f5; }
                .hotspot-list-item.selected {
                    background: #fee2e2;
                    border-left: 3px solid #ef4444;
                }
                
                .risk-badge {
                    display: inline-block;
                    padding: 2px 8px;
                    border-radius: 12px;
                    font-size: 10px;
                    font-weight: 600;
                }
                .risk-high { background: #fee2e2; color: #ef4444; }
                .risk-medium { background: #fff3e0; color: #f97316; }
                .risk-low { background: #dbeafe; color: #3b82f6; }
                
                #hotspotsList::-webkit-scrollbar {
                    width: 6px;
                }
                #hotspotsList::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }
                #hotspotsList::-webkit-scrollbar-thumb {
                    background: #cbd5e1;
                    border-radius: 10px;
                }
                
                .drawing-active {
                    background: #ef4444 !important;
                    color: white !important;
                }
                
                /* Responsive Breakpoints */
                @media (max-width: 1200px) {
                    .hotspots-container {
                        padding: 16px !important;
                    }
                }
                
               
                
                @media (max-width: 768px) {
                    .stats-grid {
                        grid-template-columns: 1fr !important;
                    }
                    .stat-card {
                        padding: 16px !important;
                    }
                    .stat-card div:first-child {
                        width: 40px !important;
                        height: 40px !important;
                    }
                    .stat-value {
                        font-size: 20px !important;
                    }
                }
                
                @media (max-width: 600px) {
                    .map-container {
                        min-height: 350px !important;
                    }
                    .map-container > div:first-of-type { /* map controls */
                        top: 8px !important;
                        right: 8px !important;
                    }
                    .map-container button {
                        width: 36px !important;
                        height: 36px !important;
                    }
                    .coords-display {
                        bottom: 8px !important;
                        left: 8px !important;
                        padding: 4px 10px !important;
                        font-size: 11px !important;
                    }
                    .map-container > div:last-of-type { /* legend */
                        bottom: 8px !important;
                        right: 8px !important;
                        padding: 8px !important;
                    }
                }
                
                @media (max-width: 480px) {
                    .hotspots-container {
                        padding: 8px !important;
                    }
                    h1 {
                        font-size: 22px !important;
                    }
                    .hotspot-count {
                        font-size: 12px !important;
                        padding: 4px 10px !important;
                    }
                    .btn-outline {
                        padding: 8px 12px !important;
                        font-size: 13px !important;
                    }
                    .search-filter {
                        flex-direction: column;
                        align-items: stretch !important;
                    }
                    .search-filter > div {
                        width: 100% !important;
                    }
                    input, select {
                        width: 100% !important;
                    }
                    .side-panel {
                        margin-top: 12px;
                    }
                }
            </style>
        </div>
    `;

    $(".tab_hotspots").html(html);
}
    /***************************************************
     * MAP INIT
     ***************************************************/
    function initMap() {
        const mapElement = document.getElementById("all_hotspots_map");
        if (!mapElement) return;

        deviceMap = new google.maps.Map(mapElement, {
            zoom: 7,
            center: { lat: 11.5721, lng: 43.1456 },
            gestureHandling: "greedy",
            mapTypeControl: true,
            fullscreenControl: true,
            streetViewControl: true,
            zoomControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            styles: [
                {
                    featureType: "poi",
                    elementType: "labels",
                    stylers: [{ visibility: "off" }]
                },
                {
                    featureType: "transit",
                    elementType: "labels",
                    stylers: [{ visibility: "off" }]
                }
            ]
        });

        // Initialize info windows
        geofenceHoverInfo = new google.maps.InfoWindow({
            disableAutoPan: true,
            pixelOffset: new google.maps.Size(0, -10)
        });

        geofenceInfoWindow = new google.maps.InfoWindow({
            maxWidth: 350
        });

        // Add mouse move listener
        deviceMap.addListener('mousemove', function(e) {
            const lat = e.latLng.lat().toFixed(6);
            const lng = e.latLng.lng().toFixed(6);
            $('#mouseCoordinates').html(`Lat: ${lat}, Lng: ${lng}`);
        });

        // Try to initialize drawing manager if available
        if (google.maps.drawing) {
            initDrawingManager();
        } else {
            console.warn("Google Maps Drawing library not loaded. Using manual drawing mode.");
            // Set up manual drawing listeners
            setupManualDrawing();
        }
    }

    /***************************************************
     * MANUAL DRAWING (Fallback when DrawingManager not available)
     ***************************************************/
    function setupManualDrawing() {
        let drawingType = null;
        
        window.toggleDrawingMode = function() {
            if (drawingType) {
                // Turn off drawing
                drawingType = null;
                $('#drawBtn').removeClass('drawing-active');
                $('#drawingInstructions').hide();
                tempPoints = [];
                if (tempPolygon) {
                    tempPolygon.setMap(null);
                    tempPolygon = null;
                }
                if (tempCircle) {
                    tempCircle.setMap(null);
                    tempCircle = null;
                }
                google.maps.event.clearListeners(deviceMap, 'click');
                google.maps.event.clearListeners(deviceMap, 'rightclick');
            } else {
                // Show drawing mode selection
                Swal.fire({
                    title: 'Select Drawing Mode',
                    text: 'Choose the type of hotspot to draw',
                    icon: 'question',
                    showCancelButton: true,
                    showDenyButton: true,
                    confirmButtonText: 'Circle',
                    denyButtonText: 'Polygon',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        drawingType = 'circle';
                        startManualCircleDrawing();
                    } else if (result.isDenied) {
                        drawingType = 'polygon';
                        startManualPolygonDrawing();
                    }
                });
            }
        };

        function startManualPolygonDrawing() {
            $('#drawBtn').addClass('drawing-active');
            $('#drawingInstructions').show();
            tempPoints = [];
            
            // Create temporary polygon for preview
            tempPolygon = new google.maps.Polygon({
                map: deviceMap,
                paths: [],
                fillColor: HOTSPOT_COLORS.POLYGON,
                fillOpacity: 0.35,
                strokeColor: HOTSPOT_COLORS.POLYGON,
                strokeWeight: 2,
                editable: false,
                draggable: false
            });

            // Add click listener
            deviceMap.addListener('click', function(e) {
                tempPoints.push({ lat: e.latLng.lat(), lng: e.latLng.lng() });
                
                // Add temporary marker
                new google.maps.Marker({
                    position: e.latLng,
                    map: deviceMap,
                    icon: {
                        path: google.maps.SymbolPath.CIRCLE,
                        scale: 6,
                        fillColor: HOTSPOT_COLORS.POLYGON,
                        fillOpacity: 1,
                        strokeColor: '#ffffff',
                        strokeWeight: 2
                    },
                    label: tempPoints.length.toString()
                });

                // Update polygon
                tempPolygon.setPaths(tempPoints);
            });

            // Add right-click listener to finish
            deviceMap.addListener('rightclick', function() {
                if (tempPoints.length >= 3) {
                    finishManualDrawing('polygon', tempPoints);
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: 'Polygon needs at least 3 points',
                        icon: 'error',
                        timer: 2000
                    });
                }
            });
        }

        function startManualCircleDrawing() {
            $('#drawBtn').addClass('drawing-active');
            $('#drawingInstructions').text('Click to set center, then click again to set radius');
            $('#drawingInstructions').show();
            tempPoints = [];

            deviceMap.addListener('click', function(e) {
                if (tempPoints.length === 0) {
                    // First click - set center
                    tempPoints.push({ lat: e.latLng.lat(), lng: e.latLng.lng() });
                    
                    // Add center marker
                    new google.maps.Marker({
                        position: e.latLng,
                        map: deviceMap,
                        icon: {
                            path: google.maps.SymbolPath.CIRCLE,
                            scale: 8,
                            fillColor: HOTSPOT_COLORS.DEFAULT,
                            fillOpacity: 1,
                            strokeColor: '#ffffff',
                            strokeWeight: 2
                        },
                        label: 'C'
                    });
                } else if (tempPoints.length === 1) {
                    // Second click - calculate radius
                    const center = tempPoints[0];
                    const radius = google.maps.geometry.spherical.computeDistanceBetween(
                        new google.maps.LatLng(center.lat, center.lng),
                        e.latLng
                    );
                    
                    finishManualDrawing('circle', {
                        center: center,
                        radius: radius
                    });
                }
            });
        }

        function finishManualDrawing(type, data) {
            // Remove temporary shapes
            if (tempPolygon) {
                tempPolygon.setMap(null);
                tempPolygon = null;
            }
            
            // Clear listeners
            google.maps.event.clearListeners(deviceMap, 'click');
            google.maps.event.clearListeners(deviceMap, 'rightclick');
            
            // Hide drawing UI
            $('#drawBtn').removeClass('drawing-active');
            $('#drawingInstructions').hide();
            
            // Show save dialog
            showSaveHotspotDialog(type, data);
            
            drawingType = null;
            tempPoints = [];
        }
    }

    /***************************************************
     * DRAWING MANAGER (if library available)
     ***************************************************/
    function initDrawingManager() {
        if (!deviceMap || !google.maps.drawing) return;
        
        try {
            drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: null,
                drawingControl: false,
                circleOptions: {
                    fillColor: HOTSPOT_COLORS.DEFAULT,
                    fillOpacity: 0.35,
                    strokeWeight: 2,
                    strokeColor: HOTSPOT_COLORS.DEFAULT,
                    clickable: true,
                    editable: true,
                    zIndex: 1
                },
                polygonOptions: {
                    fillColor: HOTSPOT_COLORS.POLYGON,
                    fillOpacity: 0.35,
                    strokeWeight: 2,
                    strokeColor: HOTSPOT_COLORS.POLYGON,
                    clickable: true,
                    editable: true,
                    zIndex: 1
                }
            });

            drawingManager.setMap(deviceMap);

            // Add drawing listeners
            google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
                // Switch off drawing mode
                drawingManager.setDrawingMode(null);
                $('#drawBtn').removeClass('drawing-active');
                $('#drawingInstructions').hide();
                
                // Get coordinates
                let coordinates = [];
                if (event.type === 'circle') {
                    const center = event.overlay.getCenter();
                    coordinates = {
                        center: { lat: center.lat(), lng: center.lng() },
                        radius: event.overlay.getRadius()
                    };
                } else if (event.type === 'polygon') {
                    const path = event.overlay.getPath();
                    coordinates = [];
                    path.forEach(latLng => {
                        coordinates.push({ lat: latLng.lat(), lng: latLng.lng() });
                    });
                }
                
                // Show save dialog
                showSaveHotspotDialog(event.type, coordinates);
                
                // Remove the temporary shape
                event.overlay.setMap(null);
            });

            window.toggleDrawingMode = function() {
                if (!drawingManager) return;
                
                if (drawingManager.getDrawingMode()) {
                    drawingManager.setDrawingMode(null);
                    $('#drawBtn').removeClass('drawing-active');
                    $('#drawingInstructions').hide();
                } else {
                    // Show drawing mode selection
                    Swal.fire({
                        title: 'Select Drawing Mode',
                        text: 'Choose the type of hotspot to draw',
                        icon: 'question',
                        showCancelButton: true,
                        showDenyButton: true,
                        confirmButtonText: 'Circle',
                        denyButtonText: 'Polygon',
                        cancelButtonText: 'Cancel'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.CIRCLE);
                            $('#drawBtn').addClass('drawing-active');
                            $('#drawingInstructions').text('Click and drag to draw a circle').show();
                        } else if (result.isDenied) {
                            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
                            $('#drawBtn').addClass('drawing-active');
                            $('#drawingInstructions').text('Click to add points. Double-click to finish').show();
                        }
                    });
                }
            };
        } catch (e) {
            console.error("Error initializing drawing manager:", e);
            setupManualDrawing();
        }
    }

    /***************************************************
     * LOAD HOTSPOTS
     ***************************************************/
    function loadHotspots() {
        controller.getAuthRequest(
            serverURL + "geofences/hotspots?size=1000",
            true,
            res => {
                geofences = res?.content || [];
                
                // Update stats
                updateStats(geofences);
                
                // Draw hotspots on map
                drawHotspotsOnly();
                
                // Populate hotspots list
                populateHotspotsList(geofences);
                
                // Update hotspot count badge
                $('.hotspot-count').text(`${geofences.length} Hotspots`);
            },
            error => {
                console.error("Error loading hotspots:", error);
                $("#hotspotsList").html(`
                    <div style="text-align: center; color: #dc2626; padding: 40px;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 32px; margin-bottom: 12px;"></i>
                        <div>Failed to load hotspots</div>
                        <button onclick="loadHotspots()" style="margin-top: 16px; padding: 8px 16px; background: #000; color: white; border: none; border-radius: 8px; cursor: pointer;">
                            Retry
                        </button>
                    </div>
                `);
            }
        );
    }

    /***************************************************
     * UPDATE STATISTICS
     ***************************************************/
    function updateStats(hotspots) {
        const total = hotspots.length;
        const circleHotspots = hotspots.filter(s => s.fenceType === "CIRCLE").length;
        const polygonHotspots = hotspots.filter(s => s.fenceType === "POLYGON").length;
        
        // Calculate average risk score (mock for demo)
        const avgRisk = calculateAverageRisk(hotspots);

        animateNumber('#totalHotspots', total);
        animateNumber('#circleHotspots', circleHotspots);
        animateNumber('#polygonHotspots', polygonHotspots);
        animateNumber('#avgRiskScore', avgRisk);
    }

    function calculateAverageRisk(hotspots) {
        const riskScores = hotspots.map(() => Math.floor(Math.random() * 100));
        const avg = riskScores.reduce((a, b) => a + b, 0) / riskScores.length;
        return Math.round(avg) || 0;
    }

    function animateNumber(selector, target) {
        const element = $(selector);
        const current = parseInt(element.text()) || 0;
        const increment = (target - current) / 20;
        let step = 0;

        const interval = setInterval(() => {
            step++;
            const value = Math.round(current + (increment * step));
            element.text(value);
            
            if (step >= 20) {
                element.text(target);
                clearInterval(interval);
            }
        }, 20);
    }

    /***************************************************
     * POPULATE HOTSPOTS LIST
     ***************************************************/
    function populateHotspotsList(hotspots) {
        const $list = $("#hotspotsList");
        $list.empty();

        hotspots.sort((a, b) => a.name.localeCompare(b.name));

        hotspots.forEach(hotspot => {
            const typeIcon = hotspot.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
            const typeColor = hotspot.fenceType === 'CIRCLE' ? HOTSPOT_COLORS.DEFAULT : HOTSPOT_COLORS.POLYGON;
            const riskLevel = calculateRiskLevel(hotspot);
            const riskClass = `risk-${riskLevel.toLowerCase()}`;

            $list.append(`
                <div class="hotspot-list-item" data-id="${hotspot.id}" onclick="selectHotspot('${hotspot.id}')">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 36px; height: 36px; background: ${typeColor}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="color: ${typeColor};"></i>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #1a1f36;">${hotspot.name}</div>
                            <div style="font-size: 11px; color: #5b677c; display: flex; gap: 8px; margin-top: 4px;">
                                <span><i class="fas fa-chart-line"></i> Risk: <span class="risk-badge ${riskClass}">${riskLevel}</span></span>
                                <span><i class="fas fa-clock"></i> ${formatDate(hotspot.updatedAt)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `);
        });

        $("#hotspotSearch").on("keyup", function() {
            const searchTerm = $(this).val().toLowerCase();
            $('.hotspot-list-item').each(function() {
                const name = $(this).text().toLowerCase();
                $(this).toggle(name.includes(searchTerm));
            });
        });

        $("#hotspotTypeFilter, #riskFilter").on("change", function() {
            filterHotspots();
        });
    }

    function calculateRiskLevel(hotspot) {
        const mockScore = Math.random() * 100;
        if (mockScore > 66) return 'High';
        if (mockScore > 33) return 'Medium';
        return 'Low';
    }

    function filterHotspots() {
        const typeFilter = $("#hotspotTypeFilter").val();
        const riskFilter = $("#riskFilter").val();
        
        $('.hotspot-list-item').each(function() {
            const $item = $(this);
            const type = $item.find('.fas').hasClass('fa-circle') ? 'circle' : 'polygon';
            const riskText = $item.find('.risk-badge').text();
            
            let showByType = typeFilter === 'all' || type === typeFilter;
            let showByRisk = riskFilter === 'all' || riskText.toLowerCase() === riskFilter;
            
            $item.toggle(showByType && showByRisk);
        });
    }

    /***************************************************
     * DRAW HOTSPOTS
     ***************************************************/
    function drawHotspotsOnly() {
        hotspotShapes.forEach(s => {
            if (s) s.setMap(null);
        });
        hotspotShapes = [];

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

        geofences.forEach(f => {
            if (!f.hotspot) return;

            if (f.fenceType === "CIRCLE" && f.centerLat && f.centerLng && f.radiusMeters) {
                const circle = new google.maps.Circle({
                    map: deviceMap,
                    center: { lat: f.centerLat, lng: f.centerLng },
                    radius: f.radiusMeters,
                    fillColor: f.colorHex || HOTSPOT_COLORS.DEFAULT,
                    fillOpacity: 0.25,
                    strokeColor: f.colorHex || HOTSPOT_COLORS.DEFAULT,
                    strokeWeight: 2,
                    strokeOpacity: 0.8,
                    clickable: true,
                    zIndex: 1,
                    metadata: f
                });

                circle.metadata = f;
                attachHotspotEvents(circle, 'circle');
                hotspotShapes.push(circle);
                bounds.extend(circle.getCenter());
                hasBounds = true;
            }

            if (f.fenceType === "POLYGON" && f.coordinatesJson) {
                try {
                    let path = JSON.parse(f.coordinatesJson);
                    
                    if (path.length > 0 && Array.isArray(path[0]) && path[0].length === 2) {
                        path = path.map(coord => ({
                            lat: coord[1],
                            lng: coord[0]
                        }));
                    }

                    const polygon = new google.maps.Polygon({
                        map: deviceMap,
                        paths: path,
                        fillColor: f.colorHex || HOTSPOT_COLORS.POLYGON,
                        fillOpacity: 0.25,
                        strokeColor: f.colorHex || HOTSPOT_COLORS.POLYGON,
                        strokeWeight: 2,
                        strokeOpacity: 0.8,
                        clickable: true,
                        zIndex: 1,
                        metadata: f
                    });

                    polygon.metadata = f;
                    attachHotspotEvents(polygon, 'polygon');
                    hotspotShapes.push(polygon);
                    path.forEach(p => bounds.extend(p));
                    hasBounds = true;
                } catch (e) {
                    console.error("Invalid hotspot polygon:", f.name, e);
                }
            }
        });

        if (hasBounds && deviceMap) {
            deviceMap.fitBounds(bounds);
        }
    }

    /***************************************************
     * HOTSPOT EVENTS
     ***************************************************/
    function attachHotspotEvents(shape, type) {
        const originalStyle = {
            fillOpacity: 0.25,
            strokeWeight: 2,
            strokeOpacity: 0.8
        };

        const hoverStyle = {
            fillOpacity: 0.45,
            strokeWeight: 3,
            strokeOpacity: 1,
            zIndex: 10
        };

        shape.addListener("mouseover", (e) => {
            shape.setOptions(hoverStyle);
            const position = type === 'circle' ? shape.getCenter() : e.latLng;
            geofenceHoverInfo.setContent(buildHotspotInfoCard(shape.metadata, 'hover'));
            geofenceHoverInfo.setPosition(position);
            geofenceHoverInfo.open(deviceMap);
        });

        shape.addListener("mouseout", () => {
            shape.setOptions(originalStyle);
            geofenceHoverInfo.close();
        });

        shape.addListener("click", (e) => {
            geofenceInfoWindow.close();
            const position = type === 'circle' ? shape.getCenter() : e.latLng;
            geofenceInfoWindow.setContent(buildHotspotInfoCard(shape.metadata, 'detailed'));
            geofenceInfoWindow.setPosition(position);
            geofenceInfoWindow.open(deviceMap);
            highlightHotspot(shape.metadata.id);
            showHotspotDetails(shape.metadata);
        });

        shape.addListener("rightclick", () => {
            if (type === 'circle') {
                deviceMap.panTo(shape.getCenter());
                deviceMap.setZoom(16);
            } else {
                const bounds = new google.maps.LatLngBounds();
                shape.getPath().forEach(p => bounds.extend(p));
                deviceMap.fitBounds(bounds);
            }
        });
    }

    /***************************************************
     * HOTSPOT INFO CARD
     ***************************************************/
    function buildHotspotInfoCard(hotspot, type = 'hover') {
        const typeIcon = hotspot.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
        const typeColor = hotspot.fenceType === 'CIRCLE' ? HOTSPOT_COLORS.DEFAULT : HOTSPOT_COLORS.POLYGON;
        const riskLevel = calculateRiskLevel(hotspot);
        const riskClass = `risk-${riskLevel.toLowerCase()}`;
        
        if (type === 'hover') {
            return `
                <div style="padding: 8px; min-width: 200px;">
                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                        <div style="width: 30px; height: 30px; background: ${typeColor}20; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="color: ${typeColor};"></i>
                        </div>
                        <div style="font-weight: 600; color: #1a1f36;">${hotspot.name}</div>
                    </div>
                    ${hotspot.description ? `<div style="font-size: 12px; color: #5b677c; margin-bottom: 4px;">${hotspot.description}</div>` : ''}
                    <div style="display: flex; gap: 8px; margin-top: 4px;">
                        <span class="risk-badge ${riskClass}">${riskLevel} Risk</span>
                        <span style="font-size: 11px; color: #94a3b8;">
                            <i class="fas fa-route"></i> ${hotspot.assignedRouteIds?.length || 0} routes
                        </span>
                    </div>
                </div>
            `;
        } else {
            const area = calculateArea(hotspot);
            
            return `
                <div style="padding: 12px; min-width: 300px;">
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
                        <div style="width: 40px; height: 40px; background: ${typeColor}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="font-size: 18px; color: ${typeColor};"></i>
                        </div>
                        <div>
                            <div style="font-weight: 600; font-size: 16px; color: #1a1f36;">${hotspot.name}</div>
                            <div style="font-size: 12px; color: #5b677c;">${hotspot.fenceType} Hotspot</div>
                        </div>
                    </div>
                    
                    <div style="border-top: 1px solid #eaeef2; padding-top: 12px;">
                        ${hotspot.description ? `
                            <div style="margin-bottom: 8px;">
                                <div style="font-size: 11px; color: #94a3b8;">Description</div>
                                <div style="font-size: 13px; color: #1a1f36;">${hotspot.description}</div>
                            </div>
                        ` : ''}
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Risk Level</div>
                                <div><span class="risk-badge ${riskClass}">${riskLevel}</span></div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Area</div>
                                <div style="font-size: 12px; color: #1a1f36;">${area}</div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Created</div>
                                <div style="font-size: 12px; color: #1a1f36;">${formatDate(hotspot.createdAt)}</div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Updated</div>
                                <div style="font-size: 12px; color: #1a1f36;">${formatDate(hotspot.updatedAt)}</div>
                            </div>
                        </div>
                        
                        ${hotspot.assignedRouteIds?.length ? `
                            <div style="margin-top: 8px;">
                                <div style="font-size: 11px; color: #94a3b8;">Connected Routes</div>
                                <div style="display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px;">
                                    ${hotspot.assignedRouteIds.map(routeId => `
                                        <span style="background: #f0f2f5; padding: 2px 8px; border-radius: 12px; font-size: 11px; color: #1a1f36;">
                                            ${routeId}
                                        </span>
                                    `).join('')}
                                </div>
                            </div>
                        ` : ''}
                        
                        <div style="display: flex; gap: 8px; margin-top: 16px;">
                            <button onclick="editHotspot('${hotspot.id}')" style="flex: 1; padding: 8px; background: #000; color: white; border: none; border-radius: 8px; font-size: 12px; cursor: pointer;">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button onclick="viewHotspotAlerts('${hotspot.id}')" style="flex: 1; padding: 8px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 8px; font-size: 12px; cursor: pointer;">
                                <i class="fas fa-bell"></i> Alerts
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    function calculateArea(hotspot) {
        if (hotspot.fenceType === 'CIRCLE' && hotspot.radiusMeters) {
            const areaKm2 = (Math.PI * Math.pow(hotspot.radiusMeters, 2) / 1000000).toFixed(2);
            return areaKm2 + ' km²';
        }
        return 'N/A';
    }

    /***************************************************
     * HIGHLIGHT HOTSPOT
     ***************************************************/
    function highlightHotspot(hotspotId) {
        hotspotShapes.forEach(shape => {
            shape.setOptions({
                fillOpacity: 0.25,
                strokeWeight: 2,
                zIndex: 1
            });
        });

        const selectedShape = hotspotShapes.find(s => s.metadata.id === hotspotId);
        if (selectedShape) {
            selectedShape.setOptions({
                fillOpacity: 0.5,
                strokeWeight: 4,
                strokeColor: '#000000',
                zIndex: 100
            });
        }

        $('.hotspot-list-item').removeClass('selected');
        $(`.hotspot-list-item[data-id="${hotspotId}"]`).addClass('selected');
    }

    /***************************************************
     * SHOW HOTSPOT DETAILS
     ***************************************************/
    function showHotspotDetails(hotspot) {
        const typeIcon = hotspot.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
        const typeColor = hotspot.fenceType === 'CIRCLE' ? HOTSPOT_COLORS.DEFAULT : HOTSPOT_COLORS.POLYGON;
        const riskLevel = calculateRiskLevel(hotspot);
        const riskClass = `risk-${riskLevel.toLowerCase()}`;
        const area = calculateArea(hotspot);
        
        const detailsHtml = `
            <div style="padding: 24px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0; display: flex; align-items: center; gap: 12px;">
                        <i class="fas ${typeIcon}" style="color: ${typeColor};"></i>
                        ${hotspot.name}
                    </h3>
                    <button onclick="hideHotspotDetails()" style="background: none; border: none; cursor: pointer;">
                        <i class="fas fa-times" style="color: #94a3b8;"></i>
                    </button>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 20px;">
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Type</div>
                        <div style="font-weight: 600; color: #1a1f36;">${hotspot.fenceType}</div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Risk Level</div>
                        <div><span class="risk-badge ${riskClass}">${riskLevel}</span></div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Area</div>
                        <div style="font-weight: 600; color: #1a1f36;">${area}</div>
                    </div>
                </div>
                
                ${hotspot.description ? `
                    <div style="margin-bottom: 20px;">
                        <div style="font-size: 12px; color: #94a3b8; margin-bottom: 4px;">Description</div>
                        <div style="background: #f8fafc; padding: 12px; border-radius: 12px; color: #1a1f36;">
                            ${hotspot.description}
                        </div>
                    </div>
                ` : ''}
                
                <div style="display: flex; gap: 12px;">
                    <button onclick="editHotspot('${hotspot.id}')" style="flex: 1; padding: 12px; background: #000; color: white; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-edit"></i> Edit Hotspot
                    </button>
                    <button onclick="deleteHotspot('${hotspot.id}')" style="flex: 1; padding: 12px; background: #fee2e2; color: #ef4444; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        `;
        
        $('#selectedHotspotPanel').html(detailsHtml).slideDown();
    }

    /***************************************************
     * UTILITY FUNCTIONS
     ***************************************************/
    window.zoomIn = function() {
        if (deviceMap) deviceMap.setZoom(deviceMap.getZoom() + 1);
    };

    window.zoomOut = function() {
        if (deviceMap) deviceMap.setZoom(deviceMap.getZoom() - 1);
    };

    window.fitAllHotspots = function() {
        if (!deviceMap || hotspotShapes.length === 0) return;
        
        const bounds = new google.maps.LatLngBounds();
        hotspotShapes.forEach(shape => {
            if (shape instanceof google.maps.Circle) {
                bounds.extend(shape.getCenter());
                for (let i = 0; i < 8; i++) {
                    const angle = (i * 45) * Math.PI / 180;
                    const point = new google.maps.LatLng(
                        shape.getCenter().lat() + (shape.getRadius() / 111000) * Math.cos(angle),
                        shape.getCenter().lng() + (shape.getRadius() / (111000 * Math.cos(shape.getCenter().lat() * Math.PI/180))) * Math.sin(angle)
                    );
                    bounds.extend(point);
                }
            } else if (shape instanceof google.maps.Polygon) {
                shape.getPath().forEach(p => bounds.extend(p));
            }
        });
        deviceMap.fitBounds(bounds);
    };

    window.selectHotspot = function(hotspotId) {
        const hotspot = geofences.find(s => s.id == hotspotId);
        if (hotspot) {
            highlightHotspot(hotspotId);
            showHotspotDetails(hotspot);
            
            const shape = hotspotShapes.find(s => s.metadata.id == hotspotId);
            if (shape) {
                if (shape instanceof google.maps.Circle) {
                    deviceMap.panTo(shape.getCenter());
                    deviceMap.setZoom(16);
                } else {
                    const bounds = new google.maps.LatLngBounds();
                    shape.getPath().forEach(p => bounds.extend(p));
                    deviceMap.fitBounds(bounds);
                }
            }
        }
    };

    window.hideHotspotDetails = function() {
        $('#selectedHotspotPanel').slideUp();
    };

    window.toggleHotspotList = function() {
        $('#hotspotListPanel').toggleClass('collapsed');
    };

    window.toggleHeatmap = function() {
        if (heatmapLayer) {
            heatmapLayer.setMap(null);
            heatmapLayer = null;
            $('#heatmapBtn').removeClass('active');
        } else {
            const heatmapData = hotspotShapes.map(shape => {
                const riskLevel = calculateRiskLevel(shape.metadata);
                let weight = 1;
                if (riskLevel === 'High') weight = 3;
                else if (riskLevel === 'Medium') weight = 2;
                
                if (shape instanceof google.maps.Circle) {
                    return {
                        location: shape.getCenter(),
                        weight: weight
                    };
                } else {
                    const bounds = new google.maps.LatLngBounds();
                    shape.getPath().forEach(p => bounds.extend(p));
                    return {
                        location: bounds.getCenter(),
                        weight: weight
                    };
                }
            });
            
            heatmapLayer = new google.maps.visualization.HeatmapLayer({
                data: heatmapData,
                map: deviceMap,
                radius: 40,
                opacity: 0.6,
                gradient: [
                    'rgba(0, 255, 255, 0)',
                    'rgba(59, 130, 246, 1)',
                    'rgba(249, 115, 22, 1)',
                    'rgba(239, 68, 68, 1)',
                    'rgba(220, 38, 38, 1)'
                ]
            });
            $('#heatmapBtn').addClass('active');
        }
    };

    window.cancelDrawing = function() {
        if (drawingManager) {
            drawingManager.setDrawingMode(null);
        }
        $('#drawBtn').removeClass('drawing-active');
        $('#drawingInstructions').hide();
        if (tempPolygon) {
            tempPolygon.setMap(null);
            tempPolygon = null;
        }
        if (tempCircle) {
            tempCircle.setMap(null);
            tempCircle = null;
        }
        tempPoints = [];
        google.maps.event.clearListeners(deviceMap, 'click');
        google.maps.event.clearListeners(deviceMap, 'rightclick');
    };

    function showSaveHotspotDialog(type, coordinates) {
        Swal.fire({
            title: 'Save New Hotspot',
            html: `
                <input id="hotspotName" class="swal2-input" placeholder="Hotspot Name">
                <textarea id="hotspotDesc" class="swal2-textarea" placeholder="Description"></textarea>
                <select id="hotspotRisk" class="swal2-select">
                    <option value="Low">Low Risk</option>
                    <option value="Medium">Medium Risk</option>
                    <option value="High">High Risk</option>
                </select>
            `,
            showCancelButton: true,
            confirmButtonText: 'Save',
            preConfirm: () => {
                const name = document.getElementById('hotspotName').value;
                const desc = document.getElementById('hotspotDesc').value;
                const risk = document.getElementById('hotspotRisk').value;
                
                if (!name) {
                    Swal.showValidationMessage('Please enter a name');
                    return false;
                }
                
                return { name, desc, risk, type, coordinates };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                console.log('New hotspot:', result.value);
                Swal.fire({
                    title: 'Success!',
                    text: 'Hotspot created successfully',
                    icon: 'success',
                    timer: 2000
                });
            }
        });
    }

    window.exportHotspots = function() {
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(geofences, null, 2));
        const downloadAnchor = document.createElement('a');
        downloadAnchor.setAttribute("href", dataStr);
        downloadAnchor.setAttribute("download", "hotspots_export.json");
        document.body.appendChild(downloadAnchor);
        downloadAnchor.click();
        downloadAnchor.remove();
    };

    window.addNewHotspot = function() {
        toggleDrawingMode();
    };

    window.editHotspot = function(hotspotId) {
        alert('Edit hotspot: ' + hotspotId + ' (To be implemented)');
    };

    window.deleteHotspot = function(hotspotId) {
        if (confirm('Are you sure you want to delete this hotspot?')) {
            alert('Delete hotspot: ' + hotspotId + ' (To be implemented)');
        }
    };

    window.viewHotspotAlerts = function(hotspotId) {
        alert('View alerts for hotspot: ' + hotspotId + ' (To be implemented)');
    };

    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        const now = new Date();
        const diff = Math.floor((now - date) / 1000);
        
        if (diff < 60) return 'just now';
        if (diff < 3600) return Math.floor(diff / 60) + ' minutes ago';
        if (diff < 86400) return Math.floor(diff / 3600) + ' hours ago';
        if (diff < 604800) return Math.floor(diff / 86400) + ' days ago';
        
        return date.toLocaleDateString();
    }

    // Make functions globally accessible
    window.selectHotspot = selectHotspot;
    window.hideHotspotDetails = hideHotspotDetails;
    window.toggleHotspotList = toggleHotspotList;
    window.toggleHeatmap = toggleHeatmap;
    window.fitAllHotspots = fitAllHotspots;
    window.zoomIn = zoomIn;
    window.zoomOut = zoomOut;
    window.exportHotspots = exportHotspots;
    window.addNewHotspot = addNewHotspot;
    window.editHotspot = editHotspot;
    window.deleteHotspot = deleteHotspot;
    window.viewHotspotAlerts = viewHotspotAlerts;
    window.cancelDrawing = cancelDrawing;
}