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

    /***************************************************
     * GLOBALS
     ***************************************************/
    let deviceMap = null;
    let geofenceHoverInfo = null;
    let geofenceInfoWindow = null;
    let heatmapLayer = null;
    let drawingManager = null;
    let currentOverlay = null;

    let geofences = [];
    let stationShapes = [];
    let selectedStation = null;
    let clusterMarkers = [];

    const STATION_COLORS = {
        DEFAULT: '#22c55e',
        SELECTED: '#000000',
        HOVER: '#3b82f6',
        ACTIVE: '#10b981',
        INACTIVE: '#94a3b8'
    };

    /***************************************************
     * INIT
     ***************************************************/
    buildLayout();
    setTimeout(() => initMap(), 100); // Small delay to ensure DOM is ready
    loadStations();

    /***************************************************
     * UI LAYOUT - MODERN DESIGN
     ***************************************************/
    function buildLayout() {
        let html = `
            <div class="stations-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;">
                    <div style="display: flex; align-items: center; gap: 16px;">
                        <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-building" style="color: #000;"></i>
                            Stations Management
                        </h1>
                        <span class="station-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;">
                        <button onclick="toggleStationList()" 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="fitAllStations()" 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 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: #e8f5e9; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-map-marker-alt" style="font-size: 20px; color: #2e7d32;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Total Stations</div>
                            <div class="stat-value" id="totalStations" 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: #e3f2fd; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-circle" style="font-size: 20px; color: #1976d2;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Circle Stations</div>
                            <div class="stat-value" id="circleStations" style="font-size: 24px; font-weight: 700; color: #1976d2;">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: #fff3e0; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-draw-polygon" style="font-size: 20px; color: #ed6c02;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Polygon Stations</div>
                            <div class="stat-value" id="polygonStations" style="font-size: 24px; font-weight: 700; color: #ed6c02;">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;">
                            <i class="fas fa-route" style="font-size: 20px; color: #7b1fa2;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Connected Routes</div>
                            <div class="stat-value" id="connectedRoutes" style="font-size: 24px; font-weight: 700; color: #7b1fa2;">0</div>
                        </div>
                    </div>
                </div>

                <!-- Search and Filters -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
                    <div style="position: relative; flex: 1; min-width: 250px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="stationSearch" placeholder="Search stations by name, description..." 
                               style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none;">
                    </div>
                    
                    <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                        <select id="stationTypeFilter" style="padding: 10px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                            <option value="all">All Types</option>
                            <option value="circle">Circle Only</option>
                            <option value="polygon">Polygon Only</option>
                        </select>
                        
                        <select id="stationSort" style="padding: 10px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                            <option value="name">Sort by Name</option>
                            <option value="area">Sort by Area</option>
                            <option value="routes">Sort by Routes</option>
                        </select>
                    </div>
                </div>

                <!-- Main Content: Map and Side Panel -->
                <div style="display: flex; gap: 20px; height: 600px;">
                    <!-- Map Container -->
                    <div style="flex: 2; position: relative; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;">
                        <div id="all_stations_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="fitAllStations()" 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>
                        </div>
                        
                        <!-- Coordinates Display -->
                        <div 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;">
                            <span id="mouseCoordinates">Hover on map to see coordinates</span>
                        </div>
                    </div>

                    <!-- Side Panel - Station List -->
                    <div id="stationListPanel" style="flex: 1; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden; display: flex; flex-direction: column;">
                        <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-list"></i>
                                Stations List
                            </h3>
                        </div>
                        
                        <div id="stationsList" style="flex: 1; overflow-y: auto; padding: 12px;">
                            <!-- Stations will be loaded here -->
                            <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 stations...</div>
                            </div>
                        </div>
                        
                        <div style="padding: 12px; border-top: 1px solid #eaeef2; background: #f8fafc;">
                            <button onclick="exportStations()" style="width: 100%; padding: 10px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                                <i class="fas fa-download"></i> Export Stations Data
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Selected Station Details Panel -->
                <div id="selectedStationPanel" style="display: none; margin-top: 20px; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;">
                    <!-- Dynamic content will be inserted here -->
                </div>

                <style>
                    /* Hover effects */
                    .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);
                    }
                    
                    /* Station list items */
                    .station-list-item {
                        padding: 12px;
                        border-bottom: 1px solid #eaeef2;
                        cursor: pointer;
                        transition: all 0.2s;
                    }
                    .station-list-item:hover {
                        background: #f8fafc;
                    }
                    .station-list-item.selected {
                        background: #f0f2f5;
                        border-left: 3px solid #000;
                    }
                    
                    /* Custom scrollbar */
                    #stationsList::-webkit-scrollbar {
                        width: 6px;
                    }
                    #stationsList::-webkit-scrollbar-track {
                        background: #f1f1f1;
                        border-radius: 10px;
                    }
                    #stationsList::-webkit-scrollbar-thumb {
                        background: #cbd5e1;
                        border-radius: 10px;
                    }
                    #stationsList::-webkit-scrollbar-thumb:hover {
                        background: #94a3b8;
                    }
                    
                    /* Responsive */
                    @media (max-width: 1200px) {
                        .stations-container { padding: 16px !important; }
                        .stats-grid { grid-template-columns: repeat(2, 1fr) !important; }
                        .main-content { flex-direction: column !important; }
                        .map-container { height: 400px !important; }
                    }
                    
                    @media (max-width: 768px) {
                        .stats-grid { grid-template-columns: 1fr !important; }
                    }
                </style>
            </div>
        `;

        $(".tab_stations").html(html);
    }

    /***************************************************
     * MAP INIT
     ***************************************************/
    function initMap() {
        const mapElement = document.getElementById("all_stations_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, // We have custom controls
            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 for coordinates
        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}`);
        });

        // Initialize drawing manager (optional feature)
        initDrawingManager();
    }

    /***************************************************
     * DRAWING MANAGER (Optional - for creating stations)
     ***************************************************/
    function initDrawingManager() {
        if (!deviceMap) return;
     
        try {
               
        drawingManager = new google.maps.drawing.DrawingManager({
            drawingMode: null,
            drawingControl: true,
            drawingControlOptions: {
                position: google.maps.ControlPosition.TOP_CENTER,
                drawingModes: [
                    google.maps.drawing.OverlayType.CIRCLE,
                    google.maps.drawing.OverlayType.POLYGON
                ]
            },
            circleOptions: {
                fillColor: '#22c55e',
                fillOpacity: 0.35,
                strokeWeight: 2,
                strokeColor: '#15803d',
                clickable: true,
                editable: true,
                zIndex: 1
            },
            polygonOptions: {
                fillColor: '#22c55e',
                fillOpacity: 0.35,
                strokeWeight: 2,
                strokeColor: '#15803d',
                clickable: true,
                editable: true,
                zIndex: 1
            }
        });
            
        } catch (error) {
            
        }

        // Add drawing listeners
        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
            // Here you could implement saving new stations
            console.log('New station drawn:', event.overlay);
            alert('Station drawing completed. Save functionality to be implemented.');
        });
    }

    /***************************************************
     * LOAD STATIONS
     ***************************************************/
    function loadStations() {
        controller.getAuthRequest(
            serverURL + "geofences/stations?size=1000",
            true,
            res => {
                geofences = res?.content || [];
                
                // Update stats
                updateStats(geofences);
                
                // Draw stations on map
                drawStations();
                
                // Populate stations list
                populateStationsList(geofences);
                
                // Update station count badge
                $('.station-count').text(`${geofences.length} Stations`);
            },
            error => {
                console.error("Error loading stations:", error);
                $("#stationsList").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 stations</div>
                        <button onclick="loadStations()" 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(stations) {
        const total = stations.length;
        const circleStations = stations.filter(s => s.fenceType === "CIRCLE").length;
        const polygonStations = stations.filter(s => s.fenceType === "POLYGON").length;
        const connectedRoutes = stations.filter(s => s.assignedRouteIds?.length > 0).length;

        animateNumber('#totalStations', total);
        animateNumber('#circleStations', circleStations);
        animateNumber('#polygonStations', polygonStations);
        animateNumber('#connectedRoutes', connectedRoutes);
    }

    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 STATIONS LIST
     ***************************************************/
    function populateStationsList(stations) {
        const $list = $("#stationsList");
        $list.empty();

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

        stations.forEach(station => {
            const typeIcon = station.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
            const routeCount = station.assignedRouteIds?.length || 0;

            $list.append(`
                <div class="station-list-item" data-id="${station.id}" onclick="selectStation('${station.id}')">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 36px; height: 36px; background: ${station.colorHex || '#22c55e'}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="color: ${station.colorHex || '#22c55e'};"></i>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #1a1f36;">${station.name}</div>
                            <div style="font-size: 11px; color: #5b677c; display: flex; gap: 8px; margin-top: 4px;">
                                <span><i class="fas fa-route"></i> ${routeCount} routes</span>
                                <span><i class="fas fa-clock"></i> ${formatDate(station.updatedAt)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `);
        });

        // Add search functionality
        $("#stationSearch").on("keyup", function() {
            const searchTerm = $(this).val().toLowerCase();
            $('.station-list-item').each(function() {
                const name = $(this).text().toLowerCase();
                $(this).toggle(name.includes(searchTerm));
            });
        });
    }

    /***************************************************
     * DRAW STATIONS
     ***************************************************/
    function drawStations() {
        // Clear existing shapes
        stationShapes.forEach(s => {
            if (s) s.setMap(null);
        });
        stationShapes = [];

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

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

            /* =====================
             * CIRCLE STATION
             * ===================== */
            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 || STATION_COLORS.DEFAULT,
                    fillOpacity: 0.25,
                    strokeColor: f.colorHex || STATION_COLORS.DEFAULT,
                    strokeWeight: 2,
                    strokeOpacity: 0.8,
                    clickable: true,
                    zIndex: 1,
                    metadata: f
                });

                // Store metadata
                circle.metadata = f;
                
                // Attach events
                attachStationEvents(circle, 'circle');
                
                stationShapes.push(circle);
                bounds.extend(circle.getCenter());
                hasBounds = true;
            }

            /* =====================
             * POLYGON STATION
             * ===================== */
            if (f.fenceType === "POLYGON" && f.coordinatesJson) {
                try {
                    let path = JSON.parse(f.coordinatesJson);
                    
                    // Convert coordinates if needed
                    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 || STATION_COLORS.DEFAULT,
                        fillOpacity: 0.25,
                        strokeColor: f.colorHex || STATION_COLORS.DEFAULT,
                        strokeWeight: 2,
                        strokeOpacity: 0.8,
                        clickable: true,
                        zIndex: 1,
                        metadata: f
                    });

                    // Store metadata
                    polygon.metadata = f;
                    
                    // Attach events
                    attachStationEvents(polygon, 'polygon');
                    
                    stationShapes.push(polygon);
                    
                    // Extend bounds
                    path.forEach(p => bounds.extend(p));
                    hasBounds = true;
                } catch (e) {
                    console.error("Invalid station polygon:", f.name, e);
                }
            }
        });

        // Fit bounds if we have shapes
        if (hasBounds && deviceMap) {
            deviceMap.fitBounds(bounds);
            
            // Add a slight padding
            setTimeout(() => {
                const currentZoom = deviceMap.getZoom();
                deviceMap.setZoom(currentZoom - 1);
            }, 500);
        }
    }

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

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

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

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

        // Click
        shape.addListener("click", (e) => {
            // Close any open info windows
            geofenceInfoWindow.close();
            
            // Show detailed info
            const position = type === 'circle' ? shape.getCenter() : e.latLng;
            geofenceInfoWindow.setContent(buildStationInfoCard(shape.metadata, 'detailed'));
            geofenceInfoWindow.setPosition(position);
            geofenceInfoWindow.open(deviceMap);
            
            // Highlight selected station
            highlightStation(shape.metadata.id);
            
            // Show detailed panel
            showStationDetails(shape.metadata);
        });

        // Right click - zoom to
        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);
            }
        });
    }

    /***************************************************
     * STATION INFO CARD
     ***************************************************/
    function buildStationInfoCard(station, type = 'hover') {
        const typeIcon = station.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
        const routeCount = station.assignedRouteIds?.length || 0;
        
        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: ${station.colorHex || STATION_COLORS.DEFAULT}20; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="color: ${station.colorHex || STATION_COLORS.DEFAULT};"></i>
                        </div>
                        <div style="font-weight: 600; color: #1a1f36;">${station.name}</div>
                    </div>
                    ${station.description ? `<div style="font-size: 12px; color: #5b677c; margin-bottom: 4px;">${station.description}</div>` : ''}
                    <div style="font-size: 11px; color: #94a3b8;">
                        <i class="fas fa-route"></i> ${routeCount} connected routes
                    </div>
                </div>
            `;
        } else {
            // Detailed view
            return `
                <div style="padding: 12px; min-width: 280px;">
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
                        <div style="width: 40px; height: 40px; background: ${station.colorHex || STATION_COLORS.DEFAULT}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas ${typeIcon}" style="font-size: 18px; color: ${station.colorHex || STATION_COLORS.DEFAULT};"></i>
                        </div>
                        <div>
                            <div style="font-weight: 600; font-size: 16px; color: #1a1f36;">${station.name}</div>
                            <div style="font-size: 12px; color: #5b677c;">${station.fenceType} Station</div>
                        </div>
                    </div>
                    
                    <div style="border-top: 1px solid #eaeef2; padding-top: 12px;">
                        ${station.description ? `
                            <div style="margin-bottom: 8px;">
                                <div style="font-size: 11px; color: #94a3b8; margin-bottom: 2px;">Description</div>
                                <div style="font-size: 13px; color: #1a1f36;">${station.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;">Created</div>
                                <div style="font-size: 12px; color: #1a1f36;">${formatDate(station.createdAt)}</div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Updated</div>
                                <div style="font-size: 12px; color: #1a1f36;">${formatDate(station.updatedAt)}</div>
                            </div>
                        </div>
                        
                        ${station.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;">
                                    ${station.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="editStation('${station.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="viewStationRoutes('${station.id}')" style="flex: 1; padding: 8px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 8px; font-size: 12px; cursor: pointer;">
                                <i class="fas fa-route"></i> Routes
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    /***************************************************
     * HIGHLIGHT STATION
     ***************************************************/
    function highlightStation(stationId) {
        // Reset all shapes
        stationShapes.forEach(shape => {
            shape.setOptions({
                fillOpacity: 0.25,
                strokeWeight: 2,
                zIndex: 1
            });
        });

        // Find and highlight selected shape
        const selectedShape = stationShapes.find(s => s.metadata.id === stationId);
        if (selectedShape) {
            selectedShape.setOptions({
                fillOpacity: 0.5,
                strokeWeight: 4,
                strokeColor: '#000000',
                zIndex: 100
            });
        }

        // Highlight in list
        $('.station-list-item').removeClass('selected');
        $(`.station-list-item[data-id="${stationId}"]`).addClass('selected');
    }

    /***************************************************
     * SHOW STATION DETAILS
     ***************************************************/
    function showStationDetails(station) {
        const typeIcon = station.fenceType === 'CIRCLE' ? 'fa-circle' : 'fa-draw-polygon';
        const routeCount = station.assignedRouteIds?.length || 0;
        
        let area = 'N/A';
        if (station.fenceType === 'CIRCLE' && station.radiusMeters) {
            area = (Math.PI * Math.pow(station.radiusMeters, 2) / 1000000).toFixed(2) + ' km²';
        }

        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: ${station.colorHex || STATION_COLORS.DEFAULT};"></i>
                        ${station.name}
                    </h3>
                    <button onclick="hideStationDetails()" 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;">${station.fenceType}</div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Routes</div>
                        <div style="font-weight: 600; color: #1a1f36;">${routeCount}</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>
                
                ${station.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;">
                            ${station.description}
                        </div>
                    </div>
                ` : ''}
                
                <div style="display: flex; gap: 12px;">
                    <button onclick="editStation('${station.id}')" style="flex: 1; padding: 12px; background: #000; color: white; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-edit"></i> Edit Station
                    </button>
                    <button onclick="deleteStation('${station.id}')" style="flex: 1; padding: 12px; background: #fee2e2; color: #dc2626; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        `;
        
        $('#selectedStationPanel').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.fitAllStations = function() {
        if (!deviceMap || stationShapes.length === 0) return;
        
        const bounds = new google.maps.LatLngBounds();
        stationShapes.forEach(shape => {
            if (shape instanceof google.maps.Circle) {
                bounds.extend(shape.getCenter());
                // Add points around circle to ensure it's fully visible
                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.selectStation = function(stationId) {
        const station = geofences.find(s => s.id == stationId);
        if (station) {
            highlightStation(stationId);
            showStationDetails(station);
            
            // Find and center on the shape
            const shape = stationShapes.find(s => s.metadata.id == stationId);
            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.hideStationDetails = function() {
        $('#selectedStationPanel').slideUp();
    };

    window.toggleStationList = function() {
        $('#stationListPanel').toggleClass('collapsed');
    };

    window.toggleHeatmap = function() {
        if (heatmapLayer) {
            heatmapLayer.setMap(null);
            heatmapLayer = null;
            $('#heatmapBtn').removeClass('active');
        } else {
            // Create heatmap data from station centers
            const heatmapData = stationShapes.map(shape => {
                if (shape instanceof google.maps.Circle) {
                    return {
                        location: shape.getCenter(),
                        weight: shape.metadata.assignedRouteIds?.length || 1
                    };
                } else {
                    // Use polygon centroid
                    const bounds = new google.maps.LatLngBounds();
                    shape.getPath().forEach(p => bounds.extend(p));
                    return {
                        location: bounds.getCenter(),
                        weight: shape.metadata.assignedRouteIds?.length || 1
                    };
                }
            });
            
            heatmapLayer = new google.maps.visualization.HeatmapLayer({
                data: heatmapData,
                map: deviceMap,
                radius: 40,
                opacity: 0.6,
                gradient: [
                    'rgba(0, 255, 255, 0)',
                    'rgba(0, 255, 255, 1)',
                    'rgba(0, 191, 255, 1)',
                    'rgba(0, 127, 255, 1)',
                    'rgba(0, 63, 255, 1)',
                    'rgba(0, 0, 255, 1)',
                    'rgba(0, 0, 223, 1)',
                    'rgba(0, 0, 191, 1)',
                    'rgba(0, 0, 159, 1)',
                    'rgba(0, 0, 127, 1)',
                    'rgba(63, 0, 91, 1)',
                    'rgba(127, 0, 63, 1)',
                    'rgba(191, 0, 31, 1)',
                    'rgba(255, 0, 0, 1)'
                ]
            });
            
            $('#heatmapBtn').addClass('active');
        }
    };

    window.exportStations = 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", "stations_export.json");
        document.body.appendChild(downloadAnchor);
        downloadAnchor.click();
        downloadAnchor.remove();
    };

    window.editStation = function(stationId) {
        alert('Edit station: ' + stationId + ' (To be implemented)');
    };

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

    window.viewStationRoutes = function(stationId) {
        alert('View routes for station: ' + stationId + ' (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.selectStation = selectStation;
    window.hideStationDetails = hideStationDetails;
    window.toggleStationList = toggleStationList;
    window.toggleHeatmap = toggleHeatmap;
    window.fitAllStations = fitAllStations;
    window.zoomIn = zoomIn;
    window.zoomOut = zoomOut;
    window.exportStations = exportStations;
    window.editStation = editStation;
    window.deleteStation = deleteStation;
    window.viewStationRoutes = viewStationRoutes;
}