
var deviceMap = null;
var markers = {};      // Store markers per device SN
mapboxgl.accessToken = "pk.eyJ1IjoiaG9zZWFrb3NrZWkiLCJhIjoiY21paDdkeDRpMDA3bTNkc2FwZGd1dWxoZyJ9.Lp_Nxc6q9-ZnAN0Zr7cWZw";

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



function loadDevices() {
    let url = serverURL + "telemetry/latest";

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

        let items = data;

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

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

        if (validDevices.length === 0) return;

        // Initialize Mapbox (only once)
        if (!deviceMap) {
            deviceMap = new mapboxgl.Map({
                container: "crud_section",
                style: "mapbox://styles/mapbox/streets-v12",
                center: [validDevices[0].longitude, validDevices[0].latitude],
                zoom: 14
            });

            deviceMap.addControl(new mapboxgl.NavigationControl());
        }

        // Loop over devices
        for (let device of validDevices) {

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

            console.log("Device found:", device.deviceName, device);

            // Reverse Geocode
            let address = "Resolving...";
            try {
                let geoUrl =
                `https://api.mapbox.com/geocoding/v5/mapbox.places/${lng},${lat}.json?access_token=${mapboxgl.accessToken}`;

                let r = await fetch(geoUrl);
                let j = await r.json();
                address = j.features?.length ? j.features[0].place_name : "Not found";
            } catch (e) {
                address = "Not found";
            }

            // Popup Content
            let popupHtml = `
                <div style="font-size:13px">
                    <b>Serial:</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> ${address}
                </div>
            `;

            // ==========================
            // FIXED ROTATING TRUCK ICON
            // ==========================
            let el = document.createElement("div");
            el.style.width = "40px";
            el.style.height = "40px";
            el.style.display = "flex";
            el.style.justifyContent = "center";
            el.style.alignItems = "center";

            let img = document.createElement("div");
            img.style.width = "35px";
            img.style.height = "35px";
            img.style.backgroundImage = "url('https://cdn-icons-png.flaticon.com/512/1329/1329628.png')";
            img.style.backgroundSize = "contain";
            img.style.backgroundRepeat = "no-repeat";
            img.style.transform = `rotate(${device.direction}deg)`;

            el.appendChild(img);

            // Update existing marker
            if (markers[device.deviceSn]) {
                markers[device.deviceSn].setLngLat([lng, lat]);

                // Rotate TRUCK ONLY
                markers[device.deviceSn].getElement().firstChild.style.transform =
                    `rotate(${device.direction}deg)`;

            } else {
                // Create new marker
                markers[device.deviceSn] = new mapboxgl.Marker(el)
                    .setLngLat([lng, lat])
                    .setPopup(new mapboxgl.Popup().setHTML(popupHtml))
                    .addTo(deviceMap);
            }
        }
    });
}

// // Auto refresh every 5 seconds
// setInterval(loadDevices, 5000);

// // First load
// loadDevices();

