// Global variables
// Main function to load and display all devices
function allDevices(onlineFilter = 'all') {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="devices-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;

    $(".tab_devices").html(loadingHTML);

    // Determine which API endpoint to use based on filter
    let url;
    if (onlineFilter === 'online') {
        url = serverURL + "devices/online?status=true&size=1000";
    } else if (onlineFilter === 'offline') {
        url = serverURL + "devices/online?status=false&size=1000";
    } else {
        url = serverURL + "devices/all";
    }

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        async: true,
        success: function(res) {
            var data = res.content || res || [];
            
            // Calculate statistics
            const totalDevices = data.length;
            const onlineDevices = data.filter(d => d.isOnline === true).length;
            const offlineDevices = totalDevices - onlineDevices;
            const activeDevices = data.filter(d => d.active === true).length;
            const inactiveDevices = totalDevices - activeDevices;
            const assignedDevices = data.filter(d => d.vehicle !== null).length;
            const unassignedDevices = totalDevices - assignedDevices;

            var html = `
            <div class="devices-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                
                <!-- Header Section -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                        <div style="display: flex; align-items: center; gap: 16px;">
                            <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-microchip" style="color: #000;"></i>
                                Device Management
                            </h1>
                            <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                                ${totalDevices} Total
                            </span>
                        </div>
                        <div style="display: flex; gap: 12px;">
                            <button onclick="addNewDevice()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #000; color: white; border: none; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-plus"></i> Add Device
                            </button>
                            <button onclick="exportDevices()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #ffffff; color: #1a1f36; border: 1px solid #d0d5dd; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-download"></i> Export
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Statistics Cards -->
                <div style="display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 24px;">
                    <!-- Total Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-truck" style="font-size: 20px; color: #000;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;" id="stat-total">${totalDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Total</div>
                    </div>

                    <!-- Online Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allDevices('online')">
                        <div style="width: 40px; height: 40px; background: #e3f2fd; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-wifi" style="font-size: 20px; color: #1976d2;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1976d2;" id="stat-online">${onlineDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Online</div>
                    </div>

                    <!-- Offline Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allDevices('offline')">
                        <div style="width: 40px; height: 40px; background: #fee2e2; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-power-off" style="font-size: 20px; color: #dc2626;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #dc2626;" id="stat-offline">${offlineDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Offline</div>
                    </div>

                    <!-- Active Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #e8f5e9; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-check-circle" style="font-size: 20px; color: #2e7d32;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #2e7d32;" id="stat-active">${activeDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Active</div>
                    </div>

                    <!-- Assigned Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #fff3e0; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-link" style="font-size: 20px; color: #ed6c02;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #ed6c02;" id="stat-assigned">${assignedDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Assigned</div>
                    </div>

                    <!-- Unassigned Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #f3e5f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-unlink" style="font-size: 20px; color: #9c27b0;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #9c27b0;" id="stat-unassigned">${unassignedDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Unassigned</div>
                    </div>
                </div>

                <!-- Filter Chips -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; gap: 8px; flex-wrap: wrap;">
                    <button class="filter-chip ${onlineFilter === 'all' ? 'active' : ''}" data-filter="all" onclick="allDevices('all')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${onlineFilter === 'all' ? '#000' : 'white'}; color: ${onlineFilter === 'all' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <i class="fas fa-list"></i> All Devices
                    </button>
                    <button class="filter-chip ${onlineFilter === 'online' ? 'active' : ''}" data-filter="online" onclick="allDevices('online')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${onlineFilter === 'online' ? '#1976d2' : 'white'}; color: ${onlineFilter === 'online' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <i class="fas fa-wifi"></i> Online
                    </button>
                    <button class="filter-chip ${onlineFilter === 'offline' ? 'active' : ''}" data-filter="offline" onclick="allDevices('offline')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${onlineFilter === 'offline' ? '#dc2626' : 'white'}; color: ${onlineFilter === 'offline' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <i class="fas fa-power-off"></i> Offline
                    </button>
                </div>

                <!-- Search and Controls -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                    <div style="position: relative; flex: 1; max-width: 400px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="deviceSearch" placeholder="Search by name, serial, IMEI..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none; transition: all 0.2s;">
                    </div>
                    <div style="display: flex; gap: 12px;">
                        <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px; outline: none;">
                            <option value="10">10 per page</option>
                            <option value="25">25 per page</option>
                            <option value="50">50 per page</option>
                            <option value="100">100 per page</option>
                        </select>
                        <button onclick="allDevices('${onlineFilter}')" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>

                <!-- Devices Table -->
                <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
                    <table class="devices-table" id="devicetableview" style=" width: 100%; border-collapse: collapse; min-width: 1400px;">
                        <thead>
                            <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 40px;">
                                    <input type="checkbox" id="selectAll" style="width: 18px; height: 18px; cursor: pointer;">
                                </th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">#</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Device Info</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Serial & IMEI</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">SIM Cards</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Status</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Vehicle</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Last Seen</th>
                                <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="deviceTableBody">
            `;

            data.forEach((item, i) => {
                const deviceId = item.deviceId || i + 1;
                const serialNo = item.serialNo || item.serialNumber || 'N/A';
                
                html += `
                <tr data-device-id="${serialNo}" 
                    data-online="${item.isOnline}" 
                    data-active="${item.active}"
                    style="border-bottom: 1px solid #eaeef2; transition: background 0.2s;">
                    
                    <td style="padding: 16px;">
                        <input type="checkbox" class="row-checkbox" data-id="${serialNo}" style="width: 18px; height: 18px; cursor: pointer;">
                    </td>

                    <td style="padding: 16px; color: #5b677c;">${i + 1}</td>

                    <td style="padding: 16px;">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-microchip" style="color: #000;"></i>
                            </div>
                            <div>
                                <div style="font-weight: 600; color: #1a1f36;">${item.serialNo || 'Unnamed'}</div>
                                <div style="font-size: 12px; color: #5b677c;">${item.make || ''} ${item.model || ''} (${item.yearOfManufacture || 'N/A'})</div>
                            </div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div>
                            <div style="font-weight: 500; color: #1a1f36;">${serialNo}</div>
                            <div style="font-size: 12px; color: #5b677c;">IMEI: ${item.imei || 'N/A'}</div>
                            <div style="font-size: 11px; color: #94a3b8;">FW: ${item.firmwareVersion || 'N/A'}</div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div style="font-size: 13px; color: #1a1f36;">
                            <div><i class="fas fa-sim-card" style="width: 16px; color: #5b677c;"></i> SIM1: ${item.sim1Number || 'N/A'}</div>
                            <div style="margin-top: 4px;"><i class="fas fa-sim-card" style="width: 16px; color: #5b677c;"></i> SIM2: ${item.sim2Number || 'N/A'}</div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div style="display: flex; flex-direction: column; gap: 6px;">
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${item.isOnline ? '#e3f2fd' : '#fee2e2'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${item.isOnline ? '#1976d2' : '#dc2626'}; width: fit-content;">
                                <span style="width: 8px; height: 8px; border-radius: 50%; background: ${item.isOnline ? '#1976d2' : '#dc2626'}; ${item.isOnline ? 'animation: pulse 2s infinite;' : ''}"></span>
                                ${item.isOnline ? 'Online' : 'Offline'}
                            </span>
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${item.active ? '#e8f5e9' : '#fff3e0'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${item.active ? '#2e7d32' : '#ed6c02'}; width: fit-content;">
                                <i class="fas ${item.active ? 'fa-check-circle' : 'fa-clock'}" style="font-size: 10px;"></i>
                                ${item.active ? 'Active' : 'Inactive'}
                            </span>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        ${item.vehicle ? `
                            <div>
                                <div style="font-weight: 500;">${item.vehicle.plateNumber || 'N/A'}</div>
                                <div style="font-size: 12px; color: #5b677c;">${item.vehicle.make || ''} ${item.vehicle.model || ''}</div>
                            </div>
                        ` : '<span style="color: #94a3b8; font-style: italic;">Not assigned</span>'}
                    </td>

                    <td style="padding: 16px;">
                        <div>
                            <div style="font-size: 13px; color: #1a1f36;">${item.lastSeen ? new Date(item.lastSeen).toLocaleString() : 'Never'}</div>
                            <div style="font-size: 11px; color: #94a3b8;">${item.lastSeen ? timeSince(new Date(item.lastSeen)) : 'N/A'}</div>
                        </div>
                    </td>

                    <td style="padding: 16px; text-align: center;">
                        <div class="action-dropdown" style="position: relative; display: inline-block;">
                            <button onclick="toggleActionMenu('${serialNo}')" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                            </button>
                            <div id="menu_${serialNo}" style="display: none; position: absolute; right: 0; top: 45px; width: 240px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                                <div style="padding: 12px; border-bottom: 1px solid #eaeef2;">
                                    <span style="font-weight: 600; color: #1a1f36;">Device Actions</span>
                                </div>
                                <div style="padding: 8px;">
                                    <button onclick='viewDeviceDetails("${encodeURIComponent(JSON.stringify(item))}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-eye" style="width: 18px;"></i> View Status
                                    </button>
                                    <button onclick='editDevice("${encodeURIComponent(JSON.stringify(item))}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-edit" style="width: 18px;"></i> Edit Device
                                    </button>
                                    <button onclick='viewHotspotViolations("${encodeURIComponent(JSON.stringify(item))}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #ef4444;">
                                        <i class="fas fa-fire" style="width: 18px;"></i> Hotspot Violations
                                    </button>
                                    <button onclick='viewGeofenceEvents("${encodeURIComponent(JSON.stringify(item))}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #3b82f6;">
                                        <i class="fas fa-map-marked-alt" style="width: 18px;"></i> Geofence Events
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick="trackDevice('${serialNo}')" style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-map-marked-alt" style="width: 18px;"></i> Live Track
                                    </button>
                                    <button onclick="viewDeviceHistory('${serialNo}')" style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-history" style="width: 18px;"></i> History Replay
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick="unassignDevice('${serialNo}')" style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #f97316;">
                                        <i class="fas fa-unlink" style="width: 18px;"></i> Unassign from Vehicle
                                    </button>
                                    <button onclick="deleteDevice('${serialNo}', '${item.name || ''}')" style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                        <i class="fas fa-trash" style="width: 18px;"></i> Delete Device
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>

                <!-- Table Footer -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                    <div style="color: #5b677c;">
                        <span id="selectedCount">0</span> items selected
                    </div>
                    <div class="table-pagination" id="tablePagination"></div>
                </div>

                <style>
                    /* Filter chip active state */
                    .filter-chip.active {
                        background: #000 !important;
                        color: white !important;
                        border-color: #000 !important;
                    }
                    
                    /* Table row hover */
                    .devices-table tbody tr:hover {
                        background: #f8fafc;
                        cursor: pointer;
                    }
                    
                    /* Action button hover */
                    .action-dropdown button:hover {
                        background: #f0f2f5;
                    }
                    
                    /* Pulse animation for online dot */
                    @keyframes pulse {
                        0%, 100% { opacity: 1; }
                        50% { opacity: 0.5; }
                    }
                    
                    /* Responsive */
                    @media (max-width: 768px) {
                        .devices-container { padding: 12px !important; }
                        .statistics-grid { grid-template-columns: 1fr 1fr !important; }
                    }
                </style>
            </div>
            `;

            $(".tab_devices").html(html);

            // Initialize DataTable
            const table = $('#devicetableview').DataTable({
                dom: 'rtip',
                pageLength: 10,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                order: [[1, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [0, 8] }
                ],
                initComplete: function() {
                    $('.dataTables_paginate').css({
                        'display': 'flex',
                        'gap': '4px'
                    });
                    $('.paginate_button').css({
                        'padding': '6px 12px',
                        'border': '1px solid #eaeef2',
                        'border-radius': '8px',
                        'background': 'white',
                        'cursor': 'pointer'
                    });
                }
            });

            // Search functionality
            $('#deviceSearch').off('keyup').on('keyup', function() {
                table.search(this.value).draw();
            });

            // Page size change
            $('#pageSize').off('change').on('change', function() {
                table.page.len(this.value).draw();
            });

            // Select All functionality
            $("#selectAll").off("click").on("click", function() {
                $(".row-checkbox").prop("checked", this.checked);
                updateSelectedCount();
            });

            $(document).off("change", ".row-checkbox").on("change", ".row-checkbox", function() {
                updateSelectedCount();
                const total = $(".row-checkbox").length;
                const checked = $(".row-checkbox:checked").length;
                $("#selectAll").prop("checked", total === checked);
            });

            function updateSelectedCount() {
                const count = $(".row-checkbox:checked").length;
                $("#selectedCount").text(count);
            }

            
            // Close dropdowns when clicking outside
            // $(document).off('click').on('click', function(e) {
            //     if (!$(e.target).closest('.action-dropdown').length) {
            //         $('[id^="menu_"]').hide();
            //     }
            // });
        },
        error: function(xhr, status, error) {
            console.error("Error loading devices:", error);
            $(".tab_devices").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626; margin-bottom: 16px;"></i>
                    <h3 style="color: #1a1f36; margin-bottom: 8px;">Failed to load devices</h3>
                    <p style="color: #5b677c; margin-bottom: 20px;">${error}</p>
                    <button onclick="allDevices()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Helper function for time ago
function timeSince(date) {
    const seconds = Math.floor((new Date() - date) / 1000);
    
    let interval = seconds / 31536000;
    if (interval > 1) return Math.floor(interval) + ' years ago';
    
    interval = seconds / 2592000;
    if (interval > 1) return Math.floor(interval) + ' months ago';
    
    interval = seconds / 86400;
    if (interval > 1) return Math.floor(interval) + ' days ago';
    
    interval = seconds / 3600;
    if (interval > 1) return Math.floor(interval) + ' hours ago';
    
    interval = seconds / 60;
    if (interval > 1) return Math.floor(interval) + ' minutes ago';
    
    return 'just now';
}

// Action menu functions
function toggleActionMenu(deviceId) {
    $('[id^="menu_"]').hide();
    $(`#menu_${deviceId}`).toggle();
}

// Add new device
function addNewDevice() {
    Swal.fire({
        title: 'Add New Device',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Device Name <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-microchip" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="deviceName" type="text" placeholder="Enter device name" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Serial Number <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-barcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="deviceSerial" type="text" placeholder="Enter serial number" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">IMEI</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-qrcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="deviceIMEI" type="text" placeholder="Enter IMEI" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Year of Manufacture</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-calendar-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="deviceYear" type="number" placeholder="e.g., 2025" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Make</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-building" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="deviceMake" type="text" placeholder="e.g., AT510K" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Model</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-tag" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="deviceModel" type="text" placeholder="e.g., AT10K" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Type</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-cubes" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="deviceType" type="text" placeholder="Device type" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Manufacturer</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-industry" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="deviceManufacturer" type="text" placeholder="Manufacturer name" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">SIM 1 Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-sim-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="sim1Number" type="text" placeholder="SIM 1 phone number" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">SIM 2 Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-sim-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="sim2Number" type="text" placeholder="SIM 2 phone number" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Warranty Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="warrantyNumber" type="text" placeholder="Warranty number" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Warranty Period (months)</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-hourglass-half" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="warrantyPeriod" type="number" placeholder="e.g., 12" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Firmware Version</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-code-branch" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="firmwareVersion" type="text" placeholder="e.g., V1.0" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Password</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-lock" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="devicePassword" type="password" placeholder="Device password" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Notes</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-sticky-note" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                        <textarea id="deviceNotes" placeholder="Additional notes" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;"></textarea>
                    </div>
                </div>
            </div>
            
            <style>
                /* Form styles */
                input:focus, textarea:focus {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
                
                .swal2-popup {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                }
                
                .swal2-title {
                    color: #1a1f36;
                }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: 'Create Device',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px',
        preConfirm: () => {
            const name = $('#deviceName').val();
            const serialNo = $('#deviceSerial').val();
            
            if (!name) {
                Swal.showValidationMessage('Device name is required');
                return false;
            }
            if (!serialNo) {
                Swal.showValidationMessage('Serial number is required');
                return false;
            }
            
            return {
                name: name.trim(),
                serialNo: serialNo.trim(),
                imei: $('#deviceIMEI').val() ? $('#deviceIMEI').val().trim() : null,
                make: $('#deviceMake').val() ? $('#deviceMake').val().trim() : null,
                model: $('#deviceModel').val() ? $('#deviceModel').val().trim() : null,
                type: $('#deviceType').val() ? $('#deviceType').val().trim() : null,
                manufacturer: $('#deviceManufacturer').val() ? $('#deviceManufacturer').val().trim() : null,
                yearOfManufacture: $('#deviceYear').val() ? parseInt($('#deviceYear').val()) : null,
                sim1Number: $('#sim1Number').val() ? $('#sim1Number').val().trim() : null,
                sim2Number: $('#sim2Number').val() ? $('#sim2Number').val().trim() : null,
                warrantyNumber: $('#warrantyNumber').val() ? $('#warrantyNumber').val().trim() : null,
                warrantyPeriodMonths: $('#warrantyPeriod').val() ? parseInt($('#warrantyPeriod').val()) : null,
                firmwareVersion: $('#firmwareVersion').val() ? $('#firmwareVersion').val().trim() : null,
                password: $('#devicePassword').val() ? $('#devicePassword').val().trim() : null,
                notes: $('#deviceNotes').val() ? $('#deviceNotes').val().trim() : null
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            createDevice(result.value);
        }
    });
}

// Create device API call
function createDevice(deviceData) {
    Swal.fire({
        title: 'Creating Device',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', API_BASE + 'devices', true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                Swal.fire({
                    title: 'Success!',
                    text: 'Device created successfully',
                    icon: 'success',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                }).then(() => {
                    allDevices();
                });
            } else {
                let errorMsg = 'Failed to create device';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                
                Swal.fire({
                    title: 'Error',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                });
            }
        }
    };
    
    xhr.send(JSON.stringify(deviceData));
}

// Edit device
function editDevice(encodedDeviceData) {
    const device = JSON.parse(decodeURIComponent(encodedDeviceData));
    const deviceId = device.deviceId;
    
    Swal.fire({
        title: 'Edit Device',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Device Name <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-microchip" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="editDeviceName" type="text" placeholder="Enter device name" value="${device.name || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Serial Number <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-barcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="editDeviceSerial" type="text" placeholder="Enter serial number" value="${device.serialNo || device.serialNumber || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">IMEI</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-qrcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDeviceIMEI" type="text" placeholder="Enter IMEI" value="${device.imei || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Year of Manufacture</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-calendar-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDeviceYear" type="number" placeholder="e.g., 2025" value="${device.yearOfManufacture || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Make</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-building" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDeviceMake" type="text" placeholder="e.g., AT510K" value="${device.make || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Model</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-tag" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDeviceModel" type="text" placeholder="e.g., AT10K" value="${device.model || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Type</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-cubes" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDeviceType" type="text" placeholder="Device type" value="${device.type || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Manufacturer</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-industry" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="editDeviceManufacturer" type="text" placeholder="Manufacturer name" value="${device.manufacturer || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">SIM 1 Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-sim-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editSim1Number" type="text" placeholder="SIM 1 phone number" value="${device.sim1Number || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">SIM 2 Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-sim-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editSim2Number" type="text" placeholder="SIM 2 phone number" value="${device.sim2Number || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Warranty Number</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editWarrantyNumber" type="text" placeholder="Warranty number" value="${device.warrantyNumber || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Warranty Period (months)</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-hourglass-half" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editWarrantyPeriod" type="number" placeholder="e.g., 12" value="${device.warrantyPeriodMonths || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Firmware Version</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-code-branch" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editFirmwareVersion" type="text" placeholder="e.g., V1.0" value="${device.firmwareVersion || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Password</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-lock" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="editDevicePassword" type="password" placeholder="Device password" value="${device.password || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Notes</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-sticky-note" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                        <textarea id="editDeviceNotes" placeholder="Additional notes" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;">${device.notes || ''}</textarea>
                    </div>
                </div>
            </div>
            
            <style>
                /* Form styles */
                input:focus, textarea:focus {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
                
                .swal2-popup {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                }
                
                .swal2-title {
                    color: #1a1f36;
                }
                
                /* Number input arrows styling */
                input[type=number]::-webkit-inner-spin-button, 
                input[type=number]::-webkit-outer-spin-button { 
                    opacity: 1;
                    height: 24px;
                }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: 'Update Device',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px',
        preConfirm: () => {
            const name = $('#editDeviceName').val();
            const serialNo = $('#editDeviceSerial').val();
            
            if (!name) {
                Swal.showValidationMessage('Device name is required');
                return false;
            }
            if (!serialNo) {
                Swal.showValidationMessage('Serial number is required');
                return false;
            }
            
            return {
                name: name.trim(),
                serialNo: serialNo.trim(),
                imei: $('#editDeviceIMEI').val() ? $('#editDeviceIMEI').val().trim() : null,
                make: $('#editDeviceMake').val() ? $('#editDeviceMake').val().trim() : null,
                model: $('#editDeviceModel').val() ? $('#editDeviceModel').val().trim() : null,
                type: $('#editDeviceType').val() ? $('#editDeviceType').val().trim() : null,
                manufacturer: $('#editDeviceManufacturer').val() ? $('#editDeviceManufacturer').val().trim() : null,
                yearOfManufacture: $('#editDeviceYear').val() ? parseInt($('#editDeviceYear').val()) : null,
                sim1Number: $('#editSim1Number').val() ? $('#editSim1Number').val().trim() : null,
                sim2Number: $('#editSim2Number').val() ? $('#editSim2Number').val().trim() : null,
                warrantyNumber: $('#editWarrantyNumber').val() ? $('#editWarrantyNumber').val().trim() : null,
                warrantyPeriodMonths: $('#editWarrantyPeriod').val() ? parseInt($('#editWarrantyPeriod').val()) : null,
                firmwareVersion: $('#editFirmwareVersion').val() ? $('#editFirmwareVersion').val().trim() : null,
                password: $('#editDevicePassword').val() ? $('#editDevicePassword').val().trim() : null,
                notes: $('#editDeviceNotes').val() ? $('#editDeviceNotes').val().trim() : null
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            updateDevice(deviceId, result.value);
        }
    });
}

// Update device API call
function updateDevice(deviceId, deviceData) {
    Swal.fire({
        title: 'Updating Device',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', API_BASE + `devices/${deviceId}`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                Swal.fire({
                    title: 'Success!',
                    text: 'Device updated successfully',
                    icon: 'success',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                }).then(() => {
                    allDevices();
                });
            } else {
                let errorMsg = 'Failed to update device';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                
                Swal.fire({
                    title: 'Error',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                });
            }
        }
    };
    
    xhr.send(JSON.stringify(deviceData));
}

// Delete device
function deleteDevice(serialNo, deviceName) {
    // First, find the device ID from the serial number
    const deviceRow = $(`tr[data-device-id="${serialNo}"]`);
    // In a real implementation, you'd need to store device IDs in the row data attribute
    
    Swal.fire({
        title: 'Delete Device?',
        html: `Are you sure you want to delete device <strong>${deviceName || serialNo}</strong>?<br><br>This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Deleting...',
                html: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Note: The deviceId needs to be retrieved properly
            // For demo, we'll use the serial number as ID (adjust based on your API)
            const deviceId = serialNo; // Replace with actual device ID from your data
            
            const xhr = new XMLHttpRequest();
            xhr.open('DELETE', API_BASE + `devices/${deviceId}`, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: 'Device has been deleted successfully.',
                            icon: 'success',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        }).then(() => {
                            allDevices();
                            $(`#menu_${serialNo}`).hide();
                        });
                    } else {
                        let errorMsg = 'Failed to delete device';
                        try {
                            const errorData = JSON.parse(xhr.responseText);
                            errorMsg = errorData.message || errorMsg;
                        } catch (e) {}
                        
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        });
                    }
                }
            };
            
            xhr.send();
        }
    });
}

