'use client';

/**
 * Phase 8 v2 (2026-05-01) — Marker POI Croix rouge sur la map Leaflet.
 *
 * Composant non-rendu (returns null) qui pose un L.Marker custom sur la
 * map quand une session UrgentistCareSession est active pour le joueur
 * connecté. Le clic ouvre la lightbox urgentiste (via window event).
 *
 * Polling toutes les 30s en parallèle de UrgentistCareGlobalManager
 * (mais ici on ne s'occupe que du marker map, l'autre gère la lightbox).
 *
 * SVG : croix rouge (#dc2626) fond blanc. Taille 32×32 px.
 *
 * Usage :
 *   <UrgentistPoiMarker map={mapInstanceRef.current} />
 * (à monter dans GameMap.tsx, ou rendu globalement avec ref vers map).
 */
import { useEffect, useRef } from 'react';
import L from 'leaflet';
import { api } from '@/lib/api';

interface UrgentistPoiMarkerProps {
  map: L.Map | null;
}

const CROSS_RED_SVG = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="32" height="32"
  style="background:#ffffff;border:2px solid #dc2626;border-radius:4px;
  box-shadow:0 0 8px rgba(220,38,38,0.55);" fill="#dc2626" aria-hidden="true">
  <rect x="10" y="3" width="4" height="18" rx="0.5" />
  <rect x="3" y="10" width="18" height="4" rx="0.5" />
</svg>`;

const urgentistIcon = L.divIcon({
  className: 'urgentist-poi-marker',
  html: CROSS_RED_SVG,
  iconSize: [32, 32],
  iconAnchor: [16, 16],
});

export function UrgentistPoiMarker({ map }: UrgentistPoiMarkerProps) {
  const markerRef = useRef<L.Marker | null>(null);

  useEffect(() => {
    if (!map) return;
    let cancelled = false;

    const refresh = async () => {
      try {
        const status = await api.hospital.urgentist.getStatus();
        if (cancelled || !map) return;

        if (status.active && status.poi_lat != null && status.poi_lon != null) {
          // Crée ou repositionne le marker
          if (!markerRef.current) {
            markerRef.current = L.marker(
              [status.poi_lat, status.poi_lon],
              {
                icon: urgentistIcon,
                interactive: true,
                title: 'Soin Urgentiste — clic pour ouvrir',
                zIndexOffset: 1000,
              },
            ).addTo(map);
            markerRef.current.on('click', () => {
              // Demande à UrgentistCareGlobalManager d'ouvrir la lightbox
              window.dispatchEvent(new CustomEvent('urgentist-care-open-lightbox'));
            });
          } else {
            markerRef.current.setLatLng([status.poi_lat, status.poi_lon]);
          }
        } else {
          // Plus de session active : retire le marker
          if (markerRef.current) {
            markerRef.current.remove();
            markerRef.current = null;
          }
        }
      } catch {
        // silent
      }
    };

    void refresh();
    const interval = setInterval(refresh, 30_000);

    return () => {
      cancelled = true;
      clearInterval(interval);
      if (markerRef.current) {
        markerRef.current.remove();
        markerRef.current = null;
      }
    };
  }, [map]);

  return null;
}
