let map;
let marker;
let pathPolyline;
let tracking = false;
let trackingSessionId = null;
const pathCoordinates = []; // Stores the simulated path

const userId = sessionStorage.getItem('userId') || `user_${Math.floor(Math.random() * 10000)}`;
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 starting 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
        simulateMovement(); // ✅ Start simulation
    })
    .catch(error => console.error("❌ Error starting tracking session:", error));
}

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

// ✅ Simulated movement with small increments
function simulateMovement() {
    if (!tracking) return;

    let lastPosition = marker.getPosition();
    let newLat = lastPosition.lat() + (Math.random() - 0.5) * 0.002;
    let newLng = lastPosition.lng() + (Math.random() - 0.5) * 0.002;
    const newPosition = { lat: newLat, lng: newLng };

    // 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);

    // Send the new simulated location
    sendLocation();

    setTimeout(simulateMovement, 3000); // ✅ Updates location every 3 seconds
}



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

    navigator.geolocation.getCurrentPosition(position => {
        const locationData = {
            userId,
            deviceId,
            trackingSessionId,
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
        };

        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
    });
}