// Unassign device from vehicle
function unassignDevice(serialNo) {
    Swal.fire({
        title: 'Unassign Device?',
        text: 'Are you sure you want to unassign this device from its vehicle?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f97316',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, unassign',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Unassigning...',
                html: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Note: The deviceId needs to be retrieved properly
            const deviceId = serialNo; // Replace with actual device ID
            
            const xhr = new XMLHttpRequest();
            xhr.open('PUT', API_BASE + `devices/${deviceId}/unassign`, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Device has been unassigned successfully.',
                            icon: 'success',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        }).then(() => {
                            allDevices();
                            $(`#menu_${serialNo}`).hide();
                        });
                    } else {
                        let errorMsg = 'Failed to unassign device';
                        try {
                            const errorData = JSON.parse(xhr.responseText);
                            errorMsg = errorData.message || errorMsg;
                        } catch (e) {}
                        
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        });
                    }
                }
            };
            
            xhr.send();
        }
    });
}

// Export devices
function exportDevices() {
    Swal.fire({
        title: 'Export Devices',
        text: 'Choose export format',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'CSV',
        cancelButtonText: 'JSON',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            alert('CSV export coming soon!');
        } else if (result.dismiss === Swal.DismissReason.cancel) {
            // Get current table data
            const table = $('#devicetableview').DataTable();
            const data = table.data().toArray();
            const jsonStr = JSON.stringify(data, null, 2);
            
            // Download as JSON
            const blob = new Blob([jsonStr], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `devices_export_${new Date().toISOString().slice(0,10)}.json`;
            a.click();
            URL.revokeObjectURL(url);
        }
    });
}

