function dashboad() {
    var htmlsection = `
    <div class="modern-fleet-dashboard">
        <!-- Header with Date/Time and Refresh -->
        <div class="dashboard-header">
            <div class="header-left">
                <h1><i class="fas fa-tachometer-alt"></i> Fleet Command Center</h1>
                <div class="live-indicator">
                    <span class="pulse-dot"></span>
                    <span>LIVE</span>
                </div>
            </div>
            <div class="header-right">
                <div class="datetime" id="current_datetime"></div>
                <button class="btn-refresh" onclick="refreshDashboard()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
        </div>

        <!-- KPI Cards -->
        <div class="kpi-grid">
            <div class="kpi-card total">
                <div class="kpi-icon">
                    <i class="fas fa-truck"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Total Fleet</span>
                    <span class="kpi-value" id="dash_total_devices">--</span>
                    <span class="kpi-trend" id="total_trend">+0%</span>
                </div>
            </div>

            <div class="kpi-card online">
                <div class="kpi-icon">
                    <i class="fas fa-wifi"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Online</span>
                    <span class="kpi-value" id="dash_online">--</span>
                    <span class="kpi-sub">Active Now</span>
                </div>
            </div>

            <div class="kpi-card offline">
                <div class="kpi-icon">
                    <i class="fas fa-power-off"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Offline</span>
                    <span class="kpi-value" id="dash_offline">--</span>
                    <span class="kpi-sub">No Signal</span>
                </div>
            </div>

            <div class="kpi-card moving">
                <div class="kpi-icon">
                    <i class="fas fa-forward"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Moving</span>
                    <span class="kpi-value" id="dash_moving">--</span>
                    <span class="kpi-sub">Speed > 0 km/h</span>
                </div>
            </div>

            <div class="kpi-card stopped">
                <div class="kpi-icon">
                    <i class="fas fa-pause-circle"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Stopped</span>
                    <span class="kpi-value" id="dash_stopped">--</span>
                    <span class="kpi-sub">Idle Vehicles</span>
                </div>
            </div>

            <div class="kpi-card geofence">
                <div class="kpi-icon">
                    <i class="fas fa-draw-polygon"></i>
                </div>
                <div class="kpi-content">
                    <span class="kpi-label">Geofences</span>
                    <span class="kpi-value" id="dash_geofences">--</span>
                    <span class="kpi-sub">Active Zones</span>
                </div>
            </div>
        </div>

        <!-- Main Dashboard Grid - NO MAP -->
        <div class="dashboard-grid">
            <!-- Left Column - Status Cards -->
            <div class="grid-item status-panel">
                <div class="panel-header">
                    <h3><i class="fas fa-chart-pie"></i> Fleet Status Overview</h3>
                </div>
                
                <div class="status-grid-large">
                    <div class="status-card-large inside-stations">
                        <div class="status-icon-wrapper">
                            <i class="fas fa-building"></i>
                        </div>
                        <div class="status-content">
                            <span class="status-label">Inside Stations</span>
                            <span class="status-value" id="dash_inside_stations">--</span>
                            <span class="status-trend">vehicles currently at stations</span>
                        </div>
                    </div>

                    <div class="status-card-large inside-hotspots">
                        <div class="status-icon-wrapper">
                            <i class="fas fa-fire"></i>
                        </div>
                        <div class="status-content">
                            <span class="status-label">Inside Hotspots</span>
                            <span class="status-value" id="dash_inside_hotspots">--</span>
                            <span class="status-trend">vehicles in danger zones</span>
                        </div>
                    </div>

                    <div class="status-card-large overspeed">
                        <div class="status-icon-wrapper">
                            <i class="fas fa-tachometer-alt"></i>
                        </div>
                        <div class="status-content">
                            <span class="status-label">Overspeed</span>
                            <span class="status-value" id="dash_overspeed">--</span>
                            <span class="status-trend">exceeding speed limit</span>
                        </div>
                    </div>

                    <div class="status-card-large idle">
                        <div class="status-icon-wrapper">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="status-content">
                            <span class="status-label">Idle > 30min</span>
                            <span class="status-value" id="dash_idle">--</span>
                            <span class="status-trend">vehicles idling</span>
                        </div>
                    </div>
                </div>

                <!-- System Health -->
                <div class="system-health">
                    <h4><i class="fas fa-heartbeat"></i> System Health</h4>
                    <div class="health-metrics">
                        <div class="metric">
                            <span>API Latency</span>
                            <span id="api_latency">--</span>
                        </div>
                        <div class="metric">
                            <span>Last Update</span>
                            <span id="last_update_time">--</span>
                        </div>
                        <div class="metric">
                            <span>Data Points</span>
                            <span id="data_points">--</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Column - Alerts and Rankings -->
            <div class="grid-item analytics-panel">
                <!-- Fleet Status Tabs -->
                <div class="analytics-tabs">
                    <button class="tab-btn active" onclick="switchAnalyticsTab('alerts')">
                        <i class="fas fa-exclamation-triangle"></i> Alerts
                    </button>
                    <button class="tab-btn" onclick="switchAnalyticsTab('ranking')">
                        <i class="fas fa-trophy"></i> Rankings
                    </button>
                    <button class="tab-btn" onclick="switchAnalyticsTab('devices')">
                        <i class="fas fa-microchip"></i> Devices
                    </button>
                </div>

                <!-- Alerts Tab Content -->
                <div id="alerts-tab" class="tab-content active">
                    <div class="alerts-header">
                        <h4>Recent Alerts</h4>
                        <span class="alert-badge" id="alert_count">0</span>
                    </div>
                    <div class="alerts-list" id="alerts_container">
                        <div class="alert-item info">
                            <i class="fas fa-info-circle"></i>
                            <div class="alert-content">
                                <span class="alert-title">System Normal</span>
                                <span class="alert-time">No active alerts</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Rankings Tab Content -->
                <div id="ranking-tab" class="tab-content">
                    <div class="ranking-sections">
                        <!-- Last Contact Rankings -->
                        <div class="ranking-section">
                            <h4><i class="fas fa-history"></i> Last Contact</h4>
                            <div class="ranking-list" id="last_contact_ranking"></div>
                        </div>

                        <!-- Top Moving Rankings -->
                        <div class="ranking-section">
                            <h4><i class="fas fa-tachometer-alt"></i> Fastest Vehicles</h4>
                            <div class="ranking-list" id="top_moving_ranking"></div>
                        </div>
                    </div>
                </div>

                <!-- Devices Tab Content -->
                <div id="devices-tab" class="tab-content">
                    <div class="devices-header">
                        <div class="search-box">
                            <i class="fas fa-search"></i>
                            <input type="text" id="deviceSearch" placeholder="Search devices...">
                        </div>
                    </div>
                    <div class="devices-list" id="devices_list">
                        <!-- Devices will be loaded here -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Stats Bar -->
       
    </div>

    <style>
        /* Modern Fleet Dashboard - Clean, Professional Design */
        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --dark: #1e293b;
            --light: #f8fafc;
            --gray: #94a3b8;
            --border: #e2e8f0;
            --shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
            --radius: 12px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .modern-fleet-dashboard {
            padding: 1px;
            background: #f1f5f9;
            min-height: 100vh;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        /* Header Styles */
        .dashboard-header {
            background: white;
            border-radius: var(--radius);
            padding: 20px 30px;
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .header-left h1 {
            margin: 0;
            font-size: 1.5rem;
            color: var(--dark);
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .header-left h1 i {
            color: var(--primary);
        }

        .live-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            background: rgba(239, 68, 68, 0.1);
            padding: 6px 14px;
            border-radius: 40px;
            color: var(--danger);
            font-weight: 600;
            font-size: 0.85rem;
        }

        .pulse-dot {
            width: 8px;
            height: 8px;
            background: var(--danger);
            border-radius: 50%;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.5); opacity: 0.5; }
            100% { transform: scale(1); opacity: 1; }
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .datetime {
            font-size: 0.95rem;
            color: var(--gray);
            font-weight: 500;
            background: var(--light);
            padding: 8px 16px;
            border-radius: 40px;
            border: 1px solid var(--border);
        }

        .btn-refresh {
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 40px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: var(--transition);
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
        }

        .btn-refresh:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(67, 97, 238, 0.4);
        }

        /* KPI Grid */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }

        .kpi-card {
            background: white;
            border-radius: var(--radius);
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            transition: var(--transition);
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
        }

        .kpi-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-lg);
        }

        .kpi-icon {
            width: 56px;
            height: 56px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.6rem;
            color: white;
        }

        .kpi-card.total .kpi-icon { background: linear-gradient(135deg, #4361ee 0%, #3a56d4 100%); }
        .kpi-card.online .kpi-icon { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
        .kpi-card.offline .kpi-icon { background: linear-gradient(135deg, #64748b 0%, #475569 100%); }
        .kpi-card.moving .kpi-icon { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
        .kpi-card.stopped .kpi-icon { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
        .kpi-card.geofence .kpi-icon { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); }

        .kpi-content {
            flex: 1;
        }

        .kpi-label {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--gray);
            display: block;
            margin-bottom: 4px;
        }

        .kpi-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--dark);
            line-height: 1.2;
            display: block;
        }

        .kpi-trend {
            font-size: 0.75rem;
            color: var(--success);
        }

        .kpi-sub {
            font-size: 0.7rem;
            color: var(--gray);
        }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            margin-bottom: 24px;
        }

        .grid-item {
            background: white;
            border-radius: var(--radius);
            overflow: hidden;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
        }

        .panel-header {
            padding: 20px;
            border-bottom: 1px solid var(--border);
            background: white;
        }

        .panel-header h3 {
            margin: 0;
            font-size: 1.1rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .panel-header h3 i {
            color: var(--primary);
        }

        /* Status Panel */
        .status-panel {
            padding: 0;
        }

        .status-grid-large {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
            padding: 20px;
        }

        .status-card-large {
            background: var(--light);
            border-radius: var(--radius);
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            transition: var(--transition);
            border: 1px solid var(--border);
        }

        .status-card-large:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }

        .status-icon-wrapper {
            width: 48px;
            height: 48px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            color: white;
        }

        .inside-stations .status-icon-wrapper { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); }
        .inside-hotspots .status-icon-wrapper { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
        .overspeed .status-icon-wrapper { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
        .idle .status-icon-wrapper { background: linear-gradient(135deg, #64748b 0%, #475569 100%); }

        .status-content {
            flex: 1;
        }

        .status-label {
            font-size: 0.8rem;
            color: var(--gray);
            display: block;
            margin-bottom: 4px;
        }

        .status-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--dark);
            line-height: 1.2;
            display: block;
        }

        .status-trend {
            font-size: 0.7rem;
            color: var(--gray);
        }

        /* System Health */
        .system-health {
            margin: 0 20px 20px 20px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            padding: 20px;
            border-radius: var(--radius);
            color: white;
        }

        .system-health h4 {
            margin: 0 0 16px 0;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .health-metrics {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
        }

        .metric {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .metric span:first-child {
            font-size: 0.7rem;
            opacity: 0.8;
        }

        .metric span:last-child {
            font-size: 1.2rem;
            font-weight: 600;
        }

        /* Analytics Panel */
        .analytics-panel {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .analytics-tabs {
            display: flex;
            padding: 16px;
            gap: 8px;
            border-bottom: 1px solid var(--border);
        }

        .tab-btn {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 8px;
            background: var(--light);
            color: var(--gray);
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            font-size: 0.85rem;
        }

        .tab-btn i {
            font-size: 0.9rem;
        }

        .tab-btn.active {
            background: var(--primary);
            color: white;
        }

        .tab-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* Alerts */
        .alerts-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

        .alerts-header h4 {
            margin: 0;
            font-size: 0.95rem;
            color: var(--dark);
        }

        .alert-badge {
            background: var(--danger);
            color: white;
            padding: 2px 8px;
            border-radius: 40px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .alerts-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .alert-item {
            background: var(--light);
            padding: 14px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            border-left: 4px solid;
        }

        .alert-item.info { border-left-color: #3b82f6; }
        .alert-item.warning { border-left-color: #f59e0b; }
        .alert-item.danger { border-left-color: #ef4444; }

        .alert-item i {
            font-size: 1.1rem;
        }

        .alert-item.info i { color: #3b82f6; }
        .alert-item.warning i { color: #f59e0b; }
        .alert-item.danger i { color: #ef4444; }

        .alert-content {
            flex: 1;
        }

        .alert-title {
            font-weight: 600;
            color: var(--dark);
            font-size: 0.9rem;
            display: block;
            margin-bottom: 4px;
        }

        .alert-time {
            font-size: 0.7rem;
            color: var(--gray);
        }

        /* Rankings */
        .ranking-sections {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .ranking-section h4 {
            margin: 0 0 12px 0;
            font-size: 0.9rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ranking-list {
            background: var(--light);
            border-radius: 12px;
            overflow: hidden;
        }

        .ranking-item {
            padding: 12px;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ranking-item:last-child {
            border-bottom: none;
        }

        .ranking-position {
            width: 24px;
            height: 24px;
            border-radius: 6px;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.75rem;
            color: var(--gray);
        }

        .ranking-info {
            flex: 1;
        }

        .ranking-name {
            font-weight: 500;
            color: var(--dark);
            font-size: 0.85rem;
        }

        .ranking-detail {
            font-size: 0.7rem;
            color: var(--gray);
        }

        .ranking-value {
            font-weight: 600;
            color: var(--primary);
            font-size: 0.85rem;
        }

        /* Devices Tab */
        .devices-header {
            margin-bottom: 16px;
        }

        .search-box {
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
        }

        .search-box input {
            width: 100%;
            padding: 10px 10px 10px 36px;
            border: 1px solid var(--border);
            border-radius: 40px;
            font-size: 0.85rem;
        }

        .devices-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .device-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            border-bottom: 1px solid var(--border);
            transition: var(--transition);
        }

        .device-item:hover {
            background: var(--light);
        }

        .device-status {
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }

        .device-status.online { background: var(--success); box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2); }
        .device-status.offline { background: var(--gray); }

        .device-info {
            flex: 1;
        }

        .device-name {
            font-weight: 500;
            color: var(--dark);
            font-size: 0.9rem;
        }

        .device-sn {
            font-size: 0.7rem;
            color: var(--gray);
        }

        .device-meta {
            display: flex;
            gap: 12px;
            font-size: 0.7rem;
            color: var(--gray);
        }

        /* Quick Stats Bar */
        .quick-stats-bar {
            background: white;
            border-radius: var(--radius);
            padding: 16px 24px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-around;
            align-items: center;
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .stat-item i {
            font-size: 1.2rem;
        }

        .stat-item span {
            color: var(--gray);
            font-size: 0.85rem;
        }

        .stat-item strong {
            color: var(--dark);
            font-size: 1rem;
            font-weight: 600;
        }

        /* Quick Actions Bar */
        .quick-actions-bar {
            background: white;
            border-radius: var(--radius);
            padding: 16px 24px;
            display: flex;
            justify-content: center;
            gap: 16px;
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
        }

        .quick-action {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border: none;
            background: var(--light);
            border-radius: 40px;
            color: var(--dark);
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            font-size: 0.9rem;
        }

        .quick-action:hover {
            background: var(--primary);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
        }

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

        ::-webkit-scrollbar-track {
            background: var(--light);
            border-radius: 10px;
        }

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

        /* Responsive */
        @media (max-width: 1400px) {
            .kpi-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 1024px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
            
            .kpi-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .modern-fleet-dashboard { padding: 16px; }
            .kpi-grid { grid-template-columns: 1fr; }
            .quick-actions-bar { flex-wrap: wrap; }
            .quick-stats-bar { flex-wrap: wrap; gap: 16px; }
        }
    </style>
    `;

    $(".crud_section").html(htmlsection);
    
    // Initialize dashboard
    initDashboard();
}

