// utils/initializeMap.js
import L from "leaflet";
import "leaflet-contextmenu";
import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
import "overlapping-marker-spiderfier-leaflet";

export const initializeMap = (
  mapRef,
  setMap,
  setOms,
  setMenuItemAdded,
  addItemsToMapContextMenu,
  hasRights,
  setPolylineEventsDisabled
) => {
  const basePath = process.env.NEXT_PUBLIC_BASE_PATH;

  if (!mapRef.current) {
    console.error("❌ Fehler: mapRef.current ist nicht definiert.");
    return;
  }

  if (mapRef.current._leaflet_id) {
    if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
      console.log("⚠️ Karte bereits initialisiert");
    }
    return;
  }

  const url = new URL(window.location.origin);
  const originWithoutPort = `${url.protocol}//${url.hostname}`;
  const tileLayerUrl = `${originWithoutPort}${basePath}/TileMap/mapTiles/{z}/{x}/{y}.png`;

  const initMap = L.map(mapRef.current, {
    center: [53.111111, 8.4625],
    zoom: 12,
    minZoom: 5,
    maxZoom: 15,
    zoomControl: false,
    dragging: true,
    contextmenu: true,
    layers: [],
  });

  initMap.dragging.enable();

  L.tileLayer(tileLayerUrl, {
    attribution: "&copy; Eigene Kartenquelle (offline)",
    tileSize: 256,
    minZoom: 5,
    maxZoom: 15,
    noWrap: true,
    errorTileUrl: "/img/empty-tile.png", // Optional
  }).addTo(initMap);

  const overlappingMarkerSpiderfier = new OverlappingMarkerSpiderfier(initMap, {
    nearbyDistance: 20,
  });

  setMap(initMap);
  setOms(overlappingMarkerSpiderfier);

  if (typeof addItemsToMapContextMenu === "function") {
    addItemsToMapContextMenu(initMap, setMenuItemAdded, setPolylineEventsDisabled);
  }
};