// Track device on map
// Track device on map with current location and interactive Google Maps
function trackDevice(deviceSn) {
    if (!deviceSn) {
        showNotification('Device serial number is required', 'error');
        return;
    }
    
    // Show loading state
    Swal.fire({
        title: 'Tracking Device',
        html: 'Fetching current location...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Fetch latest telemetry data for the device
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + `telemetry/device/${deviceSn}?page=0&size=1`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const response = JSON.parse(xhr.responseText);
                const telemetryData = response.content && response.content.length > 0 ? response.content[0] : null;
                
                if (telemetryData) {
                    displayGoogleMap(deviceSn, telemetryData);
                } else {
                    Swal.fire({
                        title: 'No Location Data',
                        text: 'No telemetry data available for this device',
                        icon: 'info',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36'
                    });
                }
            } else {
                let errorMsg = 'Failed to fetch device location';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                
                Swal.fire({
                    title: 'Error',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                });
            }
        }
    };
    
    xhr.send();
}

// Display interactive Google Map
function displayGoogleMap(deviceSn, telemetry) {
    const timestamp = telemetry.timestamp ? new Date(telemetry.timestamp).toLocaleString() : 'N/A';
    const latitude = telemetry.latitude || 0;
    const longitude = telemetry.longitude || 0;
    const speed = telemetry.speedKmh || 0;
    const direction = telemetry.direction || 0;
    const mileage = telemetry.mileageKm ? telemetry.mileageKm.toFixed(1) : 'N/A';
    const deviceName = telemetry.deviceName || 'Unknown';
    
    // Format direction as compass direction
    const compassDirections = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
    const directionIndex = Math.round(direction / 22.5) % 16;
    const compassDirection = compassDirections[directionIndex];
    
    // Generate a unique ID for the map container
    const mapId = 'google_map_' + Date.now();
    
    Swal.fire({
        title: `📍 Current Location: ${deviceName}`,
        html: `
            <div style="text-align: left;">
                <!-- Map Type Controls -->
                <div style="margin-bottom: 10px; display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
                    <button id="btnRoadmap" class="map-type-btn active" onclick="setGoogleMapType('roadmap')" style="padding: 6px 12px; background: #000; color: white; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-road"></i> Roadmap
                    </button>
                    <button id="btnSatellite" class="map-type-btn" onclick="setGoogleMapType('satellite')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-satellite"></i> Satellite
                    </button>
                    <button id="btnHybrid" class="map-type-btn" onclick="setGoogleMapType('hybrid')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-globe"></i> Hybrid
                    </button>
                    <button id="btnTerrain" class="map-type-btn" onclick="setGoogleMapType('terrain')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-mountain"></i> Terrain
                    </button>
                </div>
                
                <!-- Map Container -->
                <div style="margin-bottom: 20px; border-radius: 12px; overflow: hidden; border: 1px solid #eaeef2; position: relative; height: 400px;">
                    <div id="${mapId}" style="height: 100%; width: 100%;"></div>
                    
                    <!-- Street View Button -->
                    <div style="position: absolute; bottom: 20px; right: 20px; z-index: 5;">
                        <button onclick="openStreetView(${latitude}, ${longitude})" 
                                style="width: 44px; height: 44px; background: white; border: none; border-radius: 50%; cursor: pointer; box-shadow: 0 2px 6px rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-street-view" style="color: #3b82f6; font-size: 20px;"></i>
                        </button>
                    </div>
                    
                    <!-- Location Info Overlay -->
                    <div style="position: absolute; top: 20px; left: 20px; z-index: 5; background: white; padding: 8px 12px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 12px; border-left: 4px solid #3b82f6;">
                        <i class="fas fa-map-marker-alt" style="color: #3b82f6; margin-right: 5px;"></i>
                        <strong>${latitude.toFixed(6)}°, ${longitude.toFixed(6)}°</strong>
                    </div>
                    
                    <!-- Zoom Level Indicator -->
                    <div style="position: absolute; bottom: 20px; left: 20px; z-index: 5; background: white; padding: 4px 10px; border-radius: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 11px;">
                        <i class="fas fa-search-plus"></i> <span id="zoomLevel">15</span>
                    </div>
                </div>
                
                <!-- Location Details -->
                <div style="background: #f8fafc; padding: 16px; border-radius: 12px; margin-bottom: 15px;">
                    <h4 style="margin: 0 0 12px 0; color: #1a1f36; font-size: 16px;">📍 Location Details</h4>
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">
                        <div>
                            <div style="font-size: 12px; color: #64748b;">Device</div>
                            <div style="font-weight: 500;">${deviceName}</div>
                            <div style="font-size: 11px; color: #64748b;">SN: ${deviceSn}</div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #64748b;">Last Updated</div>
                            <div style="font-weight: 500;">${timestamp}</div>
                            <div style="font-size: 11px; color: #64748b;">${timeSince(new Date(telemetry.timestamp))}</div>
                        </div>
                    </div>
                </div>
                
                <!-- Coordinates & Telemetry -->
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-map-pin" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;">${latitude.toFixed(6)}</div>
                        <div style="font-size: 12px; color: #64748b;">Latitude</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-map-marker-alt" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;">${longitude.toFixed(6)}</div>
                        <div style="font-size: 12px; color: #64748b;">Longitude</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-compass" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;">${direction}° ${compassDirection}</div>
                        <div style="font-size: 12px; color: #64748b;">Direction</div>
                    </div>
                </div>
                
                <!-- Speed & Mileage -->
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 15px; border-radius: 12px; color: white;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-tachometer-alt" style="font-size: 24px;"></i>
                            <div>
                                <div style="font-size: 28px; font-weight: 700;">${speed} km/h</div>
                                <div style="font-size: 12px; opacity: 0.9;">Current Speed</div>
                            </div>
                        </div>
                    </div>
                    <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 15px; border-radius: 12px; color: white;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-road" style="font-size: 24px;"></i>
                            <div>
                                <div style="font-size: 28px; font-weight: 700;">${mileage} km</div>
                                <div style="font-size: 12px; opacity: 0.9;">Total Mileage</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div style="display: flex; gap: 10px; justify-content: center;">
                    <button onclick="window.open('https://www.google.com/maps?q=${latitude},${longitude}', '_blank')" 
                            style="flex: 1; padding: 12px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <i class="fas fa-external-link-alt"></i> Open in Google Maps
                    </button>
                    <button onclick="getDirections(${latitude}, ${longitude})" 
                            style="flex: 1; padding: 12px; background: #10b981; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <i class="fas fa-directions"></i> Get Directions
                    </button>
                </div>
                
                <!-- Raw Data Toggle -->
                <div style="margin-top: 15px;">
                    <details style="background: #f8fafc; border-radius: 8px; padding: 12px;">
                        <summary style="color: #3b82f6; cursor: pointer; font-size: 13px; font-weight: 500;">
                            <i class="fas fa-code"></i> View Raw Telemetry Data
                        </summary>
                        <pre style="background: #1e293b; color: #e2e8f0; padding: 16px; border-radius: 8px; margin-top: 12px; overflow-x: auto; font-size: 11px;">${JSON.stringify(telemetry, null, 2)}</pre>
                    </details>
                </div>
            </div>
            
            <style>
                /* Map container styles */
                .map-type-btn.active {
                    background: #000 !important;
                    color: white !important;
                }
                
                .swal2-popup {
                    width: 900px !important;
                }
                
                @media (max-width: 768px) {
                    .swal2-popup {
                        width: 95% !important;
                    }
                    div[style*="grid-template-columns: repeat(3, 1fr)"] {
                        grid-template-columns: 1fr !important;
                    }
                    div[style*="grid-template-columns: repeat(2, 1fr)"] {
                        grid-template-columns: 1fr !important;
                    }
                }
            </style>
        `,
        showConfirmButton: false,
        showCloseButton: true,
        background: '#ffffff',
        color: '#1a1f36',
        width: '900px',
        didOpen: () => {
            // Initialize Google Map after the modal is opened
            initGoogleMap(mapId, latitude, longitude, deviceName);
        }
    });
}

// Initialize Google Map
function initGoogleMap(mapId, latitude, longitude, deviceName) {
    // Check if Google Maps API is loaded, if not, load it
    if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
        // Load Google Maps API with the key (you need to replace with your actual API key)
        const script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMapCallback';
        script.async = true;
        script.defer = true;
        
        window.initMapCallback = function() {
            createGoogleMap(mapId, latitude, longitude, deviceName);
        };
        
        document.head.appendChild(script);
    } else {
        createGoogleMap(mapId, latitude, longitude, deviceName);
    }
}

