// /utils/mapUtils.js
import L from "leaflet";

// Call this function on page load to restore zoom and center
export const restoreMapSettings = map => {
  const savedZoom = localStorage.getItem("mapZoom");
  const savedCenter = localStorage.getItem("mapCenter");

  if (savedZoom && savedCenter) {
    try {
      const centerCoords = JSON.parse(savedCenter);
      map.setView(centerCoords, parseInt(savedZoom));
    } catch (e) {
      console.error("Error parsing stored map center:", e);
      map.setView([53.111111, 8.4625], 12); // Standardkoordinaten und -zoom
    }
  }
};

// Now update checkOverlappingMarkers to check if oms is initialized
// Globales Array, um Plus-Icons zu speichern
let plusMarkers = [];

export const checkOverlappingMarkers = (map, markers, plusIcon, oms) => {
  if (!Array.isArray(markers)) {
    console.warn("⚠️ checkOverlappingMarkers erwartet ein Array, aber erhielt:", markers);
    return;
  }

  const overlappingGroups = {};

  markers.forEach(marker => {
    if (map.hasLayer(marker)) {
      const latlngStr = marker.getLatLng().toString();
      if (overlappingGroups[latlngStr]) {
        overlappingGroups[latlngStr].push(marker);
      } else {
        overlappingGroups[latlngStr] = [marker];
      }
    }
  });

  plusMarkers.forEach(plusMarker => map.removeLayer(plusMarker));
  plusMarkers = [];

  for (const coords in overlappingGroups) {
    if (overlappingGroups[coords].length > 1) {
      const latLng = L.latLng(coords.match(/[-.\d]+/g).map(Number));
      const plusMarker = L.marker(latLng, { icon: plusIcon }).addTo(map);
      plusMarkers.push(plusMarker);

      plusMarker.on("click", () => {
        const nearbyMarkers = overlappingGroups[coords];

        if (oms && nearbyMarkers.length > 0) {
          oms.spiderfy(nearbyMarkers); // ✅ Zeige Marker als Spider
        }
      });
    }
  }
};

export const handlePlusIconClick = (map, markers, oms, clickedLatLng) => {
  // Debugging-Ausgabe
  if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
    console.log("Plus-Icon Position:", clickedLatLng);
  }

  // Finde Marker in der Nähe der Klickposition
  const nearbyMarkers = markers.filter(
    marker => map.distance(marker.getLatLng(), clickedLatLng) < 50
  );

  // Debugging-Ausgabe
  if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
    console.log("Gefundene Marker in der Nähe:", nearbyMarkers);
  }

  if (oms && nearbyMarkers.length > 0) {
    // Spiderfy die gefundenen Marker
    oms.spiderfy(nearbyMarkers);
  } else {
    if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
      console.log("Keine überlappenden Marker gefunden.");
    }
  }
};
