// hooks/useLayerVisibility.js
import { useEffect } from "react";
import { addContextMenuToMarker } from "../utils/addContextMenuToMarker";

const useLayerVisibility = (map, markers, mapLayersVisibility, layerKey, oms) => {
  useEffect(() => {
    if (!map || !markers || !oms) return;

    // Leerzeichen, Bindestriche entfernen & Kleinbuchstaben erzwingen
    const normalizedLayerKey = layerKey.replace(/\s|-/g, "").toLowerCase();

    // Alle mapLayersVisibility-Keys auch normalisieren
    const visibilityKeys = Object.keys(mapLayersVisibility).reduce((acc, key) => {
      acc[key.replace(/\s|-/g, "").toLowerCase()] = mapLayersVisibility[key];
      return acc;
    }, {});

    const isVisible = visibilityKeys[normalizedLayerKey] ?? false;

    const toggleLayer = (isVisible) => {
      markers.forEach((marker) => {
        if (isVisible) {
          marker.addTo(map);
          oms.addMarker(marker);
          addContextMenuToMarker(marker);
        } else {
          map.removeLayer(marker);
          oms.removeMarker(marker);
        }
      });
    };

    toggleLayer(isVisible);
  }, [map, markers, mapLayersVisibility, layerKey, oms]);
};

export default useLayerVisibility;