// Create Google Map
function createGoogleMap(mapId, latitude, longitude, deviceName) {
    const mapContainer = document.getElementById(mapId);
    if (!mapContainer) return;
    
    // Map options
    const mapOptions = {
        center: { lat: latitude, lng: longitude },
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControl: true,
        zoomControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER
        },
        streetViewControl: true,
        streetViewControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER
        },
        fullscreenControl: true,
        fullscreenControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER
        },
        scaleControl: true,
        rotateControl: true,
        gestureHandling: 'greedy' // Allows easy zoom on mobile
    };
    
    // Create the map
    window.googleMap = new google.maps.Map(mapContainer, mapOptions);
    
    // Add marker for device location
    const marker = new google.maps.Marker({
        position: { lat: latitude, lng: longitude },
        map: window.googleMap,
        title: deviceName,
        animation: google.maps.Animation.DROP,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 10,
            fillColor: '#3b82f6',
            fillOpacity: 1,
            strokeColor: '#ffffff',
            strokeWeight: 3
        }
    });
    
    // Add info window
    const infoWindow = new google.maps.InfoWindow({
        content: `
            <div style="padding: 8px; font-family: sans-serif;">
                <strong style="color: #1a1f36;">${deviceName}</strong><br>
                <span style="color: #64748b; font-size: 12px;">Lat: ${latitude.toFixed(6)}</span><br>
                <span style="color: #64748b; font-size: 12px;">Lng: ${longitude.toFixed(6)}</span>
            </div>
        `
    });
    
    marker.addListener('click', () => {
        infoWindow.open(window.googleMap, marker);
    });
    
    // Open info window by default
    infoWindow.open(window.googleMap, marker);
    
    // Add accuracy circle
    new google.maps.Circle({
        strokeColor: '#3b82f6',
        strokeOpacity: 1,
        strokeWeight: 1,
        fillColor: '#3b82f6',
        fillOpacity: 0.1,
        map: window.googleMap,
        center: { lat: latitude, lng: longitude },
        radius: 50 // 50 meters accuracy radius
    });
    
    // Store map instance for global functions
    window.googleMapInstance = window.googleMap;
    
    // Update zoom level indicator
    window.googleMap.addListener('zoom_changed', function() {
        const zoom = window.googleMap.getZoom();
        document.getElementById('zoomLevel').textContent = zoom;
    });
}




// Global function to change map type
window.setGoogleMapType = function(type) {
    if (!window.googleMapInstance) return;
    
    // Update button styles
    $('.map-type-btn').css('background', '#f0f2f5').css('color', '#1a1f36');
    $(`#btn${type.charAt(0).toUpperCase() + type.slice(1)}`).css('background', '#000').css('color', 'white');
    
    // Map type mapping
    const mapTypes = {
        'roadmap': google.maps.MapTypeId.ROADMAP,
        'satellite': google.maps.MapTypeId.SATELLITE,
        'hybrid': google.maps.MapTypeId.HYBRID,
        'terrain': google.maps.MapTypeId.TERRAIN
    };
    
    window.googleMapInstance.setMapTypeId(mapTypes[type]);
};

// Global function to open street view
window.openStreetView = function(lat, lng) {
    if (!window.googleMapInstance) return;
    
    const panorama = window.googleMapInstance.getStreetView();
    panorama.setPosition({ lat: lat, lng: lng });
    panorama.setPov({
        heading: 0,
        pitch: 0,
        zoom: 1
    });
    panorama.setVisible(true);
};

