/* AUSIEGE · Shared Leaflet map for the Contact / adresse section.
   Tiles: CartoDB Dark Matter (free, no API key, matches the dark theme).
   Custom champagne pin via L.divIcon to match the brand. */

const SALON = {
  lat: 49.4297,
  lng: 2.0807,
  label: "11 rue des Arbalétriers, 60000 Beauvais",
};

const SALON_MAPS_QUERY = encodeURIComponent(SALON.label);
const SALON_MAPS_URL = `https://www.google.com/maps/search/?api=1&query=${SALON_MAPS_QUERY}`;
const SALON_DIR_URL = `https://www.google.com/maps/dir/?api=1&destination=${SALON_MAPS_QUERY}`;

const SalonMap = ({ className = "salon-map__canvas", zoom = 16, pinSize = 32 }) => {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);

  React.useEffect(() => {
    const start = (attempt = 0) => {
      if (!containerRef.current || mapRef.current) return;
      if (!window.L) {
        if (attempt > 40) return;
        setTimeout(() => start(attempt + 1), 50);
        return;
      }
      const L = window.L;
      const map = L.map(containerRef.current, {
        center: [SALON.lat, SALON.lng],
        zoom,
        zoomControl: false,
        scrollWheelZoom: false,
        attributionControl: true,
      });
      mapRef.current = map;

      L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
        subdomains: "abcd",
        maxZoom: 19,
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attributions">CARTO</a>',
      }).addTo(map);

      L.control.zoom({ position: "bottomleft" }).addTo(map);

      const icon = L.divIcon({
        className: "salon-pin",
        html: '<span class="salon-pin__dot"></span><span class="salon-pin__ring"></span>',
        iconSize: [pinSize, pinSize],
        iconAnchor: [pinSize / 2, pinSize / 2],
      });
      L.marker([SALON.lat, SALON.lng], { icon, keyboard: false, title: SALON.label }).addTo(map);
    };
    start();

    return () => {
      if (mapRef.current) {
        mapRef.current.remove();
        mapRef.current = null;
      }
    };
  }, [zoom, pinSize]);

  return <div ref={containerRef} className={className} aria-label={`Carte ${SALON.label}`} />;
};

window.SALON = SALON;
window.SALON_MAPS_URL = SALON_MAPS_URL;
window.SALON_DIR_URL = SALON_DIR_URL;
window.SalonMap = SalonMap;
