// ============================================================
// DYNAMIC AGENTS SIDEBAR LOADER (UPDATED)
// Uses: /customs/company/{id} to get T1s and displays device serial numbers
// ============================================================
loadAgentsSidebar();
function loadAgentsSidebar() {
    console.log("loadAgentsSidebar started");
    const $agentsLi = $('li.agentssection');
    if (!$agentsLi.length) {
        console.error("Agents sidebar section not found – check class name 'agentssection'");
        return;
    }
    const $agentsUl = $agentsLi.find('> ul.treeview-menu').first();
    if (!$agentsUl.length) {
        console.error("Agents inner ul not found – expected a direct child <ul class='treeview-menu'>");
        return;
    }

    // Show loading spinner
    $agentsUl.html('<li style="padding:15px; text-align:center;"><i class="fa fa-spinner fa-spin"></i> Loading agents...</li>');
    console.log("Spinner displayed");

    // Check global variables
    if (typeof serverURL === 'undefined') {
        console.error("serverURL is not defined");
        $agentsUl.html('<li style="padding:15px; text-align:center; color:#f00;">Error: serverURL missing</li>');
        return;
    }
    if (!userObj || !userObj.accessToken) {
        console.error("userObj or accessToken is not defined");
        $agentsUl.html('<li style="padding:15px; text-align:center; color:#f00;">Error: authentication missing</li>');
        return;
    }

    // 1. Fetch all companies (agents)
    $.ajax({
        url: serverURL + 'companies/all',
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(companies) {
            console.log("Companies loaded:", companies);
            if (!companies || companies.length === 0) {
                $agentsUl.html('<li style="padding:15px; text-align:center; color:#999;">No agents found</li>');
                return;
            }

            // Create promises to fetch T1s for each company (paginated, but we request up to 1000)
            const t1Promises = companies.map(company => {
                return new Promise(resolve => {
                    $.ajax({
                        url: serverURL + 'customs/company/' + company.id + '?page=0&size=1000&sort=createdAt,desc',
                        type: 'GET',
                        headers: { Authorization: 'Bearer ' + userObj.accessToken },
                        success: function(data) {
                            // Extract the content array from the paginated response
                            const t1List = data.content || [];
                            console.log(`T1s for company ${company.id} (${company.name}):`, t1List);
                            resolve(t1List);
                        },
                        error: function(xhr, status, err) {
                            console.warn(`Failed to load T1s for company ${company.id}:`, err);
                            resolve([]); // resolve with empty array so other companies continue
                        }
                    });
                });
            });

            Promise.all(t1Promises).then(results => {
                console.log("All T1 promises resolved, building menu...");
                let menuHtml = '';

                companies.forEach((company, index) => {
                    const allT1s = results[index] || [];
                    // Filter to only T1s that have a device assigned (with serial number)
                    const t1sWithDevice = allT1s.filter(t1 => t1.device && t1.device.serialNumber);
                    const safeCompanyName = escapeHtml(company.name || 'Unknown');

                    // Always show the company, even if no devices (optional – you can skip companies with no devices)
                    menuHtml += `
                        <li class="treeview">
                            <a href="#!"><i class="icon-arrow-right"></i><span>${safeCompanyName}</span><i class="icon-arrow-down"></i></a>
                            <ul class="treeview-menu">
                    `;

                    if (t1sWithDevice.length === 0) {
                        menuHtml += `<li style="padding:8px 15px; color:#999; font-style:italic;">No devices</li>`;
                    } else {
                        t1sWithDevice.forEach(t1 => {
                            const serialNumber = t1.device.serialNumber;
                            menuHtml += `
                                <li>
                                    <a class="waves-effect waves-dark" href="javascript:void(0);" onclick="trackDeviceByCompany('${serialNumber}')" title="Track device ${serialNumber}">
                                        <i class="icon-arrow-right"></i> ${serialNumber}
                                    </a>
                                </li>
                            `;
                        });
                    }

                    menuHtml += `</ul></li>`;
                });

                console.log("Menu HTML generated, inserting...");
                $agentsUl.html(menuHtml);

                // Re-initialize treeview plugin if it exists (e.g., metisMenu)
                if (typeof $.fn.metisMenu === 'function') {
                    console.log("Re-initializing metisMenu");
                    $('.treeview').metisMenu('dispose').metisMenu();
                }
            }).catch(error => {
                console.error('Promise.all failed:', error);
                $agentsUl.html('<li style="padding:15px; text-align:center; color:#f00;">Failed to load T1 data</li>');
            });
        },
        error: function(xhr, status, error) {
            console.error('Error loading companies:', error);
            $agentsUl.html('<li style="padding:15px; text-align:center; color:#f00;">Failed to load agents</li>');
        }
    });
}