// Global function to get directions
window.getDirections = function(lat, lng) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            const userLat = position.coords.latitude;
            const userLng = position.coords.longitude;
            window.open(`https://www.google.com/maps/dir/${userLat},${userLng}/${lat},${lng}`, '_blank');
        }, function() {
            window.open(`https://www.google.com/maps/dir//${lat},${lng}`, '_blank');
        });
    } else {
        window.open(`https://www.google.com/maps/dir//${lat},${lng}`, '_blank');
    }
};
// View device history
// View device history replay with interactive Google Maps
function viewDeviceHistory(deviceSn) {
    if (!deviceSn) {
        showNotification('Device serial number is required', 'error');
        return;
    }
    
    // Get date range from user
    Swal.fire({
        title: 'Select Date Range',
        html: `
            <div style="text-align: left; padding: 10px;">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Start Date & Time</label>
                    <input type="text" id="historyStartDate" class="swal2-input datetimepicker" placeholder="Select start date" style="width: 100%;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">End Date & Time</label>
                    <input type="text" id="historyEndDate" class="swal2-input datetimepicker" placeholder="Select end date" style="width: 100%;">
                </div>
                <div style="font-size: 12px; color: #64748b; background: #f8fafc; padding: 10px; border-radius: 8px;">
                    <i class="fas fa-info-circle"></i> Leave empty to load the most recent data (last 24 hours)
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Load History',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        didOpen: () => {
            // Initialize datetime pickers
            const now = new Date();
            const yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            
            // Check if flatpickr is available
            if (typeof flatpickr !== 'undefined') {
                flatpickr("#historyStartDate", {
                    enableTime: true,
                    dateFormat: "Y-m-d H:i",
                    time_24hr: true,
                    defaultDate: yesterday
                });

                flatpickr("#historyEndDate", {
                    enableTime: true,
                    dateFormat: "Y-m-d H:i",
                    time_24hr: true,
                    defaultDate: now
                });
            } else {
                // Fallback to regular inputs if flatpickr not available
                document.getElementById('historyStartDate').type = 'datetime-local';
                document.getElementById('historyEndDate').type = 'datetime-local';
                document.getElementById('historyStartDate').value = yesterday.toISOString().slice(0,16);
                document.getElementById('historyEndDate').value = now.toISOString().slice(0,16);
            }
        },
        preConfirm: () => {
            const startDate = $('#historyStartDate').val();
            const endDate = $('#historyEndDate').val();
            return { startDate, endDate };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            // Open history replay in a new modal with the selected date range
            openGoogleHistoryReplayModal(deviceSn, result.value.startDate, result.value.endDate);
        }
    });
}

// Open the history replay modal with Google Maps
function openGoogleHistoryReplayModal(deviceSn, startDate, endDate) {
    // Generate unique IDs for map and controls
    const mapId = 'google_history_map_' + Date.now();
    
    Swal.fire({
        title: `📊 History Replay: ${deviceSn}`,
        html: `
            <div style="text-align: left; max-height: 650px; overflow-y: auto; padding: 10px;">
                <!-- Map Type Controls -->
                <div style="margin-bottom: 10px; display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
                    <button id="btnRoadmap" class="map-type-btn active" onclick="window.historyMapInstance.setMapType('roadmap')" style="padding: 6px 12px; background: #000; color: white; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-road"></i> Roadmap
                    </button>
                    <button id="btnSatellite" class="map-type-btn" onclick="window.historyMapInstance.setMapType('satellite')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-satellite"></i> Satellite
                    </button>
                    <button id="btnHybrid" class="map-type-btn" onclick="window.historyMapInstance.setMapType('hybrid')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-globe"></i> Hybrid
                    </button>
                    <button id="btnTerrain" class="map-type-btn" onclick="window.historyMapInstance.setMapType('terrain')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-mountain"></i> Terrain
                    </button>
                </div>
                
                <!-- Playback Controls -->
                <div style="background: #f8fafc; padding: 15px; border-radius: 12px; margin-bottom: 15px;">
                    <div style="display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; margin-bottom: 10px;">
                        <button id="playBtn" class="replay-btn play" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 8px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;">
                            <i class="fas fa-play"></i> Play
                        </button>
                        <button id="pauseBtn" class="replay-btn pause" style="padding: 10px 20px; background: #f59e0b; color: white; border: none; border-radius: 8px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;">
                            <i class="fas fa-pause"></i> Pause
                        </button>
                        <button id="resetBtn" class="replay-btn reset" style="padding: 10px 20px; background: #6b7280; color: white; border: none; border-radius: 8px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;">
                            <i class="fas fa-undo"></i> Reset
                        </button>
                        <select id="speedSelect" style="padding: 10px; border: 1px solid #eaeef2; border-radius: 8px; background: white;">
                            <option value="1">1x Speed</option>
                            <option value="2">2x Speed</option>
                            <option value="5">5x Speed</option>
                            <option value="10">10x Speed</option>
                            <option value="20">20x Speed</option>
                        </select>
                    </div>
                    
                    <!-- Timeline -->
                    <div style="margin: 15px 0;">
                        <input type="range" id="historyTimelineSlider" class="timeline-slider" min="0" max="100" value="0" style="width: 100%;">
                        <div style="display: flex; justify-content: space-between; font-size: 12px; color: #64748b; margin-top: 5px;">
                            <span id="currentTime">00:00:00</span>
                            <span id="totalTime">00:00:00</span>
                        </div>
                    </div>
                    
                    <!-- Current Telemetry -->
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                        <div style="background: white; padding: 8px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 11px; color: #64748b;">Speed</div>
                            <div style="font-weight: 600; color: #1a1f36; font-size: 16px;" id="currentSpeed">0 km/h</div>
                        </div>
                        <div style="background: white; padding: 8px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 11px; color: #64748b;">Direction</div>
                            <div style="font-weight: 600; color: #1a1f36; font-size: 16px;" id="currentDirection">0°</div>
                        </div>
                        <div style="background: white; padding: 8px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 11px; color: #64748b;">Mileage</div>
                            <div style="font-weight: 600; color: #1a1f36; font-size: 16px;" id="currentMileage">0 km</div>
                        </div>
                    </div>
                </div>
                
                <!-- Google Maps Container -->
                <div style="margin-bottom: 20px; border-radius: 12px; overflow: hidden; border: 1px solid #eaeef2; height: 350px;">
                    <div id="${mapId}" style="height: 100%; width: 100%;"></div>
                </div>
                
                <!-- Statistics -->
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: #f1f5f9; padding: 10px; border-radius: 8px; text-align: center;">
                        <div style="font-size: 11px; color: #64748b;">Data Points</div>
                        <div style="font-size: 18px; font-weight: 600; color: #1a1f36;" id="totalPoints">0</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 10px; border-radius: 8px; text-align: center;">
                        <div style="font-size: 11px; color: #64748b;">Distance</div>
                        <div style="font-size: 18px; font-weight: 600; color: #1a1f36;" id="totalDistance">0 km</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 10px; border-radius: 8px; text-align: center;">
                        <div style="font-size: 11px; color: #64748b;">Duration</div>
                        <div style="font-size: 18px; font-weight: 600; color: #1a1f36;" id="totalDuration">0 min</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 10px; border-radius: 8px; text-align: center;">
                        <div style="font-size: 11px; color: #64748b;">Avg Speed</div>
                        <div style="font-size: 18px; font-weight: 600; color: #1a1f36;" id="avgSpeed">0 km/h</div>
                    </div>
                </div>
                
                <!-- Raw Data Toggle -->
                <div>
                    <details style="background: #f8fafc; border-radius: 8px; padding: 12px;">
                        <summary style="color: #3b82f6; cursor: pointer; font-size: 13px; font-weight: 500;">
                            <i class="fas fa-code"></i> View Raw Telemetry Data
                        </summary>
                        <pre id="rawData" style="background: #1e293b; color: #e2e8f0; padding: 16px; border-radius: 8px; margin-top: 12px; overflow-x: auto; font-size: 11px; max-height: 200px;">Loading...</pre>
                    </details>
                </div>
            </div>
            
            <style>
                .replay-btn {
                    transition: all 0.2s;
                    font-weight: 500;
                }
                .replay-btn:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                }
                .timeline-slider {
                    -webkit-appearance: none;
                    height: 8px;
                    background: #e2e8f0;
                    border-radius: 4px;
                    outline: none;
                }
                .timeline-slider::-webkit-slider-thumb {
                    -webkit-appearance: none;
                    width: 20px;
                    height: 20px;
                    background: #3b82f6;
                    border-radius: 50%;
                    cursor: pointer;
                    border: 2px solid white;
                    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
                }
                .map-type-btn.active {
                    background: #000 !important;
                    color: white !important;
                }
                .swal2-popup {
                    width: 1000px !important;
                }
                @media (max-width: 768px) {
                    .swal2-popup {
                        width: 95% !important;
                    }
                    div[style*="grid-template-columns: repeat(4, 1fr)"] {
                        grid-template-columns: repeat(2, 1fr) !important;
                    }
                }
            </style>
        `,
        showConfirmButton: false,
        showCloseButton: true,
        background: '#ffffff',
        color: '#1a1f36',
        width: '1000px',
        didOpen: () => {
            // Initialize the Google Maps history replay
            initGoogleHistoryReplay(mapId, deviceSn, startDate, endDate);
        }
    });
}

// Google Maps History Replay Class
class GoogleHistoryReplay {
    constructor(mapId, deviceSn, startDate, endDate) {
        this.mapId = mapId;
        this.deviceSn = deviceSn;
        this.startDate = startDate;
        this.endDate = endDate;
        this.map = null;
        this.marker = null;
        this.path = null;
        this.startMarker = null;
        this.endMarker = null;
        this.data = [];
        this.currentIndex = 0;
        this.isPlaying = false;
        this.animationTimeout = null;
        this.speed = 1;
        this.totalDuration = 0;
        this.bounds = null;
        
        // Load the data
        this.loadData();
    }
    
    async loadData() {
        // Show loading
        Swal.showLoading();
        
        try {
            // Format dates for API
            const formatDateForAPI = (dateString) => {
                if (!dateString) return '';
                const date = new Date(dateString);
                const isoString = date.toISOString().split('.')[0];
                return isoString.replace(/:/g, '%3A');
            };
            
            const fromParam = this.startDate ? formatDateForAPI(this.startDate) : '';
            const toParam = this.endDate ? formatDateForAPI(this.endDate) : '';
            
            // Build URL
            let url;
            if (fromParam && toParam) {
                url = `${API_BASE}telemetry/device/${this.deviceSn}/range?from=${fromParam}&to=${toParam}&page=0&size=1000`;
            } else {
                url = `${API_BASE}telemetry/device/${this.deviceSn}?page=0&size=1000`;
            }
            
            // Fetch data
            const response = await fetch(url, {
                headers: {
                    'Authorization': 'Bearer ' + userObj.accessToken
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            this.data = result.content || [];
            
            if (this.data.length > 0) {
                // Sort by timestamp (oldest to newest)
                this.data.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
                
                // Initialize map
                this.initMap();
                
                // Update raw data display
                document.getElementById('rawData').textContent = JSON.stringify(this.data, null, 2);
                
                // Calculate and update statistics
                this.updateStatistics();
            } else {
                document.getElementById('rawData').textContent = 'No telemetry data found for this period.';
                showNotification('No telemetry data found for this period', 'info');
            }
        } catch (error) {
            console.error('Error loading data:', error);
            document.getElementById('rawData').textContent = 'Failed to load telemetry data.';
            showNotification('Failed to load telemetry data', 'error');
        } finally {
            Swal.hideLoading();
        }
    }
    
    initMap() {
        // Check if Google Maps is loaded
        if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
            // Load Google Maps API
            this.loadGoogleMapsAPI();
            return;
        }
        
        this.createMap();
    }
    
    loadGoogleMapsAPI() {
        // You need to replace with your actual Google Maps API key
        const script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initHistoryMapCallback';
        script.async = true;
        script.defer = true;
        
        window.initHistoryMapCallback = () => {
            this.createMap();
        };
        
        document.head.appendChild(script);
    }
    
    createMap() {
        const mapContainer = document.getElementById(this.mapId);
        if (!mapContainer) return;
        
        // Calculate bounds
        this.bounds = new google.maps.LatLngBounds();
        this.data.forEach(point => {
            this.bounds.extend({ lat: point.latitude, lng: point.longitude });
        });
        
        // Map options
        const mapOptions = {
            center: { lat: this.data[0].latitude, lng: this.data[0].longitude },
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            zoomControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_CENTER
            },
            streetViewControl: true,
            fullscreenControl: true,
            scaleControl: true,
            rotateControl: true,
            gestureHandling: 'greedy'
        };
        
        // Create map
        this.map = new google.maps.Map(mapContainer, mapOptions);
        
        // Store map instance globally for type switching
        window.historyMapInstance = this;
        
        // Draw path
        const pathCoordinates = this.data.map(point => ({
            lat: point.latitude,
            lng: point.longitude
        }));
        
        this.path = new google.maps.Polyline({
            path: pathCoordinates,
            geodesic: true,
            strokeColor: '#3b82f6',
            strokeOpacity: 0.8,
            strokeWeight: 4
        });
        
        this.path.setMap(this.map);
        
        // Add start marker
        this.startMarker = new google.maps.Marker({
            position: { lat: this.data[0].latitude, lng: this.data[0].longitude },
            map: this.map,
            title: 'Start',
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 8,
                fillColor: '#10b981',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 2
            },
            label: {
                text: 'S',
                color: 'white',
                fontSize: '12px',
                fontWeight: 'bold'
            }
        });
        
        // Add end marker
        this.endMarker = new google.maps.Marker({
            position: { lat: this.data[this.data.length-1].latitude, lng: this.data[this.data.length-1].longitude },
            map: this.map,
            title: 'End',
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 8,
                fillColor: '#ef4444',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 2
            },
            label: {
                text: 'E',
                color: 'white',
                fontSize: '12px',
                fontWeight: 'bold'
            }
        });
        
        // Create vehicle marker with custom icon
        const vehicleIcon = {
            url: 'data:image/svg+xml;utf8,' + encodeURIComponent(`
                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="10" fill="#3b82f6" stroke="white" stroke-width="2"/>
                    <path d="M12 6 L16 12 L12 18 L8 12 Z" fill="white" transform="rotate(${this.data[0].direction || 0}, 12, 12)"/>
                </svg>
            `),
            scaledSize: new google.maps.Size(32, 32),
            anchor: new google.maps.Point(16, 16)
        };
        
        this.marker = new google.maps.Marker({
            position: { lat: this.data[0].latitude, lng: this.data[0].longitude },
            map: this.map,
            icon: vehicleIcon,
            title: 'Vehicle',
            animation: google.maps.Animation.DROP
        });
        
        // Add info windows
        const startInfo = new google.maps.InfoWindow({
            content: `<div style="padding: 5px;"><b>Start</b><br>${new Date(this.data[0].timestamp).toLocaleString()}</div>`
        });
        
        const endInfo = new google.maps.InfoWindow({
            content: `<div style="padding: 5px;"><b>End</b><br>${new Date(this.data[this.data.length-1].timestamp).toLocaleString()}</div>`
        });
        
        this.startMarker.addListener('click', () => startInfo.open(this.map, this.startMarker));
        this.endMarker.addListener('click', () => endInfo.open(this.map, this.endMarker));
        
        // Fit map to bounds
        this.map.fitBounds(this.bounds);
        
        // Calculate total duration
        this.totalDuration = new Date(this.data[this.data.length-1].timestamp) - new Date(this.data[0].timestamp);
        this.formatTotalTime();
        
        // Set up event listeners
        this.setupEventListeners();
        
        // Initialize display
        this.updateTelemetryDisplay(0);
    }
    
    setupEventListeners() {
        // Play button
        document.getElementById('playBtn').addEventListener('click', () => {
            if (this.currentIndex >= this.data.length - 1) {
                this.currentIndex = 0;
                this.updateMarkerPosition(0);
            }
            this.isPlaying = true;
            this.animate();
        });
        
        // Pause button
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.isPlaying = false;
            if (this.animationTimeout) {
                clearTimeout(this.animationTimeout);
                this.animationTimeout = null;
            }
        });
        
        // Reset button
        document.getElementById('resetBtn').addEventListener('click', () => {
            this.isPlaying = false;
            if (this.animationTimeout) {
                clearTimeout(this.animationTimeout);
                this.animationTimeout = null;
            }
            this.currentIndex = 0;
            this.updateMarkerPosition(0);
            this.map.panTo({ lat: this.data[0].latitude, lng: this.data[0].longitude });
        });
        
        // Speed selector
        document.getElementById('speedSelect').addEventListener('change', (e) => {
            this.speed = parseInt(e.target.value);
        });
        
        // Timeline slider
        document.getElementById('historyTimelineSlider').addEventListener('input', (e) => {
            if (!this.isPlaying) {
                const percentage = parseInt(e.target.value);
                const index = Math.floor((percentage / 100) * (this.data.length - 1));
                this.currentIndex = index;
                this.updateMarkerPosition(index);
                this.map.panTo({ lat: this.data[index].latitude, lng: this.data[index].longitude });
            }
        });
    }
    
    animate() {
        if (!this.isPlaying || this.currentIndex >= this.data.length - 1) {
            this.isPlaying = false;
            return;
        }
        
        const nextIndex = this.currentIndex + 1;
        const currentPoint = this.data[this.currentIndex];
        const nextPoint = this.data[nextIndex];
        
        // Calculate time difference
        const timeDiff = new Date(nextPoint.timestamp) - new Date(currentPoint.timestamp);
        
        // Update marker position
        this.updateMarkerPosition(nextIndex);
        
        // Update current index and display
        this.currentIndex = nextIndex;
        
        // Schedule next frame
        this.animationTimeout = setTimeout(() => {
            this.animate();
        }, timeDiff / this.speed);
    }
    
    updateMarkerPosition(index) {
        const point = this.data[index];
        
        // Update marker position
        this.marker.setPosition({ lat: point.latitude, lng: point.longitude });
        
        // Update marker icon rotation if direction available
        if (point.direction) {
            const icon = {
                url: 'data:image/svg+xml;utf8,' + encodeURIComponent(`
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" fill="#3b82f6" stroke="white" stroke-width="2"/>
                        <path d="M12 6 L16 12 L12 18 L8 12 Z" fill="white" transform="rotate(${point.direction}, 12, 12)"/>
                    </svg>
                `),
                scaledSize: new google.maps.Size(32, 32),
                anchor: new google.maps.Point(16, 16)
            };
            this.marker.setIcon(icon);
        }
        
        // Update telemetry display
        this.updateTelemetryDisplay(index);
        
        // Update timeline slider
        const percentage = (index / (this.data.length - 1)) * 100;
        document.getElementById('historyTimelineSlider').value = percentage;
    }
    
    updateTelemetryDisplay(index) {
        const point = this.data[index];
        
        document.getElementById('currentSpeed').textContent = `${point.speedKmh || 0} km/h`;
        document.getElementById('currentDirection').textContent = `${point.direction || 0}°`;
        document.getElementById('currentMileage').textContent = `${point.mileageKm ? point.mileageKm.toFixed(1) : '0'} km`;
        
        // Update current time
        const elapsed = new Date(point.timestamp) - new Date(this.data[0].timestamp);
        const elapsedSeconds = Math.floor(elapsed / 1000);
        const eHours = Math.floor(elapsedSeconds / 3600);
        const eMinutes = Math.floor((elapsedSeconds % 3600) / 60);
        const eSecs = elapsedSeconds % 60;
        document.getElementById('currentTime').textContent = 
            `${eHours.toString().padStart(2, '0')}:${eMinutes.toString().padStart(2, '0')}:${eSecs.toString().padStart(2, '0')}`;
    }
    
    updateStatistics() {
        const totalPoints = this.data.length;
        
        // Calculate total distance
        let totalDistance = 0;
        for (let i = 1; i < this.data.length; i++) {
            totalDistance += this.calculateDistance(
                this.data[i-1].latitude, this.data[i-1].longitude,
                this.data[i].latitude, this.data[i].longitude
            );
        }
        
        const totalSeconds = Math.floor(this.totalDuration / 1000);
        const avgSpeed = totalDistance / (totalSeconds / 3600);
        
        document.getElementById('totalPoints').textContent = totalPoints;
        document.getElementById('totalDistance').textContent = `${totalDistance.toFixed(1)} km`;
        document.getElementById('totalDuration').textContent = `${Math.floor(totalSeconds / 60)} min`;
        document.getElementById('avgSpeed').textContent = `${avgSpeed.toFixed(1)} km/h`;
    }
    
    formatTotalTime() {
        const totalSeconds = Math.floor(this.totalDuration / 1000);
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const secs = totalSeconds % 60;
        document.getElementById('totalTime').textContent = 
            `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    
    calculateDistance(lat1, lon1, lat2, lon2) {
        const R = 6371; // Earth's radius in km
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a = 
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLon/2) * Math.sin(dLon/2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    }
    
    setMapType(type) {
        if (!this.map) return;
        
        // Update button styles
        document.querySelectorAll('.map-type-btn').forEach(btn => {
            btn.style.background = '#f0f2f5';
            btn.style.color = '#1a1f36';
        });
        
        const mapTypes = {
            'roadmap': google.maps.MapTypeId.ROADMAP,
            'satellite': google.maps.MapTypeId.SATELLITE,
            'hybrid': google.maps.MapTypeId.HYBRID,
            'terrain': google.maps.MapTypeId.TERRAIN
        };
        
        document.getElementById(`btn${type.charAt(0).toUpperCase() + type.slice(1)}`).style.background = '#000';
        document.getElementById(`btn${type.charAt(0).toUpperCase() + type.slice(1)}`).style.color = 'white';
        
        this.map.setMapTypeId(mapTypes[type]);
    }
}

// Initialize Google Maps history replay
function initGoogleHistoryReplay(mapId, deviceSn, startDate, endDate) {
    window.historyMapInstance = new GoogleHistoryReplay(mapId, deviceSn, startDate, endDate);
}

// Add the setMapType function to window for button access
window.setHistoryMapType = function(type) {
    if (window.historyMapInstance) {
        window.historyMapInstance.setMapType(type);
    }
};

// Update the existing viewDeviceHistory function in your action menu
// Make sure the onclick in your table uses the device serial number:
// onclick="viewDeviceHistory('${item.serialNo}')"
// function viewDeviceHistory(deviceSn) {
//     if (typeof switchCrudTab === 'function') {
//         switchCrudTab({currentTarget: $('.tab-item[onclick*="replay"]')[0]}, 'replay');
//         setTimeout(() => {
//             if (typeof setDeviceForReplay === 'function') {

                
//                 setDeviceForReplay(deviceSn);


//             } else {
//                 showNotification('History replay coming soon', 'info');
//             }
//         }, 1000);
//     } else {
//         showNotification('History replay feature coming soon', 'info');
//     }
// }

// Send command to device
function sendCommand(deviceSn) {
    Swal.fire({
        title: 'Send Command',
        html: `
            <div style="text-align: left;">
                <select id="commandSelect" class="swal2-input" style="margin-bottom: 15px;">
                    <option value="arm">Arm Device</option>
                    <option value="disarm">Disarm Device</option>
                    <option value="reboot">Reboot Device</option>
                    <option value="setinterval">Set Reporting Interval</option>
                    <option value="custom">Custom Command</option>
                </select>
                <div id="customCommandDiv" style="display: none;">
                    <input id="customCommand" class="swal2-input" placeholder="Enter custom command">
                </div>
                <div id="intervalDiv" style="display: none;">
                    <input id="intervalValue" type="number" class="swal2-input" placeholder="Interval in seconds">
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Send',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        didOpen: () => {
            $('#commandSelect').on('change', function() {
                $('#customCommandDiv').hide();
                $('#intervalDiv').hide();
                
                if ($(this).val() === 'custom') {
                    $('#customCommandDiv').show();
                } else if ($(this).val() === 'setinterval') {
                    $('#intervalDiv').show();
                }
            });
        },
        preConfirm: () => {
            const commandType = $('#commandSelect').val();
            let command = '';
            
            if (commandType === 'custom') {
                command = $('#customCommand').val();
                if (!command) {
                    Swal.showValidationMessage('Please enter a custom command');
                    return false;
                }
            } else if (commandType === 'setinterval') {
                const interval = $('#intervalValue').val();
                if (!interval) {
                    Swal.showValidationMessage('Please enter interval value');
                    return false;
                }
                command = `SET_INTERVAL ${interval}`;
            } else {
                command = commandType.toUpperCase();
            }
            
            return { deviceSn, command };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Command Sent',
                text: `Command "${result.value.command}" sent to device ${deviceSn}`,
                icon: 'success',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        }
    });
}

// Manage geofence for device
function manageGeofence(deviceSn) {
    // Switch to geofence tab
    if (typeof switchCrudTab === 'function') {
        switchCrudTab({currentTarget: $('.tab-item[onclick*="geofence"]')[0]}, 'geofence');
        setTimeout(() => {
            if (typeof filterGeofencesByDevice === 'function') {
                filterGeofencesByDevice(deviceSn);
            } else {
                showNotification('Geofence management coming soon', 'info');
            }
        }, 1000);
    } else {
        showNotification('Geofence management coming soon', 'info');
    }
}

// Assign vehicle to device
function assignVehicle(deviceSn) {
    Swal.fire({
        title: 'Assign Vehicle',
        html: `
            <div style="text-align: left;">
                <input id="vehiclePlate" class="swal2-input" placeholder="Vehicle plate number">
                <input id="vehicleMake" class="swal2-input" placeholder="Vehicle make">
                <input id="vehicleModel" class="swal2-input" placeholder="Vehicle model">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Assign',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            showNotification(`Vehicle assigned to device ${deviceSn}`, 'success');
        }
    });
}

