let map;
let marker;
let pathPolyline;
let tracking = false;
let trackingSessionId = null;
const pathCoordinates = []; // Stores the user's movement path

const userId = sessionStorage.getItem('userId');
const deviceId = `device_${Math.floor(Math.random() * 10000)}`;
sessionStorage.setItem('userId', userId);

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        zoom: 14,
        center: { lat: 9.045, lng: 38.744 } // Default start location
    });

    marker = new google.maps.Marker({
        position: { lat: 9.045, lng: 38.744 },
        map: map,
        title: "Live Position",
        icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png",
    });

    pathPolyline = new google.maps.Polyline({
        path: pathCoordinates,
        geodesic: true,
        strokeColor: "#0000FF",
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map
    });
}

function startTracking() {
    fetch('/api/gps/location/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, deviceId })
    })
    .then(response => response.json())
    .then(data => {
        trackingSessionId = data.trackingSessionId;
        console.log("✅ New Tracking Session ID:", trackingSessionId);
        tracking = true;
        document.getElementById("status").innerText = "📡 Tracking started...";
        sendLocation(); // ✅ Send first location immediately
        trackingInterval = setInterval(sendLocation, 60000); // ✅ Update every 6 seconds
    })
    .catch(error => console.error("❌ Error starting tracking session:", error));
}

function stopTracking() {
    tracking = false;
    clearInterval(trackingInterval);
    document.getElementById("status").innerText = "⏹ Tracking stopped.";
    trackingSessionId = null;
}

function sendLocation() {
    if (!navigator.geolocation || !trackingSessionId) {
        console.log("❌ Geolocation not supported or session missing");
        return;
    }

    navigator.geolocation.getCurrentPosition(position => {
        const newPosition = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };

        // Update marker position
     //   marker.setPosition(newPosition);

        // Add new position to the path
      //  pathCoordinates.push(newPosition);
      //  pathPolyline.setPath(pathCoordinates);

        // Center the map on the new position
      //  map.setCenter(newPosition);

        const locationData = {
            userId,
            deviceId,
            trackingSessionId,
            latitude: newPosition.lat,
            longitude: newPosition.lng
        };

        fetch('/api/gps/location', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(locationData)
        })
        .then(response => response.json())
        .then(data => {
            console.log("✅ Location Sent:", data);
            document.getElementById("status").innerText = "📍 Location Updated: " + new Date().toLocaleTimeString();
        })
        .catch(error => console.error("❌ Error sending location:", error));

    }, error => console.log("❌ Error getting location: " + error.message), {
        enableHighAccuracy: true,
        maximumAge: 0,
        timeout: 5000
    });
}
