let map;
let markers = { start: null, end: null, current: null }; // To store markers
let directionsService; // Service to calculate routes
let bluePolyline = null; // Blue polyline for the predefined path
let redPolyline = null; // Red polyline for start-to-current path
let greenPolyline = null; // Green polyline for current-to-end path

function initMap() {
  // Initialize the map
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 13,
    center: { lat: 9.045, lng: 38.744 }, // Default center near Piassa
  });

  // Initialize DirectionsService
  directionsService = new google.maps.DirectionsService();

  // Predefine start and end points
  const startPoint = { lat: 9.045, lng: 38.744 }; // Piassa
  const endPoint = { lat: 8.9806, lng: 38.7578 }; // Bole International Airport

  // Add start and end markers
  markers.start = new google.maps.Marker({
    position: startPoint,
    map: map,
    title: "Start Point",
    icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png", // Green marker
  });

  markers.end = new google.maps.Marker({
    position: endPoint,
    map: map,
    title: "End Point",
    icon: "http://maps.google.com/mapfiles/ms/icons/red-dot.png", // Red marker
  });

  // Draw the predefined blue path from start to end
  calculateAndDisplayPredefinedPath(startPoint, endPoint);

  // Place the current marker at the start point initially
  markers.current = new google.maps.Marker({
    position: startPoint,
    map: map,
    title: "Current Position",
    icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png", // Blue marker
  });

  // Connect to WebSocket for real-time updates
  const socket = io("http://localhost:5000");

  // Handle real-time location updates
  socket.on("locationUpdate", (data) => {
    const { latitude, longitude } = data;
    const currentPosition = { lat: latitude, lng: longitude };

    // Calculate and display paths for the current GPS position
    calculateAndDisplayPaths(currentPosition, endPoint);
  });
}

function calculateAndDisplayPredefinedPath(startPoint, endPoint) {
  directionsService.route(
    {
      origin: startPoint,
      destination: endPoint,
      travelMode: google.maps.TravelMode.DRIVING, // Follow roads
    },
    (response, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        const path = response.routes[0].overview_path;

        // Draw the predefined blue path
        drawPath(path, "#0000FF", 2); // Blue path
      } else {
        console.error("Predefined path request failed: " + status);
      }
    }
  );
}

function calculateAndDisplayPaths(currentPosition, endPoint) {
  const startPoint = markers.start.getPosition(); // Predefined start point

  // Draw path from start to current position (red)
  directionsService.route(
    {
      origin: startPoint,
      destination: currentPosition,
      travelMode: google.maps.TravelMode.DRIVING,
    },
    (response, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        const path = response.routes[0].overview_path;

        // Draw red path from start to current
        drawPath(path, "#FF0000", 3, "redPolyline");
      } else {
        console.error("Start-to-current path request failed: " + status);
      }
    }
  );

  // Draw path from current position to end point (green)
  directionsService.route(
    {
      origin: currentPosition,
      destination: endPoint,
      travelMode: google.maps.TravelMode.DRIVING,
    },
    (response, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        const path = response.routes[0].overview_path;

        // Draw green path from current to end
        drawPath(path, "#00FF00", 3, "greenPolyline");
      } else {
        console.error("Current-to-end path request failed: " + status);
      }
    }
  );

  // Update the current marker's position
  markers.current.setPosition(currentPosition);
}

function drawPath(coordinates, color, weight, polylineName) {
  // Remove the existing polyline if it exists
  if (polylineName && window[polylineName]) {
    window[polylineName].setMap(null);
  }

  // Create a new polyline
  
  const polyline = new google.maps.Polyline({
    path: coordinates,
    geodesic: true,
    strokeColor: color,
    strokeOpacity: 1.0,
    strokeWeight: weight,
  });

  // Add the polyline to the map
  polyline.setMap(map);

  // Save the polyline globally if a name is provided
  if (polylineName) {
    window[polylineName] = polyline;
  }
}