// View device logs
function viewDeviceLogs(deviceSn) {
    Swal.fire({
        title: 'Device Logs',
        html: `
            <div style="text-align: left; max-height: 400px; overflow-y: auto;">
                <pre style="background: #1e293b; color: #e2e8f0; padding: 16px; border-radius: 8px; font-size: 11px;">
[${new Date().toISOString()}] Device connected
[${new Date(Date.now() - 3600000).toISOString()}] GPS fix acquired
[${new Date(Date.now() - 7200000).toISOString()}] Heartbeat received
[${new Date(Date.now() - 10800000).toISOString()}] Configuration updated
[${new Date(Date.now() - 14400000).toISOString()}] Device started
                </pre>
            </div>
        `,
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px'
    });
}

// View alarms for device
function viewAlarms(deviceSn) {
    Swal.fire({
        title: 'Device Alarms',
        html: `
            <div style="text-align: left;">
                <p style="color: #64748b;">No active alarms for this device.</p>
            </div>
        `,
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36'
    });
}

// Unlock device
function unlockDevice(deviceSn) {
    Swal.fire({
        title: 'Unlock Device',
        text: `Are you sure you want to unlock device ${deviceSn}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, unlock',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            showNotification(`Device ${deviceSn} unlocked`, 'success');
        }
    });
}

// Deactivate device
function deactivateDevice(deviceSn) {
    Swal.fire({
        title: 'Deactivate Device',
        text: `Are you sure you want to deactivate device ${deviceSn}?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, deactivate',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            showNotification(`Device ${deviceSn} deactivated`, 'success');
        }
    });
}

// View device details with geofence status
function viewDeviceDetails(encodedDeviceData) {
    const device = JSON.parse(decodeURIComponent(encodedDeviceData));
    const deviceSn = device.serialNo || device.serialNumber || device.imei;
    
    Swal.fire({
        title: 'Loading Device Status',
        html: 'Fetching geofence information...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Fetch geofence status for the device
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + `geofence-monitoring/device/${deviceSn}/status`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const geofenceStatus = JSON.parse(xhr.responseText);
                displayDeviceDetailsWithGeofenceStatus(device, geofenceStatus);
            } else {
                // If geofence status fails, show basic device info
                Swal.fire({
                    title: 'Device Details',
                    html: `
                        <div style="text-align: left; max-height: 500px; overflow-y: auto;">
                            <pre style="background: #f8fafc; padding: 16px; border-radius: 8px; font-size: 12px;">${JSON.stringify(device, null, 2)}</pre>
                        </div>
                    `,
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36',
                    width: '700px'
                });
            }
        }
    };
    
    xhr.send();
}

