var deviceMap = null;
var markers = {};

loadDevices();
// Optional refresh
// setInterval(loadDevices, 3000);

function loadDevices() {

    var url = serverURL + "telemetry/latest";

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

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

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

        // Initialize Google Map first time
        if (!deviceMap) {
            deviceMap = new google.maps.Map(document.getElementById("crud_section"), {
                center: { lat: validDevices[0].latitude, lng: validDevices[0].longitude },
                zoom: 14,
                mapTypeId: "roadmap"
            });
        }

        validDevices.forEach(async device => {

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

            // Reverse Geocoding
            let address = "Resolving...";
            try {
                const geocoder = new google.maps.Geocoder();
                const resp = await geocoder.geocode({ location: { lat, lng } });
                if (resp.results[0]) {
                    address = resp.results[0].formatted_address;
                }
            } catch (e) {
                address = "Not Found";
            }

            // Truck icon
            let truckIcon = {
                url: "https://cdn-icons-png.flaticon.com/512/1329/1329628.png",
                scaledSize: new google.maps.Size(40, 40),
                anchor: new google.maps.Point(20, 20),
            };

            // Popup Window
            let infoHtml = `
                <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>Timestamp:</b> ${device.timestamp} <br>
                    <b>Address:</b><br> ${address}
                </div>
            `;

            // If marker exists, update position
            if (markers[device.deviceSn]) {
                markers[device.deviceSn].setPosition({ lat, lng });
                markers[device.deviceSn].infowindow.setContent(infoHtml);
            }
            else {
                // Create marker
                let marker = new google.maps.Marker({
                    position: { lat, lng },
                    map: deviceMap,
                    icon: truckIcon
                });

                let infoWindow = new google.maps.InfoWindow({
                    content: infoHtml
                });

                // Click = open popup
                marker.addListener("click", function () {
                    infoWindow.open(deviceMap, marker);
                });

                marker.infowindow = infoWindow;
                markers[device.deviceSn] = marker;
            }

        });

    });
}