// Helper to escape HTML special characters (prevents XSS)
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// Call on document ready
// $(document).ready(function() {
//     loadAgentsSidebar();
// });

// Enhanced trackDevice to load content into .crud_section
function trackDeviceByCompany(deviceSn) {
    if (!deviceSn) {
        showNotification('Device serial number is required', 'error');
        return;
    }

    // Show loading skeleton in .crud_section
    $(".crud_section").html(`
        <div class="tracking-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(3, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(3).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>
    `);

    // 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) {
                    displayDeviceTracking(deviceSn, telemetryData);
                } else {
                    $(".crud_section").html(`
                        <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                            <i class="fas fa-map-marked-alt" style="font-size: 48px; color: #94a3b8; margin-bottom: 16px;"></i>
                            <h3 style="color: #1a1f36; margin-bottom: 8px;">No Location Data</h3>
                            <p style="color: #5b677c;">No telemetry data available for this device</p>
                            <button onclick="trackDeviceByCompany('${deviceSn}')" style="margin-top: 16px; padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                                <i class="fas fa-sync-alt"></i> Retry
                            </button>
                        </div>
                    `);
                }
            } else {
                let errorMsg = 'Failed to fetch device location';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                $(".crud_section").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;">Error</h3>
                        <p style="color: #5b677c;">${errorMsg}</p>
                        <button onclick="trackDeviceByCompany('${deviceSn}')" style="margin-top: 16px; padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-sync-alt"></i> Retry
                        </button>
                    </div>
                `);
            }
        }
    };

    xhr.send();
}

// Display interactive Google Map in .crud_section
function displayDeviceTracking(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();

    const html = `
        <div class="tracking-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            <!-- Header -->
            <div style="background: linear-gradient(135deg, #ececec 0%, #ececec 100%); border-radius: 8px; padding: 6px; margin-bottom: 8px; color: white; display: flex; align-items: center; gap: 16px;">
                <div style="width: 60px; height: 60px; background: rgba(255,255,255,0.2); border-radius: 16px; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-map-marker-alt" style="font-size: 30px; color: black"></i>
                </div>
                <div>
                    <h1 style="margin: 0; font-size: 18px; font-weight: 600; color: black">Live Tracking</h1>
                    <p style="margin: 4px 0 0; opacity: 0.9;">Device: <strong>${deviceName}</strong> (SN: ${deviceSn})</p>
                </div>
            </div>

            <!-- Map Type Controls -->
            <div style="margin-bottom: 20px; display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-start;">
                <button id="btnRoadmap" class="map-type-btn active" onclick="setGoogleMapType('roadmap')" style="padding: 8px 16px; background: #000; color: white; border: none; border-radius: 30px; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-road"></i> Roadmap
                </button>
                <button id="btnSatellite" class="map-type-btn" onclick="setGoogleMapType('satellite')" style="padding: 8px 16px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 30px; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-satellite"></i> Satellite
                </button>
                <button id="btnHybrid" class="map-type-btn" onclick="setGoogleMapType('hybrid')" style="padding: 8px 16px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 30px; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-globe"></i> Hybrid
                </button>
                <button id="btnTerrain" class="map-type-btn" onclick="setGoogleMapType('terrain')" style="padding: 8px 16px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 30px; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-mountain"></i> Terrain
                </button>
            </div>

            <!-- Map Container -->
            <div style="margin-bottom: 24px; border-radius: 16px; overflow: hidden; border: 1px solid #eaeef2; position: relative; height: 450px;">
                <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 14px; border-radius: 30px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 13px; border-left: 4px solid #3b82f6;">
                    <i class="fas fa-map-marker-alt" style="color: #3b82f6; margin-right: 6px;"></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: 6px 12px; border-radius: 30px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 12px;">
                    <i class="fas fa-search-plus"></i> <span id="zoomLevel">15</span>
                </div>
            </div>

            <!-- Stats Grid -->
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                <div style="background: #f8fafc; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 48px; height: 48px; background: #e3f2fd; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-tachometer-alt" style="font-size: 24px; color: #1976d2;"></i>
                        </div>
                        <div>
                            <div style="font-size: 24px; font-weight: 700; color: #1a1f36;">${speed} km/h</div>
                            <div style="font-size: 13px; color: #5b677c;">Speed</div>
                        </div>
                    </div>
                </div>
                <div style="background: #f8fafc; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 48px; height: 48px; background: #e8f5e9; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-compass" style="font-size: 24px; color: #2e7d32;"></i>
                        </div>
                        <div>
                            <div style="font-size: 24px; font-weight: 700; color: #1a1f36;">${direction}° ${compassDirection}</div>
                            <div style="font-size: 13px; color: #5b677c;">Direction</div>
                        </div>
                    </div>
                </div>
                <div style="background: #f8fafc; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 48px; height: 48px; background: #fff3e0; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-road" style="font-size: 24px; color: #ed6c02;"></i>
                        </div>
                        <div>
                            <div style="font-size: 24px; font-weight: 700; color: #1a1f36;">${mileage} km</div>
                            <div style="font-size: 13px; color: #5b677c;">Mileage</div>
                        </div>
                    </div>
                </div>
                <div style="background: #f8fafc; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 48px; height: 48px; background: #f3e5f5; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-clock" style="font-size: 24px; color: #9c27b0;"></i>
                        </div>
                        <div>
                            <div style="font-size: 16px; font-weight: 600; color: #1a1f36;">${timestamp}</div>
                            <div style="font-size: 13px; color: #5b677c;">Last Update</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div style="display: flex; gap: 16px; justify-content: center; margin-bottom: 24px;">
                <button onclick="window.open('https://www.google.com/maps?q=${latitude},${longitude}', '_blank')" 
                        style="flex: 1; max-width: 300px; padding: 14px; background: #3b82f6; color: white; border: none; border-radius: 12px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer; transition: 0.2s;">
                    <i class="fas fa-external-link-alt"></i> Open in Google Maps
                </button>
                <button onclick="getDirections(${latitude}, ${longitude})" 
                        style="flex: 1; max-width: 300px; padding: 14px; background: #10b981; color: white; border: none; border-radius: 12px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer; transition: 0.2s;">
                    <i class="fas fa-directions"></i> Get Directions
                </button>
            </div>

            <!-- Raw Data Toggle -->
            <div style="margin-bottom: 20px;">
                <details style="background: #f8fafc; border-radius: 12px; padding: 16px; border: 1px solid #eaeef2;">
                    <summary style="color: #3b82f6; cursor: pointer; font-size: 15px; 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: 16px; overflow-x: auto; font-size: 12px;">${JSON.stringify(telemetry, null, 2)}</pre>
                </details>
            </div>

            <!-- Back Button -->
            <div style="text-align: center;">
                <button onclick="history.back()" style="padding: 12px 24px; background: #64748b; color: white; border: none; border-radius: 30px; cursor: pointer;">
                    <i class="fas fa-arrow-left"></i> Go Back
                </button>
            </div>

            <style>
                .map-type-btn.active {
                    background: #000 !important;
                    color: white !important;
                }
                @media (max-width: 768px) {
                    div[style*="grid-template-columns: repeat(4, 1fr)"] {
                        grid-template-columns: repeat(2, 1fr) !important;
                    }
                }
            </style>
        </div>
    `;

    $(".crud_section").html(html);

    // Initialize Google Map
    initGoogleMap(mapId, latitude, longitude, deviceName);
}