// Display device details with geofence status
function displayDeviceDetailsWithGeofenceStatus(device, geofenceStatus) {
    // Format device status badges
    const onlineStatus = device.isOnline ? 
        '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(16, 185, 129, 0.1); border-radius: 30px; color: #10b981; font-size: 12px; font-weight: 600;"><span style="width: 8px; height: 8px; border-radius: 50%; background: #10b981; animation: pulse 2s infinite;"></span>Online</span>' : 
        '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(239, 68, 68, 0.1); border-radius: 30px; color: #ef4444; font-size: 12px; font-weight: 600;"><span style="width: 8px; height: 8px; border-radius: 50%; background: #ef4444;"></span>Offline</span>';
    
    const activeStatus = device.active ?
        '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(16, 185, 129, 0.1); border-radius: 30px; color: #10b981; font-size: 12px; font-weight: 600;"><i class="fas fa-check-circle"></i>Active</span>' :
        '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(245, 158, 11, 0.1); border-radius: 30px; color: #f59e0b; font-size: 12px; font-weight: 600;"><i class="fas fa-clock"></i>Inactive</span>';
    
    // Calculate statistics for geofence status
    const insideCount = geofenceStatus ? geofenceStatus.filter(s => s.inside).length : 0;
    const outsideCount = geofenceStatus ? geofenceStatus.filter(s => !s.inside).length : 0;
    const routeCount = geofenceStatus ? geofenceStatus.filter(s => s.geofenceType === 'ROUTE').length : 0;
    const stationCount = geofenceStatus ? geofenceStatus.filter(s => s.geofenceType === 'STATION').length : 0;
    const hotspotCount = geofenceStatus ? geofenceStatus.filter(s => s.geofenceType === 'HOTSPOT').length : 0;
    
    const deviceInfo = `
        <div style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); padding: 20px; border-radius: 16px; margin-bottom: 20px; border: 1px solid #e2e8f0;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <h3 style="margin: 0; color: #1e293b; font-size: 18px; font-weight: 700; display: flex; align-items: center; gap: 8px;">
                    <i class="fas fa-microchip" style="color: #3b82f6;"></i>
                    Device Information
                </h3>
                <div style="display: flex; gap: 8px;">
                    ${onlineStatus}
                    ${activeStatus}
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;">
                <div style="background: white; padding: 12px; border-radius: 12px; border: 1px solid #e2e8f0;">
                    <div style="font-size: 11px; color: #64748b; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px;">Device Name</div>
                    <div style="font-weight: 600; color: #1e293b; font-size: 15px;">${device.name || 'N/A'}</div>
                </div>
                <div style="background: white; padding: 12px; border-radius: 12px; border: 1px solid #e2e8f0;">
                    <div style="font-size: 11px; color: #64748b; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px;">Serial Number</div>
                    <div style="font-weight: 600; color: #1e293b; font-family: monospace;">${device.serialNo || device.serialNumber || 'N/A'}</div>
                </div>
                <div style="background: white; padding: 12px; border-radius: 12px; border: 1px solid #e2e8f0;">
                    <div style="font-size: 11px; color: #64748b; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px;">IMEI</div>
                    <div style="font-weight: 600; color: #1e293b; font-family: monospace;">${device.imei || 'N/A'}</div>
                </div>
            </div>
        </div>
    `;
    
    let geofenceHtml = '';
    
    if (!geofenceStatus || geofenceStatus.length === 0) {
        geofenceHtml = `
            <div style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); padding: 40px; border-radius: 16px; text-align: center; border: 1px dashed #cbd5e1;">
                <div style="width: 80px; height: 80px; background: #e2e8f0; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px;">
                    <i class="fas fa-map-marked-alt" style="font-size: 32px; color: #94a3b8;"></i>
                </div>
                <h4 style="margin: 0 0 8px 0; color: #1e293b; font-weight: 600;">No Geofence Status</h4>
                <p style="margin: 0; color: #64748b; font-size: 14px;">This device is not currently in any geofence</p>
            </div>
        `;
    } else {
        let rows = '';
        geofenceStatus.forEach((status, index) => {
            // Determine geofence type icon and color
            let typeIcon = 'fa-draw-polygon';
            let typeColor = '#64748b';
            let typeBg = '#f1f5f9';
            
            if (status.geofenceType === 'ROUTE') {
                typeIcon = 'fa-route';
                typeColor = '#3b82f6';
                typeBg = 'rgba(59, 130, 246, 0.1)';
            } else if (status.geofenceType === 'STATION') {
                typeIcon = 'fa-map-marker-alt';
                typeColor = '#10b981';
                typeBg = 'rgba(16, 185, 129, 0.1)';
            } else if (status.geofenceType === 'HOTSPOT') {
                typeIcon = 'fa-fire';
                typeColor = '#ef4444';
                typeBg = 'rgba(239, 68, 68, 0.1)';
            }
            
            const enteredAt = status.enteredAt ? new Date(status.enteredAt).toLocaleString() : 'N/A';
            const exitedAt = status.exitedAt ? new Date(status.exitedAt).toLocaleString() : 'Still inside';
            
            // Format duration if available
            let durationText = '';
            if (status.totalTimeInsideSeconds) {
                const hours = Math.floor(status.totalTimeInsideSeconds / 3600);
                const minutes = Math.floor((status.totalTimeInsideSeconds % 3600) / 60);
                const seconds = status.totalTimeInsideSeconds % 60;
                durationText = `${hours}h ${minutes}m ${seconds}s`;
            }
            
            rows += `
                <tr style="border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
                    <td style="padding: 14px 12px; color: #64748b; font-weight: 500; width: 50px;">${index + 1}</td>
                    <td style="padding: 14px 12px;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div style="width: 36px; height: 36px; background: ${typeBg}; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas ${typeIcon}" style="color: ${typeColor}; font-size: 16px;"></i>
                            </div>
                            <div>
                                <div style="font-weight: 600; color: #1e293b;">${status.geofenceName || 'Unknown'}</div>
                                <div style="font-size: 11px; color: ${typeColor};">${status.geofenceType || 'REGULAR'}</div>
                            </div>
                        </div>
                    </td>
                    <td style="padding: 14px 12px;">
                        ${status.inside ? 
                            '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(16, 185, 129, 0.1); border-radius: 30px; color: #10b981; font-size: 12px; font-weight: 600;"><span style="width: 8px; height: 8px; border-radius: 50%; background: #10b981;"></span>Inside</span>' : 
                            '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(100, 116, 139, 0.1); border-radius: 30px; color: #64748b; font-size: 12px; font-weight: 600;"><span style="width: 8px; height: 8px; border-radius: 50%; background: #64748b;"></span>Outside</span>'
                        }
                    </td>
                    <td style="padding: 14px 12px;">
                        <div style="display: flex; flex-direction: column;">
                            <span style="color: #1e293b; font-weight: 500; font-size: 13px;">${enteredAt.split(',')[0]}</span>
                            <span style="color: #64748b; font-size: 11px;">${enteredAt.split(',')[1] || ''}</span>
                        </div>
                    </td>
                    <td style="padding: 14px 12px;">
                        <div style="display: flex; flex-direction: column;">
                            <span style="color: #1e293b; font-weight: 500; font-size: 13px;">${exitedAt.split(',')[0]}</span>
                            <span style="color: #64748b; font-size: 11px;">${exitedAt.split(',')[1] || ''}</span>
                        </div>
                    </td>
                    <td style="padding: 14px 12px;">
                        ${durationText ? 
                            `<span style="font-family: monospace; color: #3b82f6; font-weight: 600;">${durationText}</span>` : 
                            '<span style="color: #94a3b8;">—</span>'
                        }
                    </td>
                </tr>
            `;
        });
        
        geofenceHtml = `
            <div style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); padding: 20px; border-radius: 16px; border: 1px solid #e2e8f0;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                    <h3 style="margin: 0; color: #1e293b; font-size: 18px; font-weight: 700; display: flex; align-items: center; gap: 8px;">
                        <i class="fas fa-map-marked-alt" style="color: #3b82f6;"></i>
                        Geofence Status
                    </h3>
                    <span style="background: #e2e8f0; padding: 4px 12px; border-radius: 30px; font-size: 12px; font-weight: 600; color: #1e293b;">
                        ${geofenceStatus.length} Active
                    </span>
                </div>
                
                <!-- Geofence Stats Cards -->
                <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin-bottom: 20px;">
                    <div style="background: white; padding: 10px; border-radius: 12px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 20px; font-weight: 700; color: #1e293b;">${geofenceStatus.length}</div>
                        <div style="font-size: 11px; color: #64748b;">Total</div>
                    </div>
                    <div style="background: white; padding: 10px; border-radius: 12px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 20px; font-weight: 700; color: #10b981;">${insideCount}</div>
                        <div style="font-size: 11px; color: #64748b;">Inside</div>
                    </div>
                    <div style="background: white; padding: 10px; border-radius: 12px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 20px; font-weight: 700; color: #64748b;">${outsideCount}</div>
                        <div style="font-size: 11px; color: #64748b;">Outside</div>
                    </div>
                    <div style="background: white; padding: 10px; border-radius: 12px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 20px; font-weight: 700; color: #3b82f6;">${routeCount}</div>
                        <div style="font-size: 11px; color: #64748b;">Routes</div>
                    </div>
                    <div style="background: white; padding: 10px; border-radius: 12px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 20px; font-weight: 700; color: #8b5cf6;">${stationCount + hotspotCount}</div>
                        <div style="font-size: 11px; color: #64748b;">Points</div>
                    </div>
                </div>
                
                <!-- Geofence Table -->
                <div style="border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden;">
                    <div style="max-height: 300px; overflow-y: auto; scrollbar-width: thin;">
                        <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
                            <thead style="background: #f8fafc; position: sticky; top: 0; z-index: 10;">
                                <tr>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">#</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Geofence</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Status</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Entered</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Exited</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Duration</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${rows}
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- Assigned Routes Section -->
                ${geofenceStatus.some(s => s.assignedRouteNames && s.assignedRouteNames.length > 0) ? `
                <div style="margin-top: 16px; padding: 16px; background: white; border-radius: 12px; border: 1px solid #e2e8f0;">
                    <h4 style="margin: 0 0 12px 0; color: #1e293b; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 6px;">
                        <i class="fas fa-route" style="color: #3b82f6;"></i>
                        Assigned Routes
                    </h4>
                    <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                        ${geofenceStatus.filter(s => s.assignedRouteNames && s.assignedRouteNames.length > 0).map(s => 
                            s.assignedRouteNames.map(routeName => 
                                `<span style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); padding: 6px 14px; border-radius: 30px; font-size: 12px; color: white; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);">
                                    <i class="fas fa-route" style="font-size: 10px;"></i> ${routeName}
                                </span>`
                            ).join('')
                        ).join('')}
                    </div>
                </div>
                ` : ''}
            </div>
        `;
    }
    
    Swal.fire({
        title: null,
        html: `
            <div style="text-align: left; background: #ffffff; border-radius: 24px; overflow: hidden; padding: 5px;">
                ${deviceInfo}
                ${geofenceHtml}
                
                <!-- Footer with refresh option -->
                <div style="margin-top: 16px; display: flex; justify-content: flex-end;">
                    <button onclick="viewDeviceDetails('${encodeURIComponent(JSON.stringify(device))}')" 
                            style="padding: 8px 16px; background: #f1f5f9; color: #1e293b; border: none; border-radius: 30px; font-size: 12px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>
        `,
        confirmButtonText: 'Close',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36',
        width: '1100px',
        customClass: {
            popup: 'device-details-popup'
        }
    });
    
    // Add styles
    const style = document.createElement('style');
    style.textContent = `
        .device-details-popup {
            border-radius: 28px !important;
            padding: 24px !important;
        }
        tr:hover td {
            background: #f8fafc !important;
        }
        button[onclick*="viewDeviceDetails"]:hover {
            background: #e2e8f0 !important;
            transform: translateY(-2px);
        }
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
    `;
    document.head.appendChild(style);
}
// View hotspot violations
function viewHotspotViolations(encodedDeviceData) {
    const device = JSON.parse(decodeURIComponent(encodedDeviceData));
    const deviceSn = device.serialNo || device.serialNumber || device.imei;
    
    Swal.fire({
        title: 'Loading Hotspot Violations',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + `geofence-monitoring/device/${deviceSn}/hotspot-violations`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const violations = JSON.parse(xhr.responseText);
                displayHotspotViolations(device, violations);
            } else {
                Swal.fire({
                    title: 'Error',
                    text: 'Failed to load hotspot violations',
                    icon: 'error',
                    confirmButtonColor: '#000'
                });
            }
        }
    };
    
    xhr.send();
}

