var deviceMap = null;
var markers = {}; // store markers for each deviceSn

loadDevices();

// setInterval(loadDevices(), 3000);
$(".crud_section").html("");

function loadDevices() {

    var url = serverURL + "telemetry/latest";

    controller.getAuthRequest(url, true, async function(data, status) {

        var items = data;  // ✅ your API returns an array directly

        if (!items || items.length === 0) {
            console.log("No device telemetry found");
            return;
        }

        // Filter valid GPS devices
        let validDevices = items.filter(d => d.latitude && d.longitude);

        if (validDevices.length === 0) {
            console.log("No GPS coordinates available");
            return;
        }

        // Initialize map once
        if (!deviceMap) {
            deviceMap = L.map("crud_section").setView(
                [validDevices[0].latitude, validDevices[0].longitude], 
                14
            );

            L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
                maxZoom: 18
            }).addTo(deviceMap);
        }

        // Loop devices and add/update markers
        validDevices.forEach(async device => {

            let lat = device.latitude;
            let lng = device.longitude;

            // Reverse geocode
            let address = "Resolving...";
            try {
                let res = await fetch(
                    `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`
                );
                let j = await res.json();
                address = j.display_name || "Unknown";
            } catch (err) {
                address = "Not found";
            }

            // Rotation angle of truck
            let rotation = device.direction || 0;

            // Truck icon
            let truckIcon = L.icon({
                iconUrl: "https://cdn-icons-png.flaticon.com/512/1329/1329628.png",
                iconSize: [40, 40],
                iconAnchor: [20, 20],
                className: "truck-" + device.deviceSn
            });

           

            // Popup content
            let popupHtml = `
                <div style='font-size:13px'>
                    <b>Device:</b> ${device.deviceName || "N/A"} <br>
                    <b>Serial No:</b> ${device.deviceSn} <br>
                    <b>Speed:</b> ${device.speedKmh} km/h <br>
                    <b>Direction:</b> ${device.direction}° <br>
                    <b>Mileage:</b> ${device.mileageKm} km <br>
                    <b>Timestamp:</b> ${device.timestamp} <br>
                    <b>Address:</b><br> ${address}
                </div>
            `;

            // Update marker if already exists
            if (markers[device.deviceSn]) {
                markers[device.deviceSn].setLatLng([lat, lng]);
                markers[device.deviceSn].setPopupContent(popupHtml);
            } 
            else {
                // Create a new marker
                markers[device.deviceSn] = L.marker([lat, lng], { icon: truckIcon })
                    .addTo(deviceMap)
                    .bindPopup(popupHtml);
            }

        });

    });

}


