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

    /***************************************************
     * GLOBALS
     ***************************************************/
    var deviceMap;
    var markers = {};
    var infoWindows = {};
    var geofenceHoverInfo = null;
    var geocoder = new google.maps.Geocoder();
    var mapStyles = {
        default: null,
        dark: [
            { elementType: "geometry", stylers: [{ color: "#242f3e" }] },
            { elementType: "labels.text.stroke", stylers: [{ color: "#242f3e" }] },
            { elementType: "labels.text.fill", stylers: [{ color: "#746855" }] },
            {
                featureType: "administrative.locality",
                elementType: "labels.text.fill",
                stylers: [{ color: "#d59563" }]
            },
            {
                featureType: "poi",
                elementType: "labels.text.fill",
                stylers: [{ color: "#d59563" }]
            },
            {
                featureType: "poi.park",
                elementType: "geometry",
                stylers: [{ color: "#263c3f" }]
            },
            {
                featureType: "poi.park",
                elementType: "labels.text.fill",
                stylers: [{ color: "#6b9a76" }]
            },
            {
                featureType: "road",
                elementType: "geometry",
                stylers: [{ color: "#38414e" }]
            },
            {
                featureType: "road",
                elementType: "geometry.stroke",
                stylers: [{ color: "#212a37" }]
            },
            {
                featureType: "road",
                elementType: "labels.text.fill",
                stylers: [{ color: "#9ca5b3" }]
            },
            {
                featureType: "road.highway",
                elementType: "geometry",
                stylers: [{ color: "#746855" }]
            },
            {
                featureType: "road.highway",
                elementType: "geometry.stroke",
                stylers: [{ color: "#1f2835" }]
            },
            {
                featureType: "road.highway",
                elementType: "labels.text.fill",
                stylers: [{ color: "#f3d19c" }]
            },
            {
                featureType: "transit",
                elementType: "geometry",
                stylers: [{ color: "#2f3948" }]
            },
            {
                featureType: "transit.station",
                elementType: "labels.text.fill",
                stylers: [{ color: "#d59563" }]
            },
            {
                featureType: "water",
                elementType: "geometry",
                stylers: [{ color: "#17263c" }]
            },
            {
                featureType: "water",
                elementType: "labels.text.fill",
                stylers: [{ color: "#515c6d" }]
            },
            {
                featureType: "water",
                elementType: "labels.text.stroke",
                stylers: [{ color: "#17263c" }]
            }
        ]
    };

    var devicesMaster = [];
    var telemetryMap = {};
    var previousPositions = {};
    var selectedDeviceSn = null;
    var mapType = "roadmap";
    var animationFrame = null;
    var pulseIntervals = {};

    var geofences = [];
    var geofenceShapes = {
        hotspots: [],
        stations: [],
        routes: []
    };

    /***************************************************
     * INIT
     ***************************************************/

    buildLayout();
    loadDevicesList();
    loadTelemetryInitial();
    setInterval(loadTelemetryRealtime, 1000);

    /***************************************************
     * UI LAYOUT - MODERN DESIGN
     ***************************************************/
    function buildLayout() {
        // Add custom CSS
        addCustomStyles();

        let html = `
            <div class="fleet-dashboard">
                <div class="dashboard-main">
                    <!-- LEFT PANEL - DEVICES -->
                    <div class="panel devices-panel">
                         <div class="panel-header">
                        <h3><i class="fas fa-list"></i></h3>
                        <div class="panel-actions">
                            <span class="live-badge"><i class="fas fa-circle"></i> LIVE</span>
                            <button class="btn-icon" onclick="window.refreshDevices ? refreshDevices() : null" title="Refresh">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn-icon toggle-device-panel" onclick="window.toggleDeviceList ? toggleDeviceList() : null" title="Toggle Panel">
                                <i class="fas fa-chevron-left"></i>
                            </button>
                        </div>
                    </div>
                        
                        <div class="panel-content">
                            <div class="device-search">
                                <i class="fas fa-search"></i>
                                <input type="text" id="device_search" placeholder="Search devices...">
                            </div>
                            
                            <div class="device-filters">
                                <button class="filter-chip active" data-filter="all" onclick="window.filterDeviceList ? filterDeviceList('all') : null">All</button>
                                <button class="filter-chip" data-filter="online" onclick="window.filterDeviceList ? filterDeviceList('online') : null">Online</button>
                                <button class="filter-chip" data-filter="offline" onclick="window.filterDeviceList ? filterDeviceList('offline') : null">Offline</button>
                            </div>
                            
                            <div class="device-list" id="device_list">
                                <div class="loading-message">Loading devices...</div>
                            </div>
                        </div>
                    </div>

                    <!-- CENTER PANEL - MAP -->
                    <div class="panel map-panel">
                        <div class="panel-header">
                            <h3><i class="fas fa-map"></i> Live Tracking</h3>
                            <div class="panel-actions">
                                <div class="map-type-selector">
                                    <button class="map-type-btn active" onclick="window.changeMapType ? changeMapType('roadmap') : null">Road</button>
                                    <button class="map-type-btn" onclick="window.changeMapType ? changeMapType('satellite') : null">Satellite</button>
                                    <button class="map-type-btn" onclick="window.changeMapType ? changeMapType('dark') : null">Dark</button>
                                </div>
                                <button class="btn-icon" onclick="window.fitMapToMarkers ? fitMapToMarkers() : null" title="Fit to all devices">
                                    <i class="fas fa-expand-arrows-alt"></i>
                                </button>
                                <button class="btn-icon" onclick="window.centerMap ? centerMap() : null" title="Recenter">
                                    <i class="fas fa-crosshairs"></i>
                                </button>
                            </div>
                        </div>
                        <div id="all_devices_map" class="map-container"></div>
                        
                        <div class="map-overlay" id="map_overlay">
                            <div class="overlay-item">
                                <i class="fas fa-crosshairs"></i>
                                <span id="map_center_coords">Loading map...</span>
                            </div>
                        </div>
                    </div>

                    <!-- RIGHT PANEL - INFO & FILTERS -->
                    <div class="panel info-panel">
                        <div class="panel-header">
                            <h3><i class="fas fa-info-circle"></i> Information</h3>
                            <button class="btn-icon toggle-info-panel" onclick="window.toggleInfoPanel ? toggleInfoPanel() : null" title="Toggle Panel">
                                <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>

                        <div class="panel-content">
                            <!-- Selected Device Info -->
                            <div class="selected-device-info" id="selected_device_info" style="display: none;">
                                <div class="info-title">
                                    <i class="fas fa-map-pin"></i> Selected Device
                                </div>
                                <div id="selected_device_details"></div>
                            </div>

                            <!-- Geofence Filters -->
                            <div class="filter-section">
                                <div class="filter-section-title">
                                    <i class="fas fa-filter"></i> Geofence Filters
                                </div>
                                <div class="filter-options">
                                    <label class="filter-checkbox">
                                        <input type="checkbox" class="geofence-filter" id="filter_hotspots" checked>
                                        <span class="checkmark"></span>
                                        <span class="filter-label">Hotspots <span class="badge" id="hotspot_count">0</span></span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="checkbox" class="geofence-filter" id="filter_stations" checked>
                                        <span class="checkmark"></span>
                                        <span class="filter-label">Stations <span class="badge" id="station_count">0</span></span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="checkbox" class="geofence-filter" id="filter_routes" checked>
                                        <span class="checkmark"></span>
                                        <span class="filter-label">Routes <span class="badge" id="route_count">0</span></span>
                                    </label>
                                </div>
                                <button class="btn-apply" onclick="window.applyGeofenceFilters ? applyGeofenceFilters() : null">
                                    <i class="fas fa-check"></i> Apply Filters
                                </button>
                            </div>

                            <!-- Quick Actions -->
                            <div class="quick-actions">
                                <div class="filter-section-title">
                                    <i class="fas fa-bolt"></i> Quick Actions
                                </div>
                                <button class="action-btn" onclick="window.openGeofences ? openGeofences() : null">
                                    <i class="fas fa-shield-alt"></i> Monitoring Center
                                </button>
                                <button class="action-btn" onclick="window.showAllDevices ? showAllDevices() : null">
                                    <i class="fas fa-eye"></i> Show All Devices
                                </button>
                                <button class="action-btn" onclick="window.clearSelection ? clearSelection() : null">
                                    <i class="fas fa-times-circle"></i> Clear Selection
                                </button>
                            </div>

                            <!-- Real-time Stats -->
                            <div class="realtime-stats">
                                <div class="filter-section-title">
                                    <i class="fas fa-chart-line"></i> Real-time Stats
                                </div>
                                <div class="stats-grid">
                                    <div class="stat-row">
                                        <span>Total Distance:</span>
                                        <span id="total_distance">0 km</span>
                                    </div>
                                    <div class="stat-row">
                                        <span>Avg Speed:</span>
                                        <span id="avg_speed">0 km/h</span>
                                    </div>
                                    <div class="stat-row">
                                        <span>Last Update:</span>
                                        <span id="last_update">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        $(".tab_position").html(html);
        
        // Initialize search listener
        $("#device_search").on("keyup", function() {
            filterDevices($(this).val());
        });
    }

    function addCustomStyles() {
        // Check if styles already exist
        if ($('#fleet-dashboard-styles').length) return;
        
        const styles = `
            <style id="fleet-dashboard-styles">
                /* Modern CSS Variables */
                :root {
                    --primary-color: #4361ee;
                    --success-color: #06d6a0;
                    --warning-color: #ffb703;
                    --danger-color: #ef476f;
                    --dark-bg: #1e1e2f;
                    --light-bg: #f8f9fa;
                    --card-bg: #ffffff;
                    --text-primary: #2b2d42;
                    --text-secondary: #8d99ae;
                    --border-radius: 12px;
                    --shadow-sm: 0 2px 4px rgba(0,0,0,0.1);
                    --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
                    --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
                    --transition: all 0.3s ease;
                }

                /* Dashboard Layout */
                .fleet-dashboard {
                    height: calc(100vh - 100px);
                    display: flex;
                    flex-direction: column;
                    background: var(--light-bg);
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                }

                .dashboard-main {
                    display: flex;
                    gap: 1rem;
                    flex: 1;
                    min-height: 0;
                }

                /* Panel Styles */
                .panel {
                    background: var(--card-bg);
                    border-radius: var(--border-radius);
                    box-shadow: var(--shadow-md);
                    display: flex;
                    flex-direction: column;
                    overflow: hidden;
                    transition: var(--transition);
                }

                .devices-panel {
                    flex: 0 0 200px;
                }

                .map-panel {
                    flex: 1;
                    position: relative;
                }

                .info-panel {
                    flex: 0 0 200px;
                }

                /* Collapsed States */
                .devices-panel.collapsed {
                    flex: 0 0 50px;
                }

                .info-panel.collapsed {
                    flex: 0 0 50px;
                }

                .devices-panel.collapsed .panel-content,
                .info-panel.collapsed .panel-content {
                    display: none;
                }

               

                .panel-header {
                    padding: 1rem;
                    background: black;
                    color: white;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex-shrink: 0;
                }

                .panel-header h3 {
                    margin: 0;
                    font-size: 1rem;
                    font-weight: 600;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .panel-header h3 i {
                    margin-right: 0.5rem;
                }

                .panel-actions {
                    display: flex;
                    gap: 0.5rem;
                    align-items: center;
                }

                .panel-content {
                    flex: 1;
                    overflow-y: auto;
                    display: flex;
                    flex-direction: column;
                }

                .btn-icon {
                    background: rgba(255,255,255,0.2);
                    border: none;
                    color: white;
                    width: 30px;
                    height: 30px;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                    transition: var(--transition);
                }

                .btn-icon:hover {
                    background: rgba(255,255,255,0.3);
                    transform: scale(1.05);
                }

                .btn-icon i {
                    transition: transform 0.3s ease;
                }

                .live-badge {
                    background: var(--danger-color);
                    color: white;
                    padding: 0.25rem 0.75rem;
                    border-radius: 20px;
                    font-size: 0.8rem;
                    font-weight: 600;
                    display: flex;
                    align-items: center;
                    gap: 0.3rem;
                }

                .live-badge i {
                    font-size: 0.6rem;
                    animation: pulse 1.5s infinite;
                }

                @keyframes pulse {
                    0% { opacity: 1; }
                    50% { opacity: 0.5; }
                    100% { opacity: 1; }
                }

                /* Device List Styles */
                .device-search {
                    padding: 0.75rem;
                    position: relative;
                }

                .device-search i {
                    position: absolute;
                    left: 1.5rem;
                    top: 50%;
                    transform: translateY(-50%);
                    color: var(--text-secondary);
                }

                .device-search input {
                    width: 100%;
                    padding: 0.5rem 0.5rem 0.5rem 2.2rem;
                    border: 1px solid #e0e0e0;
                    border-radius: 20px;
                    font-size: 0.9rem;
                    transition: var(--transition);
                    box-sizing: border-box;
                }

                .device-search input:focus {
                    outline: none;
                    border-color: var(--primary-color);
                    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
                }

                .device-filters {
                    padding: 0 0.75rem 0.75rem;
                    display: flex;
                    gap: 0.5rem;
                    flex-wrap: wrap;
                }

                .filter-chip {
                    padding: 0.3rem 0.8rem;
                    border: 1px solid #e0e0e0;
                    border-radius: 20px;
                    background: white;
                    color: var(--text-secondary);
                    font-size: 0.8rem;
                    cursor: pointer;
                    transition: var(--transition);
                }

                .filter-chip.active {
                    background: var(--primary-color);
                    color: white;
                    border-color: var(--primary-color);
                }

                .filter-chip:hover {
                    background: var(--primary-color);
                    color: white;
                    border-color: var(--primary-color);
                }

                .device-list {
                    flex: 1;
                    overflow-y: auto;
                    padding: 0 0.75rem 0.75rem;
                }

                .loading-message {
                    text-align: center;
                    color: var(--text-secondary);
                    padding: 2rem;
                }

                .device-card {
                    background: var(--light-bg);
                    border-radius: 10px;
                    padding: 0.5rem;
                    margin-bottom: 0.1rem;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    cursor: pointer;
                    transition: var(--transition);
                    border: 2px solid transparent;
                }

                .device-card:hover {
                    transform: translateX(5px);
                    box-shadow: var(--shadow-md);
                }

                .device-card.selected {
                    border-color: var(--primary-color);
                    background: rgba(67, 97, 238, 0.05);
                }

                .device-left {
                    display: flex;
                    align-items: center;
                    gap: 0.75rem;
                }

                .device-pin {
                    width: 35px;
                    height: 35px;
                    border-radius: 50%;
                    background: var(--primary-color);
                    color: white;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 1rem;
                    flex-shrink: 0;
                }

                .device-text {
                    display: flex;
                    flex-direction: column;
                    min-width: 0;
                }

                .device-title {
                    font-weight: 600;
                    color: var(--text-primary);
                    font-size: 0.8rem;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .device-id {
                    font-size: 0.7rem;
                    color: var(--text-secondary);
                }

                .device-badge {
                    padding: 0.2rem 0.5rem;
                    border-radius: 12px;
                    font-size: 0.6rem;
                    font-weight: 600;
                    text-transform: uppercase;
                    white-space: nowrap;
                }

                .device-badge.online {
                    background: rgba(6, 214, 160, 0.1);
                    color: var(--success-color);
                }

                .device-badge.offline {
                    background: rgba(141, 153, 174, 0.1);
                    color: var(--text-secondary);
                }

                /* Map Container */
                .map-container {
                    width: 100%;
                    height: 100%;
                    min-height: 500px;
                }

                .map-overlay {
                    position: absolute;
                    bottom: 1rem;
                    left: 1rem;
                    background: rgba(255,255,255,0.9);
                    padding: 0.5rem 1rem;
                    border-radius: 20px;
                    backdrop-filter: blur(10px);
                    box-shadow: var(--shadow-sm);
                    font-size: 0.8rem;
                    z-index: 10;
                }

                .map-type-selector {
                    display: flex;
                    gap: 0.2rem;
                    background: rgba(255,255,255,0.2);
                    border-radius: 8px;
                    padding: 0.2rem;
                }

                .map-type-btn {
                    background: transparent;
                    border: none;
                    color: white;
                    padding: 0.2rem 0.5rem;
                    border-radius: 6px;
                    font-size: 0.7rem;
                    cursor: pointer;
                    transition: var(--transition);
                }

                .map-type-btn.active {
                    background: rgba(255,255,255,0.3);
                }

                /* Info Panel Styles */
                .selected-device-info {
                    padding: 1rem;
                    background: #005fc6;
                    color: white;
                    margin: 1rem;
                    border-radius: 10px;
                }

                .info-title {
                    font-size: 0.7rem;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    opacity: 0.8;
                    margin-bottom: 0.5rem;
                }

                .filter-section {
                    padding: 1rem;
                    border-bottom: 1px solid #e0e0e0;
                }

                .filter-section-title {
                    font-weight: 600;
                    color: var(--text-primary);
                    margin-bottom: 1rem;
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                }

                .filter-options {
                    display: flex;
                    flex-direction: column;
                    gap: 0.75rem;
                    margin-bottom: 1rem;
                }

                .filter-checkbox {
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                    cursor: pointer;
                    position: relative;
                    padding-left: 30px;
                }

                .filter-checkbox input {
                    position: absolute;
                    opacity: 0;
                    cursor: pointer;
                    height: 0;
                    width: 0;
                }

                .checkmark {
                    position: absolute;
                    left: 0;
                    height: 18px;
                    width: 18px;
                    background-color: #eee;
                    border-radius: 4px;
                    transition: var(--transition);
                }

                .filter-checkbox:hover input ~ .checkmark {
                    background-color: #ccc;
                }

                .filter-checkbox input:checked ~ .checkmark {
                    background-color: var(--primary-color);
                }

                .checkmark:after {
                    content: "";
                    position: absolute;
                    display: none;
                }

                .filter-checkbox input:checked ~ .checkmark:after {
                    display: block;
                }

                .filter-checkbox .checkmark:after {
                    left: 6px;
                    top: 2px;
                    width: 5px;
                    height: 10px;
                    border: solid white;
                    border-width: 0 2px 2px 0;
                    transform: rotate(45deg);
                }

                .badge {
                    background: var(--primary-color);
                    color: white;
                    padding: 0.2rem 0.4rem;
                    border-radius: 4px;
                    font-size: 0.6rem;
                    margin-left: 0.3rem;
                }

                .btn-apply {
                    width: 100%;
                    padding: 0.5rem;
                    background: var(--primary-color);
                    color: white;
                    border: none;
                    border-radius: 8px;
                    cursor: pointer;
                    transition: var(--transition);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 0.5rem;
                }

                .btn-apply:hover {
                    background: #3651d4;
                    transform: translateY(-2px);
                }

                .quick-actions {
                    padding: 1rem;
                }

                .action-btn {
                    width: 100%;
                    padding: 0.5rem;
                    margin-bottom: 0.5rem;
                    background: var(--light-bg);
                    border: 1px solid #e0e0e0;
                    border-radius: 8px;
                    cursor: pointer;
                    transition: var(--transition);
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                }

                .action-btn:hover {
                    background: var(--primary-color);
                    color: white;
                    border-color: var(--primary-color);
                }

                .realtime-stats {
                    padding: 1rem;
                }

                .stats-grid {
                    background: var(--light-bg);
                    padding: 0.75rem;
                    border-radius: 8px;
                }

                .stat-row {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 0.5rem;
                    font-size: 0.9rem;
                }

                .stat-row:last-child {
                    margin-bottom: 0;
                }

                /* Info Window Custom Styles */
                .geofence-hover-card {
                    padding: 0.5rem;
                    max-width: 200px;
                }

                .geofence-hover-title {
                    font-weight: 600;
                    color: var(--primary-color);
                    margin-bottom: 0.25rem;
                }

                .geofence-hover-type {
                    font-size: 0.7rem;
                    color: var(--text-secondary);
                    text-transform: uppercase;
                    margin-bottom: 0.25rem;
                }

                .geofence-hover-desc {
                    font-size: 0.8rem;
                    color: var(--text-primary);
                }

                /* Scrollbar Styling */
                ::-webkit-scrollbar {
                    width: 6px;
                }

                ::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }

                ::-webkit-scrollbar-thumb {
                    background: var(--primary-color);
                    border-radius: 10px;
                }

                ::-webkit-scrollbar-thumb:hover {
                    background: #3651d4;
                }

                /* Responsive Design */
                @media (max-width: 1200px) {
                    .devices-panel {
                        flex: 0 0 250px;
                    }
                    
                    .info-panel {
                        flex: 0 0 240px;
                    }
                }

                @media (max-width: 768px) {
                    .dashboard-main {
                        flex-direction: column;
                    }
                    
                    .devices-panel,
                    .info-panel {
                        flex: none;
                        width: 100%;
                    }
                    
                    .devices-panel.collapsed,
                    .info-panel.collapsed {
                        flex: none;
                        width: 100%;
                    }
                }
                    /* Add to your existing CSS in addCustomStyles function */

/* Hide live-badge and refresh button when panel is collapsed */
.devices-panel.collapsed .live-badge,
.devices-panel.collapsed .btn-icon:not(.toggle-device-panel) {
    display: none;
}

/* Adjust header for collapsed state */
.devices-panel.collapsed .panel-header {
    justify-content: center;
    padding: 1rem 0.5rem;
}

.devices-panel.collapsed .panel-header h3 {
    display: none;
}

.devices-panel.collapsed .panel-actions {
    margin: 0;
}

/* Info panel collapsed state */
.info-panel.collapsed .panel-header {
    justify-content: center;
    padding: 1rem 0.5rem;
}

.info-panel.collapsed .panel-header h3 {
    display: none;
}

/* Ensure toggle button is always visible */
.devices-panel .toggle-device-panel,
.info-panel .toggle-info-panel {
    display: flex !important;
}

/* Adjust panel widths when collapsed */
.devices-panel.collapsed {
    flex: 0 0 50px;
    min-width: 50px;
}

.info-panel.collapsed {
    flex: 0 0 50px;
    min-width: 50px;
}

/* Hide all content except header when collapsed */
.devices-panel.collapsed .panel-content,
.info-panel.collapsed .panel-content {
    display: none;
}

/* Center the toggle button */
.devices-panel.collapsed .panel-actions,
.info-panel.collapsed .panel-actions {
    width: 100%;
    display: flex;
    justify-content: center;
}

/* Animation for smooth transitions */
.panel {
    transition: flex 0.3s ease, min-width 0.3s ease;
}

.panel-header {
    transition: padding 0.3s ease;
}

.panel-header h3 {
    transition: opacity 0.3s ease;
}

.live-badge,
.btn-icon:not(.toggle-device-panel):not(.toggle-info-panel) {
    transition: opacity 0.3s ease, display 0.3s ease;
}
            </style>
        `;
        
        $('head').append(styles);
    }

    /***************************************************
     * DEVICE FUNCTIONS
     ***************************************************/
    function loadDevicesList() {
        controller.getAuthRequest(
            API_BASE + "devices/all",
            true,
            data => {
                devicesMaster = data || [];
                renderDeviceList();
                updateStats();
            },
            error => {
                $("#device_list").html('<div class="loading-message">Error loading devices</div>');
            }
        );
    }

    function renderDeviceList() {
        const $list = $("#device_list");
        $list.empty();
        
        if (!devicesMaster.length) {
            $list.html('<div class="loading-message">No devices found</div>');
            return;
        }
        
        devicesMaster.forEach(device => {
            const isOnline = device.isOnline;
            const telemetry = telemetryMap[device.serialNo];
            const statusClass = isOnline ? 'online' : 'offline';
            const statusText = isOnline ? 'ONLINE' : 'OFFLINE';
            
            const $card = $(`
                <div class="device-card ${selectedDeviceSn === device.serialNo ? 'selected' : ''}" 
                     data-sn="${device.serialNo}"
                     data-online="${isOnline}">
                    <div class="device-left">
                        <div class="device-pin" style="background: ${getDeviceColor(device)}">
                            <i class="fas fa-location-dot"></i>
                        </div>
                        <div class="device-text">
                            <div class="device-title">${device.serialNo}</div>
                            <div class="device-id">
                                ${telemetry ? `${telemetry.speedKmh || 0} km/h` : 'No data'}
                            </div>
                        </div>
                    </div>
                    <div class="device-badge ${statusClass}">
                        ${statusText}
                    </div>
                </div>
            `);
            
            $card.on('click', function() {
                focusDevice(device.serialNo);
            });
            
            $list.append($card);
        });
    }

    function getDeviceColor(device) {
        if (device.isOnline) {
            return telemetryMap[device.serialNo]?.speedKmh > 0 ? 
                'var(--warning-color)' : 'var(--success-color)';
        }
        return 'var(--text-secondary)';
    }

    function updateStats() {
        const total = devicesMaster.length;
        const online = devicesMaster.filter(d => d.isOnline).length;
        const offline = total - online;
        const moving = devicesMaster.filter(d => 
            d.isOnline && telemetryMap[d.serialNo]?.speedKmh > 0
        ).length;
        
        $("#total_devices").text(total);
        $("#online_devices").text(online);
        $("#offline_devices").text(offline);
        $("#moving_devices").text(moving);
        
        // Calculate total distance and avg speed
        let totalDistance = 0;
        let totalSpeed = 0;
        let speedCount = 0;
        
        Object.values(telemetryMap).forEach(t => {
            if (t.mileageKm) totalDistance += t.mileageKm;
            if (t.speedKmh > 0) {
                totalSpeed += t.speedKmh;
                speedCount++;
            }
        });
        
        $("#total_distance").text(`${Math.round(totalDistance).toLocaleString()} km`);
        $("#avg_speed").text(speedCount ? Math.round(totalSpeed / speedCount) + ' km/h' : '0 km/h');
        $("#last_update").text(new Date().toLocaleTimeString());
        
        // Update geofence counts
        $("#hotspot_count").text(geofenceShapes.hotspots.length);
        $("#station_count").text(geofenceShapes.stations.length);
        $("#route_count").text(geofenceShapes.routes.length);
    }

    function filterDevices(searchTerm) {
        const $cards = $('.device-card');
        const term = searchTerm ? searchTerm.toLowerCase().trim() : '';
        
        if ($cards.length === 0) return;
        
        $cards.each(function() {
            const $card = $(this);
            const sn = $card.data('sn');
            
            if (!sn) return;
            
            const snLower = sn.toString().toLowerCase();
            
            if (term === '') {
                $card.show();
            } else if (snLower.includes(term)) {
                $card.show();
            } else {
                $card.hide();
            }
        });
        
        const visibleCount = $cards.filter(':visible').length;
        if (visibleCount === 0 && term !== '') {
            if ($('#no-search-results').length === 0) {
                $('#device_list').append('<div id="no-search-results" class="loading-message">No devices match "' + searchTerm + '"</div>');
            }
        } else {
            $('#no-search-results').remove();
        }
    }

    function filterDeviceList(filter) {
        $('.filter-chip').removeClass('active');
        $(`.filter-chip[data-filter="${filter}"]`).addClass('active');
        
        const $cards = $('.device-card');
        
        $cards.each(function() {
            const $card = $(this);
            switch(filter) {
                case 'all':
                    $card.show();
                    break;
                case 'online':
                    if ($card.data('online') === true) $card.show();
                    else $card.hide();
                    break;
                case 'offline':
                    if ($card.data('online') === false) $card.show();
                    else $card.hide();
                    break;
            }
        });
    }

    /***************************************************
     * MAP FUNCTIONS
     ***************************************************/
    function loadTelemetryInitial() {
        controller.getAuthRequest(serverURL + "telemetry/latest", true, data => {
            if (!data?.length) {
                $("#map_center_coords").text("No device data available");
                return;
            }

            data.forEach(d => telemetryMap[d.deviceSn] = d);

            const first = data.find(d => d.latitude && d.longitude);
            if (!first) {
                $("#map_center_coords").text("No location data available");
                return;
            }

            const mapOptions = {
                zoom: 18,
                center: { lat: first.latitude, lng: first.longitude },
                gestureHandling: "greedy",
                zoomControl: true,
                mapTypeControl: true,
                fullscreenControl: true,
                streetViewControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            deviceMap = new google.maps.Map(
                document.getElementById("all_devices_map"),
                mapOptions
            );

            google.maps.event.addListener(deviceMap, 'click', function(e) {
                updateMapOverlay(e.latLng);
            });

            google.maps.event.addListener(deviceMap, 'idle', function() {
                updateMapOverlay(deviceMap.getCenter());
            });

            geofenceHoverInfo = new google.maps.InfoWindow({ disableAutoPan: true });

            data.forEach(addOrUpdateMarker);
            loadGeofences();
            
            startAnimationLoop();
            
            updateMapOverlay(deviceMap.getCenter());
            
            renderDeviceList();
        });
    }

    function loadTelemetryRealtime() {
        controller.getAuthRequest(serverURL + "telemetry/latest", true, data => {
            if (!data) return;
            
            data.forEach(d => {
                const oldData = telemetryMap[d.deviceSn];
                telemetryMap[d.deviceSn] = d;
                
                if (oldData && markers[d.deviceSn] && oldData.latitude && oldData.longitude) {
                    previousPositions[d.deviceSn] = {
                        lat: oldData.latitude,
                        lng: oldData.longitude,
                        timestamp: Date.now()
                    };
                }
                
                addOrUpdateMarker(d);
            });
            
            updateStats();
        });
    }

    function changeMapType(type) {
        $('.map-type-btn').removeClass('active');
        $(`.map-type-btn:contains("${type === 'roadmap' ? 'Road' : type === 'satellite' ? 'Satellite' : 'Dark'}")`).addClass('active');
        
        if (!deviceMap) return;
        
        switch(type) {
            case 'roadmap':
                deviceMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
                deviceMap.setOptions({ styles: null });
                break;
            case 'satellite':
                deviceMap.setMapTypeId(google.maps.MapTypeId.SATELLITE);
                deviceMap.setOptions({ styles: null });
                break;
            case 'dark':
                deviceMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
                deviceMap.setOptions({ styles: mapStyles.dark });
                break;
        }
    }

    function fitMapToMarkers() {
        if (!deviceMap) return;
        
        const bounds = new google.maps.LatLngBounds();
        let hasMarkers = false;
        
        Object.values(markers).forEach(marker => {
            if (marker && marker.getPosition()) {
                bounds.extend(marker.getPosition());
                hasMarkers = true;
            }
        });
        
        if (hasMarkers) {
            deviceMap.fitBounds(bounds);
        }
    }

    function centerMap() {
        if (!deviceMap) return;
        
        if (selectedDeviceSn && markers[selectedDeviceSn]) {
            deviceMap.panTo(markers[selectedDeviceSn].getPosition());
            deviceMap.setZoom(18);
        } else {
            fitMapToMarkers();
        }
    }

    function updateMapOverlay(latLng) {
        if (!latLng) return;
        
        const lat = typeof latLng.lat === 'function' ? latLng.lat().toFixed(6) : latLng.lat.toFixed(6);
        const lng = typeof latLng.lng === 'function' ? latLng.lng().toFixed(6) : latLng.lng.toFixed(6);
        $("#map_center_coords").html(`${lat}, ${lng}`);
    }

    /***************************************************
     * MARKER FUNCTIONS
     ***************************************************/
//  function addOrUpdateMarker(t) {
//     if (!t.latitude || !t.longitude || !deviceMap) return;

//     // Create custom lorry icon based on speed and online status
//     const iconUrl = t.speedKmh > 0 ? 
//         'assets/truck_1.png' : // Moving - red truck
//         'assets/truck_1.png'; // Stationary - blue dot
    
//     // Alternative: Use custom icons if you have them
//     // const iconUrl = t.speedKmh > 0 ? 
//     //     '/assets/images/lorry-moving.png' : 
//     //     '/assets/images/lorry-stopped.png';

//     if (!markers[t.deviceSn]) {
//         const markerOptions = {
//             map: deviceMap,
//             position: { lat: t.latitude, lng: t.longitude },
//             title: t.deviceName || t.deviceSn,
//             // animation: google.maps.Animation.DROP,
//             icon: {
//                 url: iconUrl,
//                 scaledSize: new google.maps.Size(16, 16), // Adjust size as needed
//                 origin: new google.maps.Point(0, 0),
//                 anchor: new google.maps.Point(8, 8) // Center the icon
//             }
//         };

//         // Add label with speed for moving vehicles (optional)
//         if (t.speedKmh > 0) {
//             markerOptions.label = {
//                 text: t.speedKmh.toString(),
//                 color: 'white',
//                 fontSize: '12px',
//                 fontWeight: 'bold'
//             };
//         }

//         markers[t.deviceSn] = new google.maps.Marker(markerOptions);

//         // Create pulse effect (keep this for visual feedback)
//         createPulseEffect(t.deviceSn);

//         infoWindows[t.deviceSn] = new google.maps.InfoWindow({
//             content: buildInfoContent(t),
//             maxWidth: 300
//         });

//         markers[t.deviceSn].addListener("click", () => {
//             closeAllInfoWindows();
//             infoWindows[t.deviceSn].open(deviceMap, markers[t.deviceSn]);
//             focusDevice(t.deviceSn);
//         });

//         previousPositions[t.deviceSn] = {
//             lat: t.latitude,
//             lng: t.longitude,
//             timestamp: Date.now()
//         };
//     } else {
//         // Update existing marker
//         markers[t.deviceSn].setIcon({
//             url: iconUrl,
//             scaledSize: new google.maps.Size(16, 16),
//             origin: new google.maps.Point(0, 0),
//             anchor: new google.maps.Point(8, 8)
//         });

//         // Update label for speed
//         if (t.speedKmh > 0) {
//             markers[t.deviceSn].setLabel({
//                 text: t.speedKmh.toString(),
//                 color: 'white',
//                 fontSize: '12px',
//                 fontWeight: 'bold'
//             });
//         } else {
//             markers[t.deviceSn].setLabel(null);
//         }
        
//         infoWindows[t.deviceSn].setContent(buildInfoContent(t));
//     }
// }

function addOrUpdateMarker(t) {
    if (!t.latitude || !t.longitude || !deviceMap) return;

    const position = { lat: t.latitude, lng: t.longitude };

    // Store circles
    if (!window.deviceCircles) window.deviceCircles = {};

    const circleIcon = {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 5,
        fillColor: '#3b82f6',
        fillOpacity: 1,
        strokeColor: '#ffffff',
        strokeWeight: 2
    };

    if (!markers[t.deviceSn]) {

        markers[t.deviceSn] = new google.maps.Marker({
            map: deviceMap,
            position: position,
            title: t.deviceName || t.deviceSn,
            icon: circleIcon
        });

        // Create blue radius circle like Google location
        deviceCircles[t.deviceSn] = new google.maps.Circle({
            strokeColor: '#3b82f6',
            strokeOpacity: 0.8,
            strokeWeight: 1,
            fillColor: '#3b82f6',
            fillOpacity: 0.15,
            map: deviceMap,
            center: position,
            radius: 14 // meters
        });

        infoWindows[t.deviceSn] = new google.maps.InfoWindow({
            content: buildInfoContent(t),
            maxWidth: 300
        });

        markers[t.deviceSn].addListener("click", () => {
            closeAllInfoWindows();
            infoWindows[t.deviceSn].open(deviceMap, markers[t.deviceSn]);
            focusDevice(t.deviceSn);
        });

    } else {

        // Update marker position
        markers[t.deviceSn].setPosition(position);

        // Move circle with marker
        if (deviceCircles[t.deviceSn]) {
            deviceCircles[t.deviceSn].setCenter(position);
        }

        infoWindows[t.deviceSn].setContent(buildInfoContent(t));
    }
}

    function createPulseEffect(deviceSn) {
        if (pulseIntervals[deviceSn]) {
            clearInterval(pulseIntervals[deviceSn]);
        }
        
        let radius = 20;
        let growing = true;
        
        pulseIntervals[deviceSn] = setInterval(() => {
            if (growing) {
                radius += 2;
                if (radius >= 40) growing = false;
            } else {
                radius -= 2;
                if (radius <= 20) growing = true;
            }
        }, 50);
    }

    /***************************************************
     * ANIMATION LOOP
     ***************************************************/
    function startAnimationLoop() {
        if (animationFrame) {
            cancelAnimationFrame(animationFrame);
        }
        
        function animate() {
            const now = Date.now();
            
            Object.keys(markers).forEach(deviceSn => {
                const marker = markers[deviceSn];
                const currentData = telemetryMap[deviceSn];
                const prevPos = previousPositions[deviceSn];
                
                if (currentData && prevPos && marker && currentData.latitude && currentData.longitude) {
                    const timeDiff = now - prevPos.timestamp;
                    const animationDuration = 2500;
                    
                    if (timeDiff < animationDuration) {
                        const progress = timeDiff / animationDuration;
                        const easedProgress = easeInOutCubic(progress);
                        
                        const currentLat = prevPos.lat + (currentData.latitude - prevPos.lat) * easedProgress;
                        const currentLng = prevPos.lng + (currentData.longitude - prevPos.lng) * easedProgress;
                        
                        marker.setPosition({
                            lat: currentLat,
                            lng: currentLng
                        });
                    }
                }
            });
            
            animationFrame = requestAnimationFrame(animate);
        }
        
        animate();
    }

    function easeInOutCubic(x) {
        return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
    }

    /***************************************************
     * FOCUS DEVICE
     ***************************************************/
    function focusDevice(sn) {
        const m = markers[sn];
        if (!m || !deviceMap) return;
        
        selectedDeviceSn = sn;
        $('.device-card').removeClass('selected');
        $(`.device-card[data-sn="${sn}"]`).addClass('selected');
        
        deviceMap.panTo(m.getPosition());
        deviceMap.setZoom(18);
        
        closeAllInfoWindows();
        if (infoWindows[sn]) {
            infoWindows[sn].open(deviceMap, m);
        }
        
        showSelectedDeviceInfo(sn);
        highlightMarker(sn);
    }

    function showSelectedDeviceInfo(sn) {
        const device = devicesMaster.find(d => d.serialNo === sn);
        const telemetry = telemetryMap[sn];
        
        if (!device) return;
        
        const fenceStatus = telemetry && telemetry.latitude && telemetry.longitude ? 
            getDeviceFenceStatus(new google.maps.LatLng(telemetry.latitude, telemetry.longitude)) : 
            null;
        
        const info = `
            <div style="color: white;">
                <h4 style="margin:0 0 10px 0;">${device.serialNo}</h4>
                <table style="width:100%; font-size:0.9rem;">
                    <tr>
                        <td>Status:</td>
                        <td><strong>${device.isOnline ? '🟢 Online' : '🔴 Offline'}</strong></td>
                    </tr>
                    ${telemetry ? `
                        <tr>
                            <td>Speed:</td>
                            <td><strong>${telemetry.speedKmh || 0} km/h</strong></td>
                        </tr>
                        <tr>
                            <td>Location:</td>
                            <td><small>${telemetry.latitude.toFixed(6)}, ${telemetry.longitude.toFixed(6)}</small></td>
                        </tr>
                        <tr>
                            <td>Last Update:</td>
                            <td><small>${new Date(telemetry.timestamp).toLocaleTimeString()}</small></td>
                        </tr>
                        ${fenceStatus?.hotspot ? `
                            <tr>
                                <td>Hotspot:</td>
                                <td><span style="background:rgba(255,255,255,0.2); padding:2px 6px; border-radius:12px;">${fenceStatus.hotspot}</span></td>
                            </tr>
                        ` : ''}
                    ` : ''}
                </table>
            </div>
        `;
        
        $('#selected_device_details').html(info);
        $('#selected_device_info').slideDown();
    }

    function highlightMarker(sn) {
        const marker = markers[sn];
        if (!marker) return;
    }

    function clearSelection() {
        selectedDeviceSn = null;
        $('.device-card').removeClass('selected');
        $('#selected_device_info').slideUp();
        closeAllInfoWindows();
        fitMapToMarkers();
    }

    function showAllDevices() {
        clearSelection();
    }

    /***************************************************
     * GEOFENCE FUNCTIONS
     ***************************************************/
    function loadGeofences() {
        controller.getAuthRequest(
            API_BASE + "geofences?size=1000",
            true,
            res => {
                geofences = res?.content || [];
                if (deviceMap) {
                    drawGeofences();
                }
            }
        );
    }

function drawGeofences() {
    if (!deviceMap) return;
    
    // Clear existing shapes
    Object.values(geofenceShapes).flat().forEach(s => {
        if (s) s.setMap(null);
    });
    geofenceShapes = { hotspots: [], stations: [], routes: [] };

    geofences.forEach(f => {
        const name = f.name;
        const color = f.colorHex || "#01020a";

        // ============================================
        // HOTSPOT (Circle)
        // ============================================
        if (f.hotspot === true && f.centerLat && f.centerLng) {
            const c = new google.maps.Circle({
                map: deviceMap,
                center: { lat: f.centerLat, lng: f.centerLng },
                radius: f.radiusMeters || 100,
                fillColor: color,
                fillOpacity: 0.25,
                strokeColor: color,
                strokeWeight: 2,
                strokeOpacity: 0.9,
                clickable: true,
                zIndex: 2
            });

            attachGeofenceHover(c, {
                name,
                type: "Hotspot",
                description: f.description,
                id: f.id,
                metadata: f
            });
            
            c.set("name", name);
            c.set("id", f.id);
            c.set("metadata", f);
            geofenceShapes.hotspots.push(c);
        }

        // ============================================
        // STATION
        // ============================================
        if (f.station === true) {
            
            // Case 1: Station as CIRCLE
            if (f.fenceType === "CIRCLE" && f.centerLat && f.centerLng) {
                const c = new google.maps.Circle({
                    map: deviceMap,
                    center: { lat: f.centerLat, lng: f.centerLng },
                    radius: f.radiusMeters || 100,
                    fillColor: color,
                    fillOpacity: 0.2,
                    strokeColor: color,
                    strokeWeight: 2,
                    strokeOpacity: 0.8,
                    clickable: true,
                    zIndex: 1
                });

                attachGeofenceHover(c, {
                    name,
                    type: "Station",
                    description: f.description,
                    stationType: f.stationType,
                    dwellTime: f.dwellTimeSeconds,
                    id: f.id,
                    metadata: f
                });
                
                c.set("name", name);
                c.set("id", f.id);
                c.set("metadata", f);
                geofenceShapes.stations.push(c);
            }
            
            // Case 2: Station as POLYGON
            else if (f.coordinatesJson && (f.fenceType === "POLYGON" || f.fenceType === "LINE")) {
                try {
                    let paths = JSON.parse(f.coordinatesJson);
                    
                    // Convert [lng, lat] format if needed
                    let processedPaths = paths;
                    if (paths.length > 0 && Array.isArray(paths[0])) {
                        if (paths[0].length === 2) {
                            processedPaths = paths.map(coord => ({
                                lat: coord[1],
                                lng: coord[0]
                            }));
                        }
                    }

                    // Check if it's a polygon (should close) or line
                    const isPolygon = processedPaths.length >= 3 && 
                        processedPaths[0].lat === processedPaths[processedPaths.length-1].lat &&
                        processedPaths[0].lng === processedPaths[processedPaths.length-1].lng;

                    if (isPolygon || f.fenceType === "POLYGON") {
                        // Draw as Polygon
                        const p = new google.maps.Polygon({
                            map: deviceMap,
                            paths: processedPaths,
                            fillColor: color,
                            fillOpacity: 0.2,
                            strokeColor: color,
                            strokeWeight: 2,
                            strokeOpacity: 0.8,
                            clickable: true,
                            zIndex: 1
                        });

                        attachGeofenceHover(p, {
                            name,
                            type: "Station (Polygon)",
                            description: f.description,
                            stationType: f.stationType,
                            id: f.id,
                            metadata: f
                        });
                        
                        p.set("name", name);
                        p.set("id", f.id);
                        p.set("metadata", f);
                        geofenceShapes.stations.push(p);
                    } else {
                        // Draw as Polyline (for linear stations)
                        const line = new google.maps.Polyline({
                            map: deviceMap,
                            path: processedPaths,
                            strokeColor: color,
                            strokeOpacity: 0.9,
                            strokeWeight: 4,
                            clickable: true,
                            geodesic: true,
                            zIndex: 1
                        });

                        attachGeofenceHover(line, {
                            name,
                            type: "Station (Linear)",
                            description: f.description,
                            stationType: f.stationType,
                            id: f.id,
                            metadata: f
                        });
                        
                        line.set("name", name);
                        line.set("id", f.id);
                        line.set("metadata", f);
                        geofenceShapes.stations.push(line);
                    }
                } catch (e) {
                    console.error("Error parsing station coordinates:", e, f);
                }
            }
        }

        // ============================================
        // ROUTE - Smooth line (NO ARROWS)
        // ============================================
        if (f.route === true && f.coordinatesJson) {
            try {
                let paths = JSON.parse(f.coordinatesJson);
                
                // Convert [lng, lat] format if needed
                let processedPaths = paths;
                if (paths.length > 0 && Array.isArray(paths[0])) {
                    if (paths[0].length === 2) {
                        processedPaths = paths.map(coord => ({
                            lat: coord[1],
                            lng: coord[0]
                        }));
                    }
                }

                // Determine line style based on route status
                const strokeWeight = f.routeStatus === 'ACTIVE' ? 5 : 4;
                const strokeOpacity = f.routeStatus === 'ACTIVE' ? 1 : 0.7;
                
                // SMOOTH LINE - NO ARROWS (icons array removed)
                const r = new google.maps.Polyline({
                    map: deviceMap,
                    path: processedPaths,
                    strokeColor: color,
                    strokeOpacity: strokeOpacity,
                    strokeWeight: strokeWeight,
                    clickable: true,
                    geodesic: true,
                    zIndex: f.routeStatus === 'ACTIVE' ? 10 : 5
                    // NO icons property = smooth continuous line
                });

                // Add route metadata for hover
                const routeInfo = {
                    name,
                    type: "Route",
                    description: f.description,
                    status: f.routeStatus,
                    distance: calculateRouteDistance(processedPaths),
                    waypoints: processedPaths.length,
                    id: f.id,
                    metadata: f
                };

                attachGeofenceHover(r, routeInfo);
                
                r.set("name", name);
                r.set("id", f.id);
                r.set("metadata", f);
                geofenceShapes.routes.push(r);

                // Add start and end markers for routes (optional - remove if you don't want markers)
                if (processedPaths.length > 0) {
                    // Start marker
                    const startMarker = new google.maps.Marker({
                        map: deviceMap,
                        position: processedPaths[0],
                        icon: {
                            path: google.maps.SymbolPath.CIRCLE,
                            scale: 8,
                            fillColor: '#10b981',
                            fillOpacity: 1,
                            strokeColor: '#FFFFFF',
                            strokeWeight: 2
                        },
                        title: 'Route Start',
                        zIndex: 20
                    });
                    
                    // End marker
                    const endMarker = new google.maps.Marker({
                        map: deviceMap,
                        position: processedPaths[processedPaths.length - 1],
                        icon: {
                            path: google.maps.SymbolPath.CIRCLE,
                            scale: 8,
                            fillColor: '#ef4444',
                            fillOpacity: 1,
                            strokeColor: '#FFFFFF',
                            strokeWeight: 2
                        },
                        title: 'Route End',
                        zIndex: 20
                    });
                    
                    // Store markers to manage them later
                    geofenceShapes.routes.push(startMarker);
                    geofenceShapes.routes.push(endMarker);
                }
            } catch (e) {
                console.error("Error parsing route coordinates:", e, f);
            }
        }
    });

    applyGeofenceFilters();
    updateStats();
}


function calculateRouteDistance(path) {
    if (!path || path.length < 2) return 0;
    
    let distance = 0;
    for (let i = 0; i < path.length - 1; i++) {
        const p1 = new google.maps.LatLng(path[i].lat, path[i].lng);
        const p2 = new google.maps.LatLng(path[i + 1].lat, path[i + 1].lng);
        distance += google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
    }
    return (distance / 1000).toFixed(2); // Return in kilometers
}
    function attachGeofenceHover(shape, meta) {
        if (!shape) return;
        
        shape.addListener("mouseover", e => {
            let position = e?.latLng;

            if (shape instanceof google.maps.Circle) {
                position = shape.getCenter();
            }

            if (shape instanceof google.maps.Polygon && shape.getPath) {
                const bounds = new google.maps.LatLngBounds();
                shape.getPath().forEach(p => bounds.extend(p));
                position = bounds.getCenter();
            }

            if (position && geofenceHoverInfo) {
                geofenceHoverInfo.setContent(`
                    <div class="geofence-hover-card">
                        <div class="geofence-hover-title">
                            ${meta.name}
                        </div>
                        <div class="geofence-hover-type">
                            ${meta.type}
                        </div>
                        ${meta.description ? `
                            <div class="geofence-hover-desc">
                                ${meta.description}
                            </div>
                        ` : ''}
                    </div>
                `);

                geofenceHoverInfo.setPosition(position);
                geofenceHoverInfo.open(deviceMap);
            }
        });

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

    function applyGeofenceFilters() {
        if (!deviceMap) return;
        
        const showHotspots = $("#filter_hotspots").is(":checked");
        const showStations = $("#filter_stations").is(":checked");
        const showRoutes = $("#filter_routes").is(":checked");

        toggleShapeGroup(geofenceShapes.hotspots, showHotspots);
        toggleShapeGroup(geofenceShapes.stations, showStations);
        toggleShapeGroup(geofenceShapes.routes, showRoutes);
    }

    function toggleShapeGroup(group, visible) {
        group.forEach(shape => {
            if (shape) {
                shape.setMap(visible ? deviceMap : null);
            }
        });
    }
/***************************************************
 * DEVICE ↔ GEOFENCE CHECK - FIXED VERSION
 ***************************************************/
function getDeviceFenceStatus(latLng) {
    let result = { hotspot: null, station: null, route: null };

    // Check if google.maps.geometry is available
    if (!google.maps.geometry) {
        console.warn("Google Maps geometry library not loaded");
        return result;
    }

    // Check hotspots (circles)
    if (geofenceShapes.hotspots && geofenceShapes.hotspots.length > 0) {
        geofenceShapes.hotspots.forEach(c => {
            if (c && typeof c.getCenter === 'function' && typeof c.getRadius === 'function') {
                try {
                    const distance = google.maps.geometry.spherical.computeDistanceBetween(latLng, c.getCenter());
                    if (distance <= c.getRadius()) {
                        result.hotspot = c.get("name") || "Unknown Hotspot";
                    }
                } catch (e) {
                    console.warn("Error checking hotspot:", e);
                }
            }
        });
    }

    // Check stations (polygons)
    if (geofenceShapes.stations && geofenceShapes.stations.length > 0) {
        geofenceShapes.stations.forEach(p => {
            if (p && typeof p.getPath === 'function') {
                try {
                    const path = p.getPath();
                    if (path && typeof path.getLength === 'function' && path.getLength() > 0) {
                        if (google.maps.geometry.poly.containsLocation(latLng, p)) {
                            result.station = p.get("name") || "Unknown Station";
                        }
                    }
                } catch (e) {
                    console.warn("Error checking station:", e);
                }
            }
        });
    }

    // Check routes (polylines)
    if (geofenceShapes.routes && geofenceShapes.routes.length > 0) {
        geofenceShapes.routes.forEach(r => {
            if (r && typeof r.getPath === 'function') {
                try {
                    const path = r.getPath();
                    if (path && typeof path.getLength === 'function' && path.getLength() > 0) {
                        // Use a small threshold for line proximity (10 meters)
                        if (google.maps.geometry.poly.isLocationOnEdge(latLng, r, 10)) {
                            result.route = r.get("name") || "Unknown Route";
                        }
                    }
                } catch (e) {
                    console.warn("Error checking route:", e);
                }
            }
        });
    }

    return result;
}

    /***************************************************
     * INFO WINDOW
     ***************************************************/
/***************************************************
 * INFO WINDOW - FIXED VERSION
 ***************************************************/
function buildInfoContent(d) {
    let fenceStatus = { hotspot: null, station: null, route: null };
    
    try {
        if (d.latitude && d.longitude && google.maps && google.maps.geometry) {
            fenceStatus = getDeviceFenceStatus(new google.maps.LatLng(d.latitude, d.longitude));
        }
    } catch (e) {
        console.warn("Error getting fence status:", e);
    }
    
    // Format timestamp
    let timeString = 'N/A';
    try {
        if (d.timestamp) {
            timeString = new Date(d.timestamp).toLocaleTimeString();
        }
    } catch (e) {
        console.warn("Error formatting timestamp:", e);
    }
    
    return `
        <div style="min-width: 250px; padding: 5px;">
            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                <div style="width: 30px; height: 30px; border-radius: 50%; background: ${d.speedKmh > 0 ? '#ffb703' : '#06d6a0'}; display: flex; align-items: center; justify-content: center; color: white;">
                    <i class="fas fa-truck"></i>
                </div>
                <div>
                    <strong style="font-size: 1.1rem;">${d.deviceName || d.deviceSn || 'Unknown Device'}</strong>
                </div>
            </div>
            <hr style="margin: 5px 0;">
            <table style="width:100%; font-size:0.9rem;">
                <tr>
                    <td>📍 Position:</td>
                    <td><small>${d.latitude ? d.latitude.toFixed(6) : 'N/A'}, ${d.longitude ? d.longitude.toFixed(6) : 'N/A'}</small></td>
                </tr>
                <tr>
                    <td>🚗 Speed:</td>
                    <td><strong>${d.speedKmh || 0} km/h</strong></td>
                </tr>
                <tr>
                    <td>🕒 Time:</td>
                    <td>${timeString}</td>
                </tr>
                ${d.mileageKm ? `
                    <tr>
                        <td>📊 Mileage:</td>
                        <td>${Math.round(d.mileageKm).toLocaleString()} km</td>
                    </tr>
                ` : ''}
                ${fenceStatus.hotspot ? `
                    <tr>
                        <td>🔥 Hotspot:</td>
                        <td><span style="background: #4361ee20; padding:2px 8px; border-radius:12px;">${fenceStatus.hotspot}</span></td>
                    </tr>
                ` : ''}
                ${fenceStatus.station ? `
                    <tr>
                        <td>🏢 Station:</td>
                        <td><span style="background: #4361ee20; padding:2px 8px; border-radius:12px;">${fenceStatus.station}</span></td>
                    </tr>
                ` : ''}
                ${fenceStatus.route ? `
                    <tr>
                        <td>🛣️ Route:</td>
                        <td><span style="background: #4361ee20; padding:2px 8px; border-radius:12px;">${fenceStatus.route}</span></td>
                    </tr>
                ` : ''}
            </table>
        </div>
    `;
}

    /***************************************************
     * UTILITY FUNCTIONS
     ***************************************************/
    function closeAllInfoWindows() {
        Object.values(infoWindows).forEach(iw => {
            if (iw) iw.close();
        });
    }

    function openGeofences() {
        window.location.href = "#app/multitracking";
    }

    function refreshDevices() {
        loadDevicesList();
        loadTelemetryRealtime();
    }

  function toggleDeviceList() {
    $('.devices-panel').toggleClass('collapsed');
    
    // Update button icon
    const $btn = $('.toggle-device-panel i');
    if ($('.devices-panel').hasClass('collapsed')) {
        $btn.removeClass('fa-chevron-left').addClass('fa-chevron-right');
    } else {
        $btn.removeClass('fa-chevron-right').addClass('fa-chevron-left');
    }
    
    // Force map to resize after animation
    setTimeout(() => {
        if (deviceMap) {
            google.maps.event.trigger(deviceMap, 'resize');
        }
    }, 300);
}
   

function toggleInfoPanel() {
    $('.info-panel').toggleClass('collapsed');
    
    // Update button icon
    const $btn = $('.toggle-info-panel i');
    if ($('.info-panel').hasClass('collapsed')) {
        $btn.removeClass('fa-chevron-right').addClass('fa-chevron-left');
    } else {
        $btn.removeClass('fa-chevron-left').addClass('fa-chevron-right');
    }
    
    // Force map to resize after animation
    setTimeout(() => {
        if (deviceMap) {
            google.maps.event.trigger(deviceMap, 'resize');
        }
    }, 300);
}

    function showroutesassigned(deviceSerialNumber) {
        $.ajax({
            url: serverURL + "telemetry/device/" + deviceSerialNumber + "?page=0&size=10",
            type: "GET",
            dataType: "json",
            headers: {
                Authorization: "Bearer " + userObj.accessToken,
                "Content-Type": "application/json"
            },
            success: function (response) {
                if (!response.content || response.content.length < 2) {
                    alert("Not enough data to draw path");
                    return;
                }
            },
            error: function () {
                alert("Failed to load device history");
            }
        });
    }

    // Make functions globally accessible
    window.focusDevice = focusDevice;
    window.filterDevices = filterDevices;
    window.filterDeviceList = filterDeviceList;
    window.changeMapType = changeMapType;
    window.fitMapToMarkers = fitMapToMarkers;
    window.centerMap = centerMap;
    window.applyGeofenceFilters = applyGeofenceFilters;
    window.openGeofences = openGeofences;
    window.refreshDevices = refreshDevices;
    window.toggleDeviceList = toggleDeviceList;
    window.toggleInfoPanel = toggleInfoPanel;
    window.showAllDevices = showAllDevices;
    window.clearSelection = clearSelection;
}