// Display hotspot violations
function displayHotspotViolations(device, violations) {
    if (!violations || violations.length === 0) {
        Swal.fire({
            title: 'No Violations',
            text: 'No hotspot violations found for this device',
            icon: 'info',
            confirmButtonColor: '#000'
        });
        return;
    }
    
    let rows = '';
    violations.forEach((v, i) => {
        rows += `
            <tr>
                <td style="padding: 8px;">${i+1}</td>
                <td style="padding: 8px;">${v.geofence?.name || 'N/A'}</td>
                <td style="padding: 8px;">${v.eventType || 'N/A'}</td>
                <td style="padding: 8px;">${v.eventTime ? new Date(v.eventTime).toLocaleString() : 'N/A'}</td>
                <td style="padding: 8px;">${v.acknowledged ? 'Yes' : 'No'}</td>
            </tr>
        `;
    });
    
    Swal.fire({
        title: `Hotspot Violations: ${device.name || device.serialNo}`,
        html: `
            <div style="max-height: 400px; overflow-y: auto;">
                <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                    <thead>
                        <tr style="background: #e2e8f0;">
                            <th style="padding: 8px;">#</th>
                            <th style="padding: 8px;">Hotspot</th>
                            <th style="padding: 8px;">Event</th>
                            <th style="padding: 8px;">Time</th>
                            <th style="padding: 8px;">Ack</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        `,
        confirmButtonColor: '#000',
        width: '800px'
    });
}

// View geofence events
function viewGeofenceEvents(encodedDeviceData, limit = 50) {
    const device = JSON.parse(decodeURIComponent(encodedDeviceData));
    const deviceSn = device.serialNo || device.serialNumber || device.imei;
    
    Swal.fire({
        title: 'Loading Geofence Events',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + `geofence-monitoring/device/${deviceSn}/events?limit=${limit}`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const events = JSON.parse(xhr.responseText);
                displayGeofenceEvents(device, events, limit);
            } else {
                Swal.fire({
                    title: 'Error',
                    text: 'Failed to load geofence events',
                    icon: 'error',
                    confirmButtonColor: '#000'
                });
            }
        }
    };
    
    xhr.send();
}

// Display geofence events
function displayGeofenceEvents(device, events, currentLimit) {
    if (!events || events.length === 0) {
        Swal.fire({
            title: 'No Geofence Events',
            html: `
                <div style="text-align: center; padding: 30px 20px;">
                    <div style="background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%); width: 80px; height: 80px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                        <i class="fas fa-map-marked-alt" style="font-size: 32px; color: #64748b;"></i>
                    </div>
                    <h3 style="color: #1e293b; margin-bottom: 10px; font-weight: 600;">No Events Found</h3>
                    <p style="color: #64748b; margin-bottom: 5px;">This device has no recorded geofence events</p>
                    <p style="color: #94a3b8; font-size: 13px;">Try selecting a different time range</p>
                </div>
            `,
            confirmButtonColor: '#000',
            confirmButtonText: 'Got it',
            background: '#ffffff',
            color: '#1a1f36'
        });
        return;
    }
    
    // Calculate statistics
    const inEvents = events.filter(e => e.eventType === 'IN_FENCE').length;
    const outEvents = events.filter(e => e.eventType === 'OUT_FENCE').length;
    const unacknowledged = events.filter(e => !e.acknowledged).length;
    const uniqueGeofences = [...new Set(events.map(e => e.geofenceName))].length;
    
    let rows = '';
    events.forEach((e, i) => {
        const eventType = e.eventType === 'IN_FENCE' ? 'Entered' : 'Exited';
        const eventIcon = e.eventType === 'IN_FENCE' ? 'fa-sign-in-alt' : 'fa-sign-out-alt';
        const eventColor = e.eventType === 'IN_FENCE' ? '#10b981' : '#ef4444';
        const eventBg = e.eventType === 'IN_FENCE' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)';
        
        rows += `
            <tr style="border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
                <td style="padding: 14px 12px; color: #64748b; font-weight: 500; width: 50px;">${i+1}</td>
                <td style="padding: 14px 12px;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-draw-polygon" style="color: white; font-size: 16px;"></i>
                        </div>
                        <div>
                            <div style="font-weight: 600; color: #1e293b;">${e.geofenceName || 'Unknown Geofence'}</div>
                            <div style="font-size: 11px; color: #64748b; margin-top: 2px;">ID: ${e.geofenceId || 'N/A'}</div>
                        </div>
                    </div>
                </td>
                <td style="padding: 14px 12px;">
                    <span style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; background: ${eventBg}; border-radius: 30px; color: ${eventColor}; font-size: 12px; font-weight: 600;">
                        <i class="fas ${eventIcon}" style="font-size: 10px;"></i>
                        ${eventType}
                    </span>
                </td>
                <td style="padding: 14px 12px;">
                    <div style="display: flex; flex-direction: column;">
                        <span style="color: #1e293b; font-weight: 500; font-size: 13px;">${e.eventTime ? new Date(e.eventTime).toLocaleDateString() : 'N/A'}</span>
                        <span style="color: #64748b; font-size: 11px;">${e.eventTime ? new Date(e.eventTime).toLocaleTimeString() : 'N/A'}</span>
                    </div>
                </td>
                <td style="padding: 14px 12px;">
                    <div style="display: flex; flex-direction: column;">
                        <span style="color: #1e293b; font-family: monospace; font-size: 12px;">${e.latitude?.toFixed(6) || 'N/A'}</span>
                        <span style="color: #64748b; font-family: monospace; font-size: 11px;">${e.longitude?.toFixed(6) || 'N/A'}</span>
                    </div>
                </td>
                <td style="padding: 14px 12px;">
                    ${e.acknowledged ? 
                        '<span style="display: inline-flex; align-items: center; gap: 4px; color: #10b981;"><i class="fas fa-check-circle"></i> Acknowledged</span>' : 
                        '<span style="display: inline-flex; align-items: center; gap: 4px; color: #f59e0b;"><i class="fas fa-clock"></i> Pending</span>'
                    }
                </td>
            </tr>
        `;
    });
    
    // Format device info
    const deviceName = device.name || device.serialNo || 'Unknown Device';
    const serialNo = device.serialNo || device.serialNumber || 'N/A';
    
    Swal.fire({
        title: null,
        html: `
            <div style="text-align: left; background: #ffffff; border-radius: 20px; overflow: hidden;">
                <!-- Header with gradient -->
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 25px 25px 20px; margin: -20px -20px 0 -20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; color: white;">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div style="width: 50px; height: 50px; background: rgba(255,255,255,0.2); border-radius: 16px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(5px);">
                                <i class="fas fa-map-marked-alt" style="font-size: 24px; color: white;"></i>
                            </div>
                            <div>
                                <h2 style="margin: 0; font-size: 22px; font-weight: 700; color: white;">Geofence Events</h2>
                                <div style="display: flex; gap: 10px; margin-top: 5px; color: rgba(255,255,255,0.9); font-size: 13px;">
                                    <span><i class="fas fa-microchip" style="margin-right: 4px;"></i>${deviceName}</span>
                                    <span><i class="fas fa-qrcode" style="margin-right: 4px;"></i>${serialNo}</span>
                                </div>
                            </div>
                        </div>
                        <div style="background: rgba(255,255,255,0.2); padding: 8px 16px; border-radius: 40px; font-size: 13px; font-weight: 600; backdrop-filter: blur(5px);">
                            <i class="fas fa-list"></i> ${events.length} Events
                        </div>
                    </div>
                </div>
                
                <!-- Stats Cards -->
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 25px 0 20px;">
                    <div style="background: #f8fafc; padding: 15px 10px; border-radius: 16px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 24px; font-weight: 700; color: #10b981; line-height: 1.2;">${inEvents}</div>
                        <div style="font-size: 12px; color: #64748b; margin-top: 4px;">Entries</div>
                    </div>
                    <div style="background: #f8fafc; padding: 15px 10px; border-radius: 16px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 24px; font-weight: 700; color: #ef4444; line-height: 1.2;">${outEvents}</div>
                        <div style="font-size: 12px; color: #64748b; margin-top: 4px;">Exits</div>
                    </div>
                    <div style="background: #f8fafc; padding: 15px 10px; border-radius: 16px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 24px; font-weight: 700; color: #f59e0b; line-height: 1.2;">${unacknowledged}</div>
                        <div style="font-size: 12px; color: #64748b; margin-top: 4px;">Unacknowledged</div>
                    </div>
                    <div style="background: #f8fafc; padding: 15px 10px; border-radius: 16px; text-align: center; border: 1px solid #e2e8f0;">
                        <div style="font-size: 24px; font-weight: 700; color: #8b5cf6; line-height: 1.2;">${uniqueGeofences}</div>
                        <div style="font-size: 12px; color: #64748b; margin-top: 4px;">Geofences</div>
                    </div>
                </div>
                
                <!-- Load More Options -->
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div style="font-size: 14px; color: #1e293b; font-weight: 600;">
                        <i class="fas fa-history" style="color: #3b82f6; margin-right: 6px;"></i>
                        Event History
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button onclick="viewGeofenceEvents('${encodeURIComponent(JSON.stringify(device))}', 100)" 
                                style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 30px; font-size: 12px; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                            <i class="fas fa-plus-circle"></i> Load 100
                        </button>
                        <button onclick="viewGeofenceEvents('${encodeURIComponent(JSON.stringify(device))}', 200)" 
                                style="padding: 8px 16px; background: #8b5cf6; color: white; border: none; border-radius: 30px; font-size: 12px; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                            <i class="fas fa-plus-circle"></i> Load 200
                        </button>
                    </div>
                </div>
                
                <!-- Events Table -->
                <div style="border: 1px solid #e2e8f0; border-radius: 16px; overflow: hidden; margin-bottom: 15px;">
                    <div style="max-height: 350px; overflow-y: auto; scrollbar-width: thin;">
                        <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
                            <thead style="background: #f8fafc; position: sticky; top: 0; z-index: 10;">
                                <tr>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">#</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Geofence</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Event</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Time</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Location</th>
                                    <th style="padding: 14px 12px; text-align: left; font-weight: 600; color: #1e293b; border-bottom: 2px solid #e2e8f0;">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${rows}
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- Footer with timestamp -->
                <div style="display: flex; justify-content: space-between; align-items: center; font-size: 11px; color: #94a3b8; padding-top: 10px; border-top: 1px solid #e2e8f0;">
                    <span><i class="fas fa-clock"></i> Last updated: ${new Date().toLocaleString()}</span>
                    <span><i class="fas fa-database"></i> Showing ${events.length} of ${currentLimit} events</span>
                </div>
            </div>
        `,
        confirmButtonText: 'Close',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36',
        width: '1100px',
        customClass: {
            popup: 'geofence-events-popup'
        }
    });
    
    // Add hover effect styles
    const style = document.createElement('style');
    style.textContent = `
        .geofence-events-popup {
            border-radius: 24px !important;
            padding: 20px !important;
        }
        tr:hover td {
            background: #f8fafc !important;
        }
        .swal2-close {
            color: white !important;
            background: rgba(255,255,255,0.2) !important;
            border-radius: 50% !important;
            width: 36px !important;
            height: 36px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            margin: 10px !important;
            transition: all 0.2s !important;
        }
        .swal2-close:hover {
            background: rgba(255,255,255,0.3) !important;
            transform: scale(1.1) !important;
        }
        button[onclick*="viewGeofenceEvents"]:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
    `;
    document.head.appendChild(style);
}

// Show notification
function showNotification(message, type = 'info') {
    const toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true
    });
    
    toast.fire({
        icon: type,
        title: message
    });
}

// Initialize on document ready
$(document).ready(function() {
    // Load devices
    allDevices();
    
    // Close menus when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.action-dropdown').length) {
            $('[id^="menu_"]').hide();
        }
    });
});