/* MapaOSM → window. Overlay de mapa OpenStreetMap (Leaflet) para UNA iglesia.
   Se abre cuando el usuario toca 📍 Ubicación en una tarjeta. Sin Google.
   Props: { iglesia, onClose } */
(function () {
  const { useEffect, useRef } = React;

  function MapaOSM({ iglesia, onClose }) {
    const containerRef = useRef(null);
    const mapRef = useRef(null);

    useEffect(() => {
      if (!iglesia || !containerRef.current) return;
      const L = window.L;
      if (!L) {
        console.warn("[MapaOSM] Leaflet no cargado");
        return;
      }

      const map = L.map(containerRef.current, {
        center: [iglesia.lat, iglesia.lng],
        zoom: 16,
        zoomControl: true,
        scrollWheelZoom: true,
      });
      mapRef.current = map;

      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution: "© OpenStreetMap",
        maxZoom: 19,
      }).addTo(map);

      const icon = L.divIcon({
        html: '<div class="osm-pin"><span aria-hidden>🏠</span></div>',
        className: "osm-pin-wrap",
        iconSize: [42, 42],
        iconAnchor: [21, 21],
      });
      L.marker([iglesia.lat, iglesia.lng], { icon, title: iglesia.nombre }).addTo(map);

      requestAnimationFrame(() => {
        if (mapRef.current) mapRef.current.invalidateSize();
      });
      setTimeout(() => {
        if (mapRef.current) mapRef.current.invalidateSize();
      }, 200);

      return () => {
        map.remove();
        mapRef.current = null;
      };
    }, [iglesia]);

    const handleComoLlegar = () => {
      if (iglesia.lat && iglesia.lng) {
        const url = `https://www.google.com/maps/dir/?api=1&destination=${iglesia.lat},${iglesia.lng}`;
        window.open(url, "_blank", "noopener");
      }
    };

    if (!iglesia) return null;

    return (
      <div className="mapa-osm-overlay" role="dialog" aria-label={"Ubicación de " + iglesia.nombre}>
        <div className="mapa-osm-header">
          <button className="mapa-osm-back" onClick={onClose} aria-label="Cerrar mapa">←</button>
          <div className="mapa-osm-title">{iglesia.nombre}</div>
        </div>
        <div className="mapa-osm-container">
          <div ref={containerRef} style={{ width: "100%", height: "100%" }} />
          <button className="mapa-osm-cta" onClick={handleComoLlegar}>
            🧭 Cómo llegar
          </button>
        </div>
      </div>
    );
  }

  window.MapaOSM = MapaOSM;
})();