// Global variables
let refreshInterval = null;

function initDashboard() {
    // Start real-time clock
    updateDateTime();
    setInterval(updateDateTime, 1000);
    
    // Load all data
    loadDashboardData();
    loadAdvancedFleetMetrics();
    loadDevicesList();
    
    // Auto-refresh every 30 seconds
    if (refreshInterval) clearInterval(refreshInterval);
    refreshInterval = setInterval(() => {
        refreshDashboard();
    }, 30000);
}

function updateDateTime() {
    const now = new Date();
    const formatted = now.toLocaleString('en-US', {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    $('#current_datetime').text(formatted);
}

function loadDashboardData() {
    const startTime = performance.now();

    // DEVICES
    controller.getAuthRequest(
        API_BASE + "devices/all",
        true,
        devices => {
            const total = devices.length;
            const online = devices.filter(d => d.isOnline).length;
            const offline = total - online;

            animateNumber('#dash_total_devices', total);
            animateNumber('#dash_online', online);
            animateNumber('#dash_offline', offline);

            // Calculate operational percentage
            const operationalPercent = total > 0 ? Math.round((online / total) * 100) : 0;
            $('#operational_percent').text(operationalPercent + '%');

            // Calculate trend
            const prevTotal = parseInt($('#dash_total_devices').text()) || total;
            const trend = total > 0 ? ((total - prevTotal) / prevTotal * 100).toFixed(1) : 0;
            $('#total_trend').text(`${trend > 0 ? '+' : ''}${trend}%`);
        }
    );

    // TELEMETRY
    controller.getAuthRequest(
        serverURL + "telemetry/latest",
        true,
        data => {
            let moving = 0;
            let stopped = 0;
            let totalMileage = 0;

            data.forEach(d => {
                if ((d.speedKmh || 0) > 0) moving++;
                else stopped++;
                if (d.mileageKm) totalMileage += d.mileageKm;
            });

            animateNumber('#dash_moving', moving);
            animateNumber('#dash_stopped', stopped);
            animateNumber('#total_mileage', Math.round(totalMileage / 1000) + 'k');
            
            $('#data_points').text(data.length);
            $('#last_update_time').text(new Date().toLocaleTimeString());
        }
    );

    // GEOFENCES
    controller.getAuthRequest(
        serverURL + "geofences?size=1000",
        true,
        res => {
            const count = res?.content?.length || 0;
            animateNumber('#dash_geofences', count);
        }
    );

    // Update API latency
    const latency = Math.round(performance.now() - startTime);
    $('#api_latency').text(`${latency}ms`);
}

function loadDevicesList() {
    controller.getAuthRequest(
        API_BASE + "devices/all",
        true,
        devices => {
            let html = '';
            
            devices.slice(0, 10).forEach(device => {
                const statusClass = device.isOnline ? 'online' : 'offline';
                const statusText = device.isOnline ? 'Online' : 'Offline';
                
                html += `
                    <div class="device-item">
                        <span class="device-status ${statusClass}"></span>
                        <div class="device-info">
                            <div class="device-name">${device.name || 'Unnamed'}</div>
                            <div class="device-sn">${device.serialNo}</div>
                            <div class="device-meta">
                                <span>${device.make || 'N/A'}</span>
                                <span>IMEI: ${device.imei || 'N/A'}</span>
                            </div>
                        </div>
                        <span class="device-badge ${statusClass}">${statusText}</span>
                    </div>
                `;
            });
            
            $('#devices_list').html(html || '<div class="no-data">No devices found</div>');
            
            // Setup search
            $('#deviceSearch').on('keyup', function() {
                const term = $(this).val().toLowerCase();
                filterDevices(devices, term);
            });
        }
    );
}

function filterDevices(devices, term) {
    const filtered = devices.filter(d => 
        (d.name && d.name.toLowerCase().includes(term)) ||
        (d.serialNo && d.serialNo.toLowerCase().includes(term)) ||
        (d.imei && d.imei.toLowerCase().includes(term))
    );
    
    let html = '';
    filtered.slice(0, 10).forEach(device => {
        const statusClass = device.isOnline ? 'online' : 'offline';
        const statusText = device.isOnline ? 'Online' : 'Offline';
        
        html += `
            <div class="device-item">
                <span class="device-status ${statusClass}"></span>
                <div class="device-info">
                    <div class="device-name">${device.name || 'Unnamed'}</div>
                    <div class="device-sn">${device.serialNo}</div>
                    <div class="device-meta">
                        <span>${device.make || 'N/A'}</span>
                        <span>IMEI: ${device.imei || 'N/A'}</span>
                    </div>
                </div>
                <span class="device-badge ${statusClass}">${statusText}</span>
            </div>
        `;
    });
    
    $('#devices_list').html(html || '<div class="no-data">No matching devices</div>');
}

function animateNumber(selector, target) {
    const element = $(selector);
    const current = parseInt(element.text().replace(/[^0-9]/g, '')) || 0;
    const increment = (target - current) / 20;
    let step = 0;

    const interval = setInterval(() => {
        step++;
        const value = Math.round(current + (increment * step));
        if (selector === '#total_mileage') {
            element.text(value + 'k');
        } else {
            element.text(value);
        }
        
        if (step >= 20) {
            if (selector === '#total_mileage') {
                element.text(target + 'k');
            } else {
                element.text(target);
            }
            clearInterval(interval);
        }
    }, 30);
}

function switchAnalyticsTab(tab) {
    $('.tab-btn').removeClass('active');
    $(`.tab-btn:contains("${tab === 'alerts' ? 'Alerts' : tab === 'ranking' ? 'Rankings' : 'Devices'}")`).addClass('active');
    
    $('.tab-content').removeClass('active');
    $(`#${tab}-tab`).addClass('active');
}

function loadAdvancedFleetMetrics() {
    const SPEED_LIMIT = 80;
    const IDLE_LIMIT_MIN = 30;

    Promise.all([
        new Promise(res => controller.getAuthRequest(serverURL + "telemetry/latest", true, res)),
        new Promise(res => controller.getAuthRequest(serverURL + "geofences?size=1000", true, r => res(r?.content || [])))
    ])
    .then(([telemetry, geofences]) => {
        let insideStations = 0;
        let insideHotspots = 0;
        let overspeed = 0;
        let idle = 0;

        // Process geofences for geometry
        const stations = [];
        const hotspots = [];

        geofences.forEach(f => {
            if (f.station && f.coordinatesJson) {
                try {
                    stations.push({
                        name: f.name,
                        polygon: new google.maps.Polygon({ 
                            paths: JSON.parse(f.coordinatesJson) 
                        })
                    });
                } catch (e) {}
            }

            if (f.hotspot && f.centerLat && f.centerLng) {
                hotspots.push({
                    name: f.name,
                    center: new google.maps.LatLng(f.centerLat, f.centerLng),
                    radius: f.radiusMeters
                });
            }
        });

        const now = Date.now();
        const lastContacts = [];
        const topMoving = [];
        const alerts = [];

        telemetry.forEach(d => {
            if (!d.latitude || !d.longitude) return;

            const pos = new google.maps.LatLng(d.latitude, d.longitude);

            // Station check
            stations.forEach(s => {
                try {
                    if (google.maps.geometry.poly.containsLocation(pos, s.polygon))
                        insideStations++;
                } catch (e) {}
            });

            // Hotspot check
            hotspots.forEach(h => {
                try {
                    const dist = google.maps.geometry.spherical.computeDistanceBetween(pos, h.center);
                    if (dist <= h.radius) insideHotspots++;
                } catch (e) {}
            });

            // Overspeed
            if ((d.speedKmh || 0) > SPEED_LIMIT) {
                overspeed++;
                alerts.push({
                    type: 'danger',
                    title: 'Overspeed Alert',
                    vehicle: d.deviceName || d.deviceSn,
                    detail: `${d.speedKmh} km/h`,
                    time: 'Just now'
                });
            }

            // Idle
            if ((d.speedKmh || 0) === 0 && d.timestamp) {
                const diffMin = (now - new Date(d.timestamp).getTime()) / 60000;
                if (diffMin > IDLE_LIMIT_MIN) {
                    idle++;
                    alerts.push({
                        type: 'warning',
                        title: 'Idle Alert',
                        vehicle: d.deviceName || d.deviceSn,
                        detail: `${Math.round(diffMin)} min idle`,
                        time: 'Just now'
                    });
                }
            }

            // Last contact
            if (d.timestamp) {
                lastContacts.push({
                    sn: d.deviceName || d.deviceSn,
                    time: new Date(d.timestamp)
                });
            }

            // Top moving
            if ((d.speedKmh || 0) > 0) {
                topMoving.push({
                    sn: d.deviceName || d.deviceSn,
                    speed: d.speedKmh
                });
            }
        });

        animateNumber('#dash_inside_stations', insideStations);
        animateNumber('#dash_inside_hotspots', insideHotspots);
        animateNumber('#dash_overspeed', overspeed);
        animateNumber('#dash_idle', idle);
        $('#alert_count').text(alerts.length);

        renderLastContactRanking(lastContacts);
        renderTopMovingRanking(topMoving);
        renderAlerts(alerts);
    });
}

function renderLastContactRanking(list) {
    list.sort((a, b) => b.time - a.time);
    
    let html = '';
    list.slice(0, 5).forEach((item, index) => {
        const timeDiff = Math.round((Date.now() - item.time.getTime()) / 60000);
        const timeText = timeDiff < 1 ? 'Just now' : 
                        timeDiff < 60 ? `${timeDiff}m ago` : 
                        `${Math.round(timeDiff/60)}h ago`;
        
        html += `
            <div class="ranking-item">
                <div class="ranking-position">${index + 1}</div>
                <div class="ranking-info">
                    <span class="ranking-name">${item.sn}</span>
                    <span class="ranking-detail">${timeText}</span>
                </div>
                <div class="ranking-value">
                    <i class="fas fa-clock"></i>
                </div>
            </div>
        `;
    });
    
    $('#last_contact_ranking').html(html || '<div class="ranking-item">No data</div>');
}

function renderTopMovingRanking(list) {
    list.sort((a, b) => b.speed - a.speed);
    
    let html = '';
    list.slice(0, 5).forEach((item, index) => {
        html += `
            <div class="ranking-item">
                <div class="ranking-position">${index + 1}</div>
                <div class="ranking-info">
                    <span class="ranking-name">${item.sn}</span>
                    <span class="ranking-detail">Current speed</span>
                </div>
                <div class="ranking-value">${item.speed} km/h</div>
            </div>
        `;
    });
    
    $('#top_moving_ranking').html(html || '<div class="ranking-item">No vehicles moving</div>');
}

function renderAlerts(alerts) {
    if (alerts.length === 0) {
        $('#alerts_container').html(`
            <div class="alert-item info">
                <i class="fas fa-info-circle"></i>
                <div class="alert-content">
                    <span class="alert-title">All Systems Normal</span>
                    <span class="alert-time">No active alerts</span>
                </div>
            </div>
        `);
        return;
    }

    let html = '';
    alerts.slice(0, 8).forEach(alert => {
        html += `
            <div class="alert-item ${alert.type}">
                <i class="fas fa-exclamation-triangle"></i>
                <div class="alert-content">
                    <span class="alert-title">${alert.title} - ${alert.vehicle}</span>
                    <span class="alert-detail">${alert.detail}</span>
                    <span class="alert-time">${alert.time}</span>
                </div>
            </div>
        `;
    });
    
    $('#alerts_container').html(html);
}

function refreshDashboard() {
    $('.btn-refresh i').addClass('fa-spin');
    
    loadDashboardData();
    loadAdvancedFleetMetrics();
    loadDevicesList();
    
    setTimeout(() => {
        $('.btn-refresh i').removeClass('fa-spin');
    }, 1000);
}

// Clean up
$(window).on('unload', function() {
    if (refreshInterval) clearInterval(refreshInterval);
});