const GOMAR_MAP_STYLES = `
.gomar-map-canvas { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 0; font-family: 'Inter', system-ui, sans-serif; }
.gomar-map-marker { width: 36px; height: 36px; border-radius: 8px; background: #1a2c6b; color: #fff; display: flex; align-items: center; justify-content: center; border: 2px solid #fff; box-shadow: 0 3px 12px rgba(21,24,31,.28); font-family: 'Barlow Semi Condensed', system-ui, sans-serif; font-size: 16px; font-weight: 700; }
.gomar-map-canvas .leaflet-popup-content-wrapper { border-radius: 10px; box-shadow: 0 8px 28px rgba(21,24,31,.2); }
.gomar-map-canvas .leaflet-popup-content { margin: 14px 16px; line-height: 1.45; }
.gomar-map-popup-name { color: #15181f; font-family: 'Barlow Semi Condensed', system-ui, sans-serif; font-size: 17px; font-weight: 600; }
.gomar-map-popup-address { color: #6b6e78; font-size: 12px; margin-top: 2px; }
.gomar-map-popup-route { color: #1a2c6b; display: inline-block; font-size: 11px; font-weight: 700; letter-spacing: .06em; margin-top: 8px; text-decoration: underline; text-underline-offset: 2px; text-transform: uppercase; }
.m-kon .gomar-map-marker { width: 32px; height: 32px; font-size: 15px; }
`;

function GomarLocationsMap({ locations, activeIndex, onActiveChange }) {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);
  const markersRef = React.useRef([]);

  React.useEffect(() => {
    if (!containerRef.current || mapRef.current || !window.L) return;

    const map = L.map(containerRef.current, {
      scrollWheelZoom: false,
      zoomControl: true,
    });
    const bounds = L.latLngBounds(locations.map((location) => location.coords));

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      maxZoom: 19,
    }).addTo(map);

    markersRef.current = locations.map((location, index) => {
      const mapsUrl = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent('GOMAR Witwicka, ' + location.adres + ', Kraków')}`;
      const icon = L.divIcon({
        className: '',
        html: `<span class="gomar-map-marker">${index + 1}</span>`,
        iconSize: [36, 36],
        iconAnchor: [18, 36],
        popupAnchor: [0, -34],
      });
      const marker = L.marker(location.coords, { icon })
        .addTo(map)
        .bindPopup(
          `<div class="gomar-map-popup-name">${location.dz}</div>` +
          `<div class="gomar-map-popup-address">${location.adres}, Kraków</div>` +
          `<a class="gomar-map-popup-route" href="${mapsUrl}" target="_blank" rel="noopener noreferrer">Wyznacz trasę</a>`,
        );
      marker.on('click', () => onActiveChange(index));
      return marker;
    });

    map.fitBounds(bounds, { padding: [34, 34] });
    mapRef.current = map;
    window.setTimeout(() => map.invalidateSize(), 0);

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

  React.useEffect(() => {
    const map = mapRef.current;
    const marker = markersRef.current[activeIndex];
    if (!map || !marker || activeIndex == null) return;
    map.flyTo(marker.getLatLng(), 16, { duration: 0.65 });
    marker.openPopup();
  }, [activeIndex]);

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: GOMAR_MAP_STYLES }} />
      <div
        ref={containerRef}
        className="gomar-map-canvas"
        role="region"
        aria-label="Mapa pięciu placówek GOMAR w Krakowie"
      />
    </>
  );
}

window.GomarLocationsMap = GomarLocationsMap;