'use client';

import { useEffect, useRef, useState, useMemo } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-minimap/dist/Control.MiniMap.min.css';
import { t } from '@/lib/i18n';
import { apiFetch } from '@/lib/api';
import { Crosshair, Layers, Filter, Building2, Home, Star, Wrench } from 'lucide-react';
import {
  useMapStore, MapEntity, MissionMapEntity,
  POISuperCategory, POI_SUPER_CATEGORIES, POI_SUPER_CATEGORY_LABELS,
} from '@/stores/mapStore';
import { useMapSocket } from '@/hooks/useMapSocket';
import { useGameStore } from '@/stores/gameStore';
import { getInterpolatedJourneyPosition, interpolatePositionEased, calculateProgress, clamp } from '@/lib/map-interpolation';
import { POILightbox } from './POILightbox';
import { MapContextMenu } from './MapContextMenu';
import { VehicleActionHandler } from './VehicleActionHandler';
// Phase 8 v2 (2026-05-01) — POI Croix rouge soin urgentiste (clic = lightbox)
import { UrgentistPoiMarker } from './UrgentistPoiMarker';
// Phase 4 (2026-04-26) — Soudoyer POI gouvernemental (police/townhall/courthouse)
import { PoiBribeModal } from '../ui/PoiBribeModal';
import { GangsterPanel } from './GangsterPanel';
import { OSM_ICON_SYMBOLS, OSM_ICON_ALIASES } from './osm-icons';
// Phase 1 refonte markers (mai 2026) — SVG game-icons centralisés
import {
  resolvePoiMarker, resolveVehicleMarker, resolveNpcMarker, resolveMissionMarker,
  buildIcon as buildMarkerIcon, buildPlayerAvatarIcon, hasSvg, preloadCommon,
  derivePlayerState, getStateExpiryMs, scheduleStateExpiry,
} from '@/lib/markers';

// Phase 2 (2026-04-20) — 4 super-catégories, 4 icônes filtre.
const SUPER_CATEGORY_ICONS: Record<POISuperCategory, React.ReactNode> = {
  commercial:   <Building2 size={12} />,
  residentiel:  <Home size={12} />,
  special:      <Star size={12} />,
  service:      <Wrench size={12} />,
};

/**
 * Phase 15 (20-04-2026) — Animation map-pick au clic POI.
 * Consigne user : « Le POI sélectionné doit rapetisser au clic et regrossir
 * au lâché du clic, et changer de couleur entre le moment où il rapetisse
 * et regrossit, passer en vert ».
 *
 * Implémentation : on récupère le DOM element du marker, applique une
 * animation CSS en 3 phases via classes, puis retire.
 */
function animatePoiPick(marker: L.Marker): void {
  const el = (marker as any).getElement?.() as HTMLElement | null;
  if (!el) return;
  el.classList.remove('map-pick-anim');
  void el.offsetWidth; // force reflow pour relancer l'animation
  el.classList.add('map-pick-anim');
  window.setTimeout(() => el.classList.remove('map-pick-anim'), 700);
}

/** Flash vert au point cliqué quand expects=location (patrol). */
function flashLocation(map: L.Map, lat: number, lng: number): void {
  const dot = L.divIcon({
    html: '<div class="map-pick-location-flash"></div>',
    className: '',
    iconSize: [20, 20],
    iconAnchor: [10, 10],
  });
  const m = L.marker([lat, lng], { icon: dot, interactive: false, zIndexOffset: 1000 }).addTo(map);
  window.setTimeout(() => m.remove(), 900);
}

// Fix leaflet default icon issue with Next.js
const defaultIcon = L.icon({
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});
L.Marker.prototype.options.icon = defaultIcon;

interface MapLayer {
  id: string;
  label: string;
  visible: boolean;
}

// Helper: create colored circle icon
function circleIcon(color: string, size = 10): L.DivIcon {
  return L.divIcon({
    html: `<div style="width:${size}px;height:${size}px;background:${color};border:1px solid ${color};border-radius:50%;box-shadow:0 0 8px ${color}80;"></div>`,
    className: '',
    iconSize: [size, size],
    iconAnchor: [size / 2, size / 2],
  });
}

// Phase 2 (2026-04-20) — Nouvelle convention SVG POI map :
// • Commerce lambda NPC  : immeuble BLEU
// • Commerce racketé     : immeuble ORANGE (racket zone du joueur)
// • Commerce possédé légal : immeuble VIOLET
// • Commerce possédé + activité illégale : immeuble VIOLET + border rouge sang 1px
// • Résidence NPC         : maison VERTE
// • Planque active joueur : maison VIOLETTE
// • POIs SPÉCIAUX  : SVG spécifique par type (banque, casino, armurerie, etc.)
// • POIs SERVICES  : SVG spécifique par type (commissariat, hôpital, mairie, etc.)

// OSM_ICON_SYMBOLS est maintenant dans osm-icons.ts — SVG officiels openstreetmap-carto

/** Symboles immeuble/maison génériques (commerces lambda / résidences). */
const BUILDING_SYMBOL = '<rect x="4" y="6" width="10" height="8" rx="0.5" fill="none" stroke="#fff" stroke-width="1.3"/><path d="M4 6l5-3 5 3M7 9h1M10 9h1M7 12h1M10 12h1" stroke="#fff" stroke-width="1"/>';
const HOUSE_SYMBOL = '<path d="M4 14h10M4 14V9l5-4 5 4v5" fill="none" stroke="#fff" stroke-width="1.3" stroke-linejoin="round"/><rect x="7" y="11" width="4" height="3" fill="#fff"/>';

function poiIcon(entity: MapEntity): L.DivIcon {
  // Phase 1 refonte (mai 2026) — Tente le nouveau système SVG game-icons.
  // Si le SVG est en cache et qu'un mapping existe, on l'utilise.
  // Sinon (casino, OSM orphelin, SVG pas encore préchargé) → ancien rendu.
  const newCfg = resolvePoiMarker(entity);
  if (newCfg && hasSvg(newCfg.svgFile)) {
    return buildMarkerIcon(newCfg);
  }

  const s = 18;
  const sub = (entity.business_type || entity.subtype || entity.icon || '').toLowerCase();
  const superCat = entity.super_category;
  const isOwned = !!entity.is_owned_by_me;
  const isRacketed = !!entity.is_racketed_by_me;
  const hasIllegal = !!entity.has_illegal;
  const isPlanque = sub === 'safe_house' || sub.includes('planque') || (superCat === 'residentiel' && isOwned);

  const fg = '#fff';
  let bg = '#3b82f6'; // bleu = commerce lambda
  let symbol = BUILDING_SYMBOL;
  let borderStyle = '';

  // POI orphelin (icon OSM connu) → lookup table, avec résolution d'alias
  const osmKey = entity.icon ? (OSM_ICON_ALIASES[entity.icon.toLowerCase()] ?? entity.icon.toLowerCase()) : undefined;
  const osmHit = osmKey ? OSM_ICON_SYMBOLS[osmKey] : undefined;
  if (osmHit) {
    bg = osmHit.bg;
    symbol = osmHit.symbol;
  } else if (superCat === 'residentiel' || sub.includes('residence') || sub.includes('squat') || sub.includes('studio') || sub.includes('apartment')) {
    // Résidence : verte lambda / violette si planque du joueur
    bg = isPlanque ? '#8b5cf6' : '#10b981';
    symbol = HOUSE_SYMBOL;
  } else if (superCat === 'commercial' || !superCat) {
    // Commerce lambda — couleur selon ownership/racket
    if (isOwned) bg = '#8b5cf6';       // violet = possédé
    else if (isRacketed) bg = '#f97316'; // orange = racketé
    else bg = '#3b82f6';                // bleu = NPC lambda
    // Bord rouge sang si activité illégale révélée
    if (hasIllegal) borderStyle = 'border: 1px solid #991b1b;';
    symbol = BUILDING_SYMBOL;
  } else if (superCat === 'special') {
    // Fallback pour spec sans icon OSM matché (ex: armurerie business_type)
    if (sub.includes('armurerie') || sub === 'gun') {
      bg = '#374151';
      symbol = '<path d="M3 7h11v3H9l-1 4H5v-4H3z" fill="#fff"/>';
    } else if (sub.includes('banque') || sub.includes('banque_joueur')) {
      bg = '#d4a843';
      symbol = OSM_ICON_SYMBOLS.bank.symbol;
    } else if (sub.includes('casino')) {
      bg = '#dc2626';
      symbol = OSM_ICON_SYMBOLS.casino.symbol;
    } else if (sub.includes('storage') || sub.includes('warehouse') || sub === 'entrepot') {
      bg = '#78716c';
      symbol = OSM_ICON_SYMBOLS.trade.symbol;
    } else if (sub.includes('drug_lab')) {
      bg = '#065f46';
      symbol = '<path d="M7 5h4v3l2 5H5l2-5z" fill="none" stroke="#fff" stroke-width="1.3"/><path d="M7 10h4" stroke="#fff" stroke-width="1"/>';
    } else if (sub.includes('weapons_cache')) {
      bg = '#1f2937';
      symbol = '<rect x="4" y="7" width="10" height="6" fill="none" stroke="#fff" stroke-width="1.3"/><path d="M5 9h8M7 7v6" stroke="#fff" stroke-width="0.8"/>';
    } else if (sub.includes('safe_house')) {
      bg = '#334155';
      symbol = HOUSE_SYMBOL;
    } else {
      // Spécial générique
      bg = '#a855f7';
      symbol = BUILDING_SYMBOL;
    }
  }

  return L.divIcon({
    html: `<div style="width:${s}px;height:${s}px;background:${bg};border-radius:5px;${borderStyle}display:flex;align-items:center;justify-content:center;box-shadow:0 1px 4px ${bg}60;">
      <svg width="${s}" height="${s}" viewBox="0 0 18 18">${symbol}</svg>
    </div>`,
    className: '',
    iconSize: [s, s],
    iconAnchor: [s / 2, s / 2],
  });
}

// Vehicle type → SVG shape mapping
function vehicleIcon(subtype?: string | null, isPlayerVehicle?: boolean): L.DivIcon {
  // Phase 1 refonte (mai 2026) — Nouveau système SVG game-icons en priorité.
  const newCfg = resolveVehicleMarker(subtype ?? null);
  if (newCfg && hasSvg(newCfg.svgFile)) {
    // Override couleur si véhicule joueur (tag doré)
    const cfg = isPlayerVehicle ? { ...newCfg, colorVar: '--marker-gold' } : newCfg;
    return buildMarkerIcon(cfg);
  }

  const color = isPlayerVehicle ? '#d4a843' : '#06b6d4';
  const shapes: Record<string, string> = {
    car: `<rect x="2" y="5" width="16" height="10" rx="3" fill="${color}"/>`,
    motorcycle: `<circle cx="5" cy="12" r="3" fill="${color}"/><circle cx="15" cy="12" r="3" fill="${color}"/><path d="M5 9 L10 5 L15 9" stroke="${color}" fill="none" stroke-width="2"/>`,
    truck: `<rect x="1" y="6" width="18" height="10" rx="2" fill="${color}"/><rect x="12" y="3" width="7" height="5" rx="1" fill="${color}" opacity="0.7"/>`,
    boat: `<path d="M2 12 Q10 6 18 12 L16 15 Q10 13 4 15 Z" fill="${color}"/>`,
    helicopter: `<circle cx="10" cy="10" r="5" fill="${color}"/><line x1="3" y1="5" x2="17" y2="5" stroke="${color}" stroke-width="2"/><line x1="10" y1="15" x2="10" y2="18" stroke="${color}" stroke-width="2"/>`,
  };
  const shape = shapes[subtype || 'car'] || shapes.car;
  return L.divIcon({
    html: `<svg width="20" height="20" viewBox="0 0 20 20">${shape}</svg>`,
    className: '',
    iconSize: [20, 20],
    iconAnchor: [10, 10],
  });
}

// Entity type → color mapping
const ENTITY_COLORS: Record<string, string> = {
  player: '#ef4444',   // rouge (autres joueurs)
  gangster: '#f97316',  // orange (enemy gangsters)
  building: '#8b5cf6',  // violet
  vehicle: '#06b6d4',   // cyan
  poi: '#22c55e',       // vert
  police: '#3b82f6',   // bleu (police)
};

// Allied gangster icon — green circle with rank indicator
function alliedGangsterIcon(entity: MapEntity): L.DivIcon {
  const size = 18;
  const statusColor = entity.hospitalized ? '#6b7280' : entity.in_transit ? '#3b82f6' : '#22c55e';
  const weaponDot = entity.assigned_weapon ? '<div style="position:absolute;top:-2px;right:-2px;width:6px;height:6px;background:#ef4444;border-radius:50%;border:1px solid #000;"></div>' : '';
  const guardIcon = entity.guarding_building_id ? '<div style="position:absolute;bottom:-2px;left:-2px;width:6px;height:6px;background:#f59e0b;border-radius:50%;border:1px solid #000;"></div>' : '';
  return L.divIcon({
    html: `<div style="position:relative;width:${size}px;height:${size}px;">
      <div style="width:${size}px;height:${size}px;background:${statusColor};border:2px solid #15803d;border-radius:50%;box-shadow:0 0 8px ${statusColor}80;display:flex;align-items:center;justify-content:center;">
        <span style="font-size:8px;font-weight:bold;color:#fff;line-height:1;">${entity.grade || 1}</span>
      </div>
      ${weaponDot}${guardIcon}
    </div>`,
    className: '',
    iconSize: [size, size],
    iconAnchor: [size / 2, size / 2],
  });
}

// Enemy gangster icon — red/orange circle
function enemyGangsterIcon(): L.DivIcon {
  const size = 14;
  return L.divIcon({
    html: `<div style="width:${size}px;height:${size}px;background:#ef4444;border:2px solid #991b1b;border-radius:50%;box-shadow:0 0 8px #ef444480;"></div>`,
    className: '',
    iconSize: [size, size],
    iconAnchor: [size / 2, size / 2],
  });
}

export function GameMap() {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstance = useRef<L.Map | null>(null);
  const layerGroups = useRef<Record<string, L.LayerGroup>>({});
  const entityMarkers = useRef<Map<string, L.Marker>>(new Map());
  const playerMarkerRef = useRef<L.Marker | null>(null);
  const territoryMarkerRef = useRef<L.Marker | null>(null);
  const influenceCircleRef = useRef<L.Circle | null>(null);
  const visibilityCircleRef = useRef<L.Circle | null>(null);
  // Phase 15 (20-04-2026) — mode map-pick : le OrderWizard active ce mode
  // pour intercepter le prochain clic POI/carte, animer la cible, et
  // renvoyer le résultat via CustomEvent('map-pick-result').
  const mapPickRef = useRef<{ active: boolean; expects: 'poi' | 'location' | 'both' }>({ active: false, expects: 'both' });

  // audit 15-04-2026 feedback : les filtres POI sont scindes en 2 niveaux :
  //  - `layers` conserve uniquement les COUCHES systeme (overlays + entites non-batiment)
  //  - les 5 super-categories batiment (commerces/residences/act_illicites/entrepots/services)
  //    passent par `poiSuperCategoryFilter` dans le mapStore (multi-selection, vide = tout).
  // On retire du layers[] les entrees redondantes 'buildings' et 'poi'.
  const [layers, setLayers] = useState<MapLayer[]>([
    { id: 'influence', label: t('map.layerInfluence'), visible: true },
    { id: 'visibility', label: t('map.layerVisibility'), visible: true },
    { id: 'players', label: 'Joueurs', visible: true },
    { id: 'gangsters', label: 'Gangsters', visible: true },
    { id: 'threats', label: 'Menaces', visible: true },
    { id: 'vehicles', label: 'Vehicules', visible: true },
    { id: 'police', label: 'Police', visible: true },
  ]);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedPoiId, setSelectedPoiId] = useState<string | null>(null);

  // Phase 1 refonte markers (mai 2026) — précharge les SVG game-icons fréquents
  // pour éviter le scintillement au 1er rendu. Idempotent.
  useEffect(() => { preloadCommon(); }, []);

  // Store data
  const playerPosition = useMapStore((s) => s.playerPosition);
  const activeJourney = useMapStore((s) => s.activeJourney);
  const visiblePlayers = useMapStore((s) => s.visiblePlayers);
  const visibleGangsters = useMapStore((s) => s.visibleGangsters);
  const visibleThreats = useMapStore((s) => s.visibleThreats);
  const visibleBuildings = useMapStore((s) => s.visibleBuildings);
  const visibleVehicles = useMapStore((s) => s.visibleVehicles);
  const visiblePOIs = useMapStore((s) => s.visiblePOIs);
  const visiblePolice = useMapStore((s) => s.visiblePolice);
  // Phase 15 Commit 3 (20-04-2026) — territoires cartel par palier heat
  const visibleCartelTerritories = useMapStore((s) => s.visibleCartelTerritories);
  // Phase 7 markers (2026-05-07) — missions actives géolocalisées du joueur
  const visibleMissions = useMapStore((s) => s.visibleMissions);

  // audit 15-04-2026 feedback : multi-selection des super-categories POI (vide = tout visible)
  const poiSuperCategoryFilter = useMapStore((s) => s.poiSuperCategoryFilter);
  const togglePoiSuperCategory = useMapStore((s) => s.togglePoiSuperCategory);
  const clearPoiSuperCategoryFilter = useMapStore((s) => s.clearPoiSuperCategoryFilter);

  // audit 15-04-2026 feedback : filtre applique aux pois/buildings par super-category.
  // Empty filter = show all (UX standard). Non-empty = only matching super-categories.
  const filteredPOIs = useMemo(() => {
    if (poiSuperCategoryFilter.size === 0) return visiblePOIs;
    return visiblePOIs.filter((p) => {
      const sc = (p.super_category ?? null) as POISuperCategory | null;
      return sc ? poiSuperCategoryFilter.has(sc) : false;
    });
  }, [visiblePOIs, poiSuperCategoryFilter]);

  const filteredBuildings = useMemo(() => {
    if (poiSuperCategoryFilter.size === 0) return visibleBuildings;
    return visibleBuildings.filter((b) => {
      const sc = (b.super_category ?? null) as POISuperCategory | null;
      return sc ? poiSuperCategoryFilter.has(sc) : false;
    });
  }, [visibleBuildings, poiSuperCategoryFilter]);

  // Player data from gameStore
  const player = useGameStore((s) => s.player);
  const gauges = useGameStore((s) => s.gauges);
  const playerId = player?.id ?? null;

  // Socket.IO connection
  const { startJourney, startGangsterJourney, startMultiGangsterJourney, executeAction, enterVehicle, exitVehicle } = useMapSocket(playerId);

  // Context menu
  const openContextMenu = useMapStore((s) => s.openContextMenu);
  const closeContextMenu = useMapStore((s) => s.closeContextMenu);
  const contextMenu = useMapStore((s) => s.contextMenu);

  // Gangster move mode
  const selectedGangster = useMapStore((s) => s.selectedGangster);
  const setSelectedGangster = useMapStore((s) => s.setSelectedGangster);

  // Initialize playerPosition from player data on mount (fixes marker stuck at start position)
  const setPlayerPosition = useMapStore((s) => s.setPlayerPosition);
  useEffect(() => {
    if (!playerPosition && player) {
      const lat = player.current_lat ?? player.start_lat;
      const lon = player.current_lon ?? player.start_lon;
      if (lat && lon) {
        setPlayerPosition(lat, lon);
      }
    }
  }, [player, playerPosition, setPlayerPosition]);

  // Determine actual player position (from journey interpolation or static)
  const effectivePosition = useMemo(() => {
    if (activeJourney && activeJourney.status === 'in_transit') {
      const pos = getInterpolatedJourneyPosition(
        activeJourney.start_lat,
        activeJourney.start_lon,
        activeJourney.end_lat,
        activeJourney.end_lon,
        activeJourney.started_at,
        activeJourney.estimated_arrival,
      );
      return pos;
    }
    if (playerPosition) return playerPosition;
    // Use current position (real-time) if available
    if (player?.current_lat && player?.current_lon) {
      return { lat: player.current_lat, lon: player.current_lon };
    }
    // Fallback: player spawn position from onboarding
    if (player?.start_lat && player?.start_lon) {
      return { lat: player.start_lat, lon: player.start_lon };
    }
    return { lat: 48.8566, lon: 2.3522 }; // Paris fallback
  }, [activeJourney, playerPosition, player]);

  // Default influence radius (from player data or 1000m)
  const influenceRadius = player?.influence_radius_m ?? 1000;
  const heatColor = useMemo(() => {
    const heat = Number(gauges?.chaleur ?? 0);
    if (heat >= 80) return '#ef4444';
    if (heat >= 60) return '#f97316';
    if (heat >= 40) return '#3b82f6';
    return '#22c55e';
  }, [gauges?.chaleur]);

  // === INIT MAP ===
  useEffect(() => {
    if (!mapRef.current || mapInstance.current) return;

    const map = L.map(mapRef.current, {
      center: [effectivePosition.lat, effectivePosition.lon],
      zoom: 15,
      zoomControl: false,
      attributionControl: false,
    });

    // Dark-tinted OSM tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; OSM',
    }).addTo(map);

    // Night overlay — opacity based on server time (Paris timezone)
    const getNightOpacity = (): number => {
      const now = new Date();
      // Paris time approximation: UTC+1 winter, UTC+2 summer
      const month = now.getUTCMonth();
      const offset = (month >= 2 && month <= 9) ? 2 : 1;
      const hour = (now.getUTCHours() + offset) % 24;
      // Night: 20h-6h, progressive transition
      if (hour >= 21 || hour < 5) return 0.3;       // Full night
      if (hour >= 20) return (hour - 20) * 0.3;     // Dusk transition
      if (hour < 6) return (6 - hour) * 0.15;       // Dawn transition
      return 0;                                       // Day
    };

    const nightOverlay = L.rectangle(
      [[-90, -180], [90, 180]],
      { fillColor: '#0a0a1a', fillOpacity: getNightOpacity(), stroke: false, interactive: false },
    ).addTo(map);

    // Update night opacity every 5 minutes
    const nightInterval = setInterval(() => {
      nightOverlay.setStyle({ fillOpacity: getNightOpacity() });
    }, 5 * 60 * 1000);

    L.control.zoom({ position: 'bottomright' }).addTo(map);
    L.control.attribution({ position: 'bottomleft', prefix: false }).addTo(map);

    // Left-click on map — move gangster(s) there (ou map-pick si actif)
    map.on('click', (e: L.LeafletMouseEvent) => {
      // Phase 15 (20-04-2026) — interception map-pick : wizard attend une cible
      if (mapPickRef.current.active) {
        const { expects } = mapPickRef.current;
        if (expects === 'location' || expects === 'both') {
          // Flash visuel au point cliqué
          flashLocation(map, e.latlng.lat, e.latlng.lng);
          mapPickRef.current.active = false;
          window.dispatchEvent(new CustomEvent('map-pick-result', {
            detail: { lat: e.latlng.lat, lng: e.latlng.lng },
          }));
        }
        return; // ne pas déclencher startJourney pendant le pick
      }

      const state = useMapStore.getState();
      // Multi-gangster mode takes priority
      if (state.selectionMode && state.selectedGangsterIds.length > 0) {
        startMultiGangsterJourney(state.selectedGangsterIds, { lat: e.latlng.lat, lon: e.latlng.lng });
        state.clearGangsterSelection();
        return;
      }
      // Legacy single gangster mode
      const gs = state.selectedGangster;
      if (gs) {
        startGangsterJourney(gs.gangId, gs.playerId, { lat: e.latlng.lat, lon: e.latlng.lng });
        state.setSelectedGangster(null);
      }
    });

    // Phase 15 (20-04-2026) — map-pick events du OrderWizard
    const onPickStart = (evt: Event) => {
      const d = (evt as CustomEvent).detail as { expects: 'poi' | 'location' | 'both' };
      mapPickRef.current = { active: true, expects: d?.expects || 'both' };
      // Curseur visuel crosshair
      if (map.getContainer()) map.getContainer().style.cursor = 'crosshair';
    };
    const onPickCancel = () => {
      mapPickRef.current.active = false;
      if (map.getContainer()) map.getContainer().style.cursor = '';
    };
    const onPickResultOrEsc = () => {
      if (map.getContainer()) map.getContainer().style.cursor = '';
    };
    window.addEventListener('map-pick-start', onPickStart);
    window.addEventListener('map-pick-cancel', onPickCancel);
    window.addEventListener('map-pick-result', onPickResultOrEsc);
    const escHandler = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && mapPickRef.current.active) {
        mapPickRef.current.active = false;
        if (map.getContainer()) map.getContainer().style.cursor = '';
        window.dispatchEvent(new CustomEvent('map-pick-cancel'));
      }
    };
    document.addEventListener('keydown', escHandler);

    // Right-click on empty map = "Se deplacer ici"
    map.on('contextmenu', (e: L.LeafletMouseEvent) => {
      e.originalEvent.preventDefault();
      openContextMenu(
        e.originalEvent.clientX,
        e.originalEvent.clientY,
        { type: 'map', id: 'map', lat: e.latlng.lat, lon: e.latlng.lng, name: 'Carte' },
        [],
      );
    });

    // Influence zone circle (gold) — FIXE sur start_lat/lon (zone d'empire, ne bouge jamais)
    const territoryLat = player?.start_lat ?? effectivePosition.lat;
    const territoryLon = player?.start_lon ?? effectivePosition.lon;
    const influenceCircle = L.circle(
      [territoryLat, territoryLon],
      {
        radius: influenceRadius,
        color: '#d4a843',
        fillColor: '#d4a843',
        fillOpacity: 0.08,
        weight: 1,
        dashArray: '8 4',
      },
    ).addTo(map);
    influenceCircleRef.current = influenceCircle;

    // Phase 11 (2026-04-20) — Territory SVG historic=fort shape.
    // Couleur : violet (#8b5cf6) = JOUEUR, puis rouge = ennemi, vert = cartel allié
    // (traité côté marker VisibilityService.cartelTerritories pour les tiers).
    // Propre marker du joueur = TOUJOURS violet (son propre point de territoire).
    const TERRITORY_COLOR = '#8b5cf6';
    const territoryIcon = L.divIcon({
      html: `<div style="width:22px;height:22px;background:${TERRITORY_COLOR};border:2px solid #c4b5fd;border-radius:5px;box-shadow:0 0 12px rgba(139,92,246,0.7);cursor:pointer;display:flex;align-items:center;justify-content:center;">
        <svg width="18" height="18" viewBox="0 0 18 18">
          <path d="M3 13h12M4 13v-5h2v-2h2v2h2v-2h2v2h2v5" fill="none" stroke="#fff" stroke-width="1.3"/>
        </svg>
      </div>`,
      className: '',
      iconSize: [22, 22],
      iconAnchor: [11, 11],
    });
    // Phase 8.5d (2026-04-29) — Bug 5 fix : ne PAS afficher le marker
    // territoire si territory_destroyed=true (le fort violet doit disparaître).
    const territoryMarker = L.marker(
      [territoryLat, territoryLon],
      { icon: territoryIcon, zIndexOffset: 500 },
    );
    if (!player?.territory_destroyed) {
      territoryMarker.addTo(map);
    }

    // Click on territory → open territory stats popup
    territoryMarker.on('click', () => {
      const p = useGameStore.getState().player;
      const g = useGameStore.getState().gauges;
      const radius = p?.influence_radius_m ?? 1000;
      const radiusKm = (radius / 1000).toFixed(1);
      const influence = g?.influence ?? 0;
      const tLat = p?.start_lat ?? territoryLat;
      const tLon = p?.start_lon ?? territoryLon;
      // Phase 8.5d (2026-04-29) — Bug 6 fix : ajout PV territoire dans popup
      const tHp = (p as any)?.territory_hp ?? 1000;
      const tHpMax = 1000;
      const hpPct = Math.round((tHp / tHpMax) * 100);
      const hpColor = hpPct < 25 ? '#ef4444' : hpPct < 50 ? '#f97316' : hpPct < 75 ? '#eab308' : '#22c55e';

      // Check if enemies are in territory zone (threats + enemy players)
      const threats = useMapStore.getState().visibleThreats;
      const enemies = useMapStore.getState().visiblePlayers;
      const radiusKmNum = radius / 1000;
      const haversine = (lat1: number, lon1: number, lat2: number, lon2: number) => {
        const R = 6371;
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a = Math.sin(dLat/2)**2 + Math.cos(lat1*Math.PI/180)*Math.cos(lat2*Math.PI/180)*Math.sin(dLon/2)**2;
        return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      };
      const enemiesInZone = [...threats, ...enemies].filter(e =>
        haversine(tLat, tLon, e.lat, e.lon) <= radiusKmNum
      );
      const underAttack = enemiesInZone.length > 0;

      // Phase 8.5d (2026-04-29) — Bug 6 fix : barre PV territoire visible
      // dans la popup, couleur dégradée selon HP %.
      let popupHtml =
        `<div style="min-width:220px;font-family:system-ui;font-size:11px;">` +
        `<p style="font-weight:bold;color:#d4a843;font-size:13px;margin:0 0 8px;">Point de Territoire</p>` +
        `<div style="margin:4px 0 8px;">` +
        `<div style="display:flex;justify-content:space-between;font-size:10px;color:#a0a0a0;margin-bottom:2px;">` +
        `<span>PV territoire</span><span style="color:${hpColor};font-weight:bold;">${tHp} / ${tHpMax}</span></div>` +
        `<div style="height:6px;background:rgba(255,255,255,0.08);border-radius:3px;overflow:hidden;">` +
        `<div style="height:100%;width:${hpPct}%;background:${hpColor};transition:width 0.3s;"></div></div>` +
        `</div>` +
        `<p style="color:#a0a0a0;margin:3px 0;">Rayon d'influence : <b style="color:#e0e0e0">${radiusKm} km</b></p>` +
        `<p style="color:#a0a0a0;margin:3px 0;">Points d'influence : <b style="color:#e0e0e0">${influence}</b></p>` +
        `<p style="color:#a0a0a0;margin:3px 0;">Chaleur : <b style="color:#e0e0e0">${g?.chaleur ?? 0}%</b></p>` +
        `<p style="color:#a0a0a0;margin:3px 0;">Respect : <b style="color:#e0e0e0">${g?.respect ?? 0}%</b></p>`;

      if (underAttack) {
        popupHtml +=
          `<div style="margin-top:8px;padding:6px 8px;background:rgba(239,68,68,0.15);border:1px solid rgba(239,68,68,0.4);border-radius:6px;">` +
          `<p style="color:#ef4444;font-weight:bold;margin:0 0 4px;">ALERTE — ${enemiesInZone.length} ennemi(s) dans la zone</p>` +
          `<button onclick="window.__territoryDefend && window.__territoryDefend()" ` +
          `style="width:100%;padding:5px 0;background:#ef4444;color:#fff;border:none;border-radius:4px;font-size:11px;font-weight:bold;cursor:pointer;">` +
          `Rentrer defendre</button>` +
          `</div>`;
      }

      popupHtml += `</div>`;

      territoryMarker.unbindPopup();
      territoryMarker.bindPopup(popupHtml, { className: 'territory-popup' }).openPopup();

      // Wire the defend button
      (window as any).__territoryDefend = () => {
        startJourney({ lat: tLat, lon: tLon }, player?.active_vehicle_id || undefined);
        territoryMarker.closePopup();
      };
    });

    // Right-click on territory → context menu with "Rentrer defendre"
    territoryMarker.on('contextmenu', (e: L.LeafletMouseEvent) => {
      e.originalEvent.preventDefault();
      e.originalEvent.stopPropagation();
      openContextMenu(
        e.originalEvent.clientX,
        e.originalEvent.clientY,
        { type: 'territory', id: 'territory', lat: territoryLat, lon: territoryLon, name: 'Point de Territoire' },
        [],
      );
    });

    territoryMarkerRef.current = territoryMarker;

    // Visibility zone circle (gray, 1.5x influence)
    const visibilityCircle = L.circle(
      [effectivePosition.lat, effectivePosition.lon],
      {
        radius: influenceRadius * 1.5,
        color: heatColor,
        fillColor: heatColor,
        fillOpacity: 0.05,
        weight: 1,
        dashArray: '4 8',
      },
    ).addTo(map);
    visibilityCircleRef.current = visibilityCircle;

    // Player avatar marker — Phase 5 refonte (mai 2026) : SVG game-icons.
    // char-person par défaut, char-beams-aura si chaleur ≥ 95, composite véhicule sinon.
    // Initialisation : on rend l'avatar libre par défaut, le useEffect dédié update ensuite.
    const playerIcon = buildPlayerAvatarIcon('free', null);
    const playerMarker = L.marker(
      [effectivePosition.lat, effectivePosition.lon],
      { icon: playerIcon, zIndexOffset: 1000 },
    ).addTo(map).bindPopup('<b style="color:#6d48c2">Vous</b>');
    playerMarkerRef.current = playerMarker;

    // Entity layer groups
    // audit 15-04-2026 feedback : on conserve 'buildings' + 'poi' en layerGroups
    // (necessaires pour le rendu), mais ces groupes ne sont plus exposes comme
    // couches toggle-ables dans layers[]. Leur visibilite est entierement
    // controlee par poiSuperCategoryFilter (vide = tout visible).
    layerGroups.current = {
      influence: L.layerGroup([influenceCircle]).addTo(map),
      visibility: L.layerGroup([visibilityCircle]).addTo(map),
      players: L.layerGroup().addTo(map),
      gangsters: L.layerGroup().addTo(map),
      threats: L.layerGroup().addTo(map),
      buildings: L.layerGroup().addTo(map),
      vehicles: L.layerGroup().addTo(map),
      poi: L.layerGroup().addTo(map),
      police: L.layerGroup().addTo(map),
      missions: L.layerGroup().addTo(map),
    };

    mapInstance.current = map;

    // MiniMap (bottom-left)
    try {
      const MiniMap = require('leaflet-minimap');
      const miniTiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 });
      const minimap = new MiniMap.default(miniTiles, {
        toggleDisplay: true,
        minimized: false,
        position: 'bottomleft',
        width: 120,
        height: 90,
        zoomLevelOffset: -5,
        strings: { hideText: '', showText: '' },
      });
      minimap.addTo(map);
    } catch (_e) {
      // MiniMap plugin not available — skip silently
    }

    return () => {
      clearInterval(nightInterval);
      map.remove();
      mapInstance.current = null;
      entityMarkers.current.clear();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // === UPDATE PLAYER ICON — Phase 5+6 refonte (mai 2026) ===
  // Recompute l'état joueur à chaque changement, puis re-render le marker.
  // Phase 6 : prison / GAV / tribunal / évasion / conqueror / méditation / mort 0PV.
  // Pour les états temporaires (conqueror 60s, dead_0pv 60s), planifie un
  // re-render à expiration via scheduleStateExpiry.
  useEffect(() => {
    if (!playerMarkerRef.current) return;
    const stateInput = {
      active_vehicle_id: player?.active_vehicle_id ?? null,
      heat: gauges?.chaleur ?? null,
      meditating_until: player?.meditating_until ?? null,
      imprisoned_until: player?.imprisoned_until ?? null,
      is_in_gav: player?.is_in_gav ?? false,
      is_at_tribunal: player?.is_at_tribunal ?? false,
      is_evading: player?.is_evading ?? false,
      last_territory_won_at: player?.last_territory_won_at ?? null,
      health_hp: player?.health_hp ?? null,
    };
    const state = derivePlayerState(stateInput);
    const newIcon = buildPlayerAvatarIcon(state, player?.active_vehicle_type ?? null);
    playerMarkerRef.current.setIcon(newIcon);

    // Re-render à l'expiration des états temporaires (60s pour conqueror/mort,
    // ou fin imprisoned_until/meditating_until). Force-trigger via state setter.
    const expiryMs = getStateExpiryMs(stateInput);
    const cancel = scheduleStateExpiry(expiryMs, () => {
      // À l'expiration, re-derive l'état (qui sera 'free' / 'free_hot' /
      // 'in_vehicle' selon les autres conditions). Le marker se met à jour.
      if (!playerMarkerRef.current) return;
      const newState = derivePlayerState(stateInput);
      playerMarkerRef.current.setIcon(buildPlayerAvatarIcon(newState, player?.active_vehicle_type ?? null));
    });
    return cancel;
  }, [
    player?.active_vehicle_id,
    player?.active_vehicle_type,
    gauges?.chaleur,
    player?.meditating_until,
    player?.imprisoned_until,
    player?.is_in_gav,
    player?.is_at_tribunal,
    player?.is_evading,
    player?.last_territory_won_at,
    player?.health_hp,
  ]);

  // === UPDATE INFLUENCE CIRCLE + TERRITORY MARKER (fixed on start_lat/lon) ===
  useEffect(() => {
    if (player?.start_lat && player?.start_lon) {
      const pos: L.LatLngExpression = [player.start_lat, player.start_lon];
      influenceCircleRef.current?.setLatLng(pos);
      influenceCircleRef.current?.setRadius(player.influence_radius_m ?? 1000);
      territoryMarkerRef.current?.setLatLng(pos);
    }
  }, [player?.start_lat, player?.start_lon, player?.influence_radius_m]);

  // === UPDATE PLAYER POSITION ===
  useEffect(() => {
    if (!mapInstance.current) return;
    const pos: L.LatLngExpression = [effectivePosition.lat, effectivePosition.lon];
    playerMarkerRef.current?.setLatLng(pos);
    // influenceCircleRef → NE PAS bouger, reste fixe sur start_lat/lon
    visibilityCircleRef.current?.setLatLng(pos);
  }, [effectivePosition]);

  useEffect(() => {
    if (!visibilityCircleRef.current) return;
    visibilityCircleRef.current.setStyle({
      color: heatColor,
      fillColor: heatColor,
      fillOpacity: 0.05,
      weight: 1,
      dashArray: '4 8',
    });
  }, [heatColor]);

  // === SYNC ENTITY MARKERS ===
  useEffect(() => {
    if (!mapInstance.current) return;

    // audit 15-04-2026 feedback : POIs/buildings filtres par super-category
    // via filteredPOIs/filteredBuildings (derives de poiSuperCategoryFilter).
    const allEntities: Array<{ entities: MapEntity[]; groupKey: string }> = [
      { entities: visiblePlayers, groupKey: 'players' },
      { entities: visibleGangsters, groupKey: 'gangsters' },
      { entities: visibleThreats, groupKey: 'threats' },
      { entities: filteredBuildings, groupKey: 'buildings' },
      { entities: visibleVehicles, groupKey: 'vehicles' },
      { entities: filteredPOIs, groupKey: 'poi' },
      { entities: visiblePolice, groupKey: 'police' },
    ];

    // Track which markers should exist
    const activeIds = new Set<string>();

    for (const { entities, groupKey } of allEntities) {
      const group = layerGroups.current[groupKey];
      if (!group) continue;

      for (const entity of entities) {
        const key = `${groupKey}:${entity.id}`;
        activeIds.add(key);

        const existing = entityMarkers.current.get(key);
        if (existing) {
          // Update position
          existing.setLatLng([entity.lat, entity.lon]);
        } else {
          // Create new marker with type-specific icon
          const color = groupKey === 'threats' ? '#ef4444' : (ENTITY_COLORS[entity.type] || '#06b6d4');
          let markerIcon: L.DivIcon;
          if (groupKey === 'police') {
            // Phase 4 bis markers (2026-05-07) — Police via SVG game-icons.
            // Backend expose des subtypes enrichis (mun/nat distinct) :
            //   police_municipale, police_nationale, bac, stups,
            //   gign_blinde, gign_helicoptere (véhicules)
            //   police_mun_pied, police_nat_pied, gign_pied, fbi, dea (piétons)
            // Compat : si une unité legacy arrive avec patrol_car/patrol_foot
            // (branch NULL), on retombe sur le rendu municipale.
            const sub = (entity.subtype || '').toLowerCase();
            let policeCfg: ReturnType<typeof resolveVehicleMarker> = null;
            const isPed = sub.endsWith('_pied') || sub === 'patrol_foot' || sub === 'fbi' || sub === 'dea';
            if (isPed) {
              const role = sub === 'patrol_foot' ? 'police_mun_pied' : sub;
              policeCfg = resolveNpcMarker(role) ?? resolveNpcMarker('police_mun_pied');
            } else {
              const role = sub === 'patrol_car' || sub === 'patrol_moto' || sub === '' ? 'police_municipale' : sub;
              policeCfg = resolveVehicleMarker(role) ?? resolveVehicleMarker('police_municipale');
            }
            if (policeCfg && hasSvg(policeCfg.svgFile)) {
              markerIcon = buildMarkerIcon(policeCfg);
            } else {
              // Fallback : ancien rendu cercle bleu/rouge à 2 niveaux
              const ps = 14;
              let outer = '#3b82f6', inner = '#fff';
              if (sub === 'patrol_car' || sub === 'patrol_foot') { outer = '#3b82f6'; inner = '#fff'; }
              else if (sub === 'patrol_moto') { outer = '#fff'; inner = '#3b82f6'; }
              else if (sub === 'bac' || sub === 'stups') { outer = '#3b82f6'; inner = '#ef4444'; }
              else if (sub.startsWith('gign')) { outer = '#ef4444'; inner = '#111'; }
              markerIcon = L.divIcon({
                html: `<div style="width:${ps}px;height:${ps}px;background:${outer};border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 0 6px ${outer}80;">
                  <div style="width:${ps - 6}px;height:${ps - 6}px;background:${inner};border-radius:50%;"></div>
                </div>`,
                className: '',
                iconSize: [ps, ps],
                iconAnchor: [ps / 2, ps / 2],
              });
            }
          } else if (entity.type === 'vehicle') {
            const isPlayerVehicle = entity.entity_id === playerId;
            markerIcon = vehicleIcon(entity.subtype, isPlayerVehicle);
          } else if (entity.type === 'gangster' && entity.allied) {
            markerIcon = alliedGangsterIcon(entity);
          } else if (entity.type === 'gangster' && !entity.allied) {
            markerIcon = enemyGangsterIcon();
          } else if (entity.type === 'building' || entity.type === 'poi') {
            markerIcon = poiIcon(entity);
          } else {
            markerIcon = circleIcon(color, 10);
          }
          const marker = L.marker([entity.lat, entity.lon], {
            icon: markerIcon,
          });
          if (groupKey === 'police') {
            marker.bindPopup(
              `<b style="color:#3b82f6">${entity.name || 'Police'}</b><br>` +
              `<small style="color:#94a3b8">${entity.in_transit ? 'En intervention' : 'En patrouille'}</small>`,
            );
          } else if (entity.type === 'poi') {
            marker.on('click', () => {
              // Phase 15 (20-04-2026) — map-pick : intercepte le clic POI,
              // anime le marker (shrink → vert → grow) et dispatch le result.
              if (mapPickRef.current.active) {
                const { expects } = mapPickRef.current;
                if (expects === 'poi' || expects === 'both') {
                  const poiType = (entity as any).poi_type || entity.subtype || 'business';
                  const poiId = (entity.entity_id as string) || entity.id;
                  animatePoiPick(marker);
                  mapPickRef.current.active = false;
                  setTimeout(() => {
                    window.dispatchEvent(new CustomEvent('map-pick-result', {
                      detail: { poi_type: poiType, poi_id: poiId },
                    }));
                  }, 600); // attend la fin de l'animation avant de remonter le modal
                  return;
                }
                // expects === 'location' : cliquer sur un POI pointe son latlng
                if (expects === 'location') {
                  const pos = marker.getLatLng();
                  animatePoiPick(marker);
                  mapPickRef.current.active = false;
                  setTimeout(() => {
                    window.dispatchEvent(new CustomEvent('map-pick-result', {
                      detail: { lat: pos.lat, lng: pos.lng },
                    }));
                  }, 600);
                  return;
                }
              }
              setSelectedPoiId(entity.id);
            });
          } else if (entity.type === 'building') {
            marker.on('click', () => {
              if (mapPickRef.current.active) {
                const { expects } = mapPickRef.current;
                if (expects === 'poi' || expects === 'both') {
                  // building utilise subtype ∈ {business, residence, warehouse, hideout}
                  const poiType = entity.subtype || 'business';
                  const poiId = (entity.entity_id as string) || entity.id;
                  animatePoiPick(marker);
                  mapPickRef.current.active = false;
                  setTimeout(() => {
                    window.dispatchEvent(new CustomEvent('map-pick-result', {
                      detail: { poi_type: poiType, poi_id: poiId },
                    }));
                  }, 600);
                  return;
                }
                if (expects === 'location') {
                  const pos = marker.getLatLng();
                  animatePoiPick(marker);
                  mapPickRef.current.active = false;
                  setTimeout(() => {
                    window.dispatchEvent(new CustomEvent('map-pick-result', {
                      detail: { lat: pos.lat, lng: pos.lng },
                    }));
                  }, 600);
                  return;
                }
              }
              setSelectedPoiId(entity.id);
            });
          } else if (entity.type === 'gangster' && entity.allied) {
            // Ctrl+click = toggle multi-selection
            marker.on('click', (e: L.LeafletMouseEvent) => {
              if (e.originalEvent.ctrlKey || e.originalEvent.metaKey) {
                e.originalEvent.stopPropagation();
                if (entity.gang_id && !entity.hospitalized) {
                  useMapStore.getState().toggleGangsterSelection(entity.gang_id, entity.id);
                }
              }
            });
            // Rich popup for allied gangsters
            const status = entity.hospitalized ? '<span style="color:#ef4444">Hospitalise</span>'
              : entity.in_transit ? '<span style="color:#3b82f6">En transit</span>'
              : entity.guarding_building_id ? '<span style="color:#f59e0b">En garde</span>'
              : entity.assigned_racket_zone_id ? '<span style="color:#a855f7">En racket</span>'
              : '<span style="color:#22c55e">Disponible</span>';
            const weapon = entity.assigned_weapon ? `<br><small>Arme: ${entity.assigned_weapon}</small>` : '';
            marker.bindPopup(
              `<b style="color:#22c55e">${entity.name || 'Gangster'}</b><br>` +
              `<small style="color:#d4a843">${entity.grade_name || 'Recrue'} (Grade ${entity.grade || 1})</small><br>` +
              `<small>${status}</small>${weapon}`,
            );
          } else if (entity.type === 'gangster' && !entity.allied) {
            marker.bindPopup(
              `<b style="color:#ef4444">Gangster ennemi</b><br><small>Grade ${entity.grade || '?'}</small>`,
            );
          } else if (entity.name) {
            marker.bindPopup(
              `<b style="color:${color}">${entity.name}</b><br><small>${entity.type}</small>`,
            );
          }

          // Right-click context menu on all entity types
          marker.on('contextmenu', (e: L.LeafletMouseEvent) => {
            e.originalEvent.preventDefault();
            e.originalEvent.stopPropagation();
            openContextMenu(
              e.originalEvent.clientX,
              e.originalEvent.clientY,
              {
                type: entity.type,
                id: entity.id,
                lat: entity.lat,
                lon: entity.lon,
                name: entity.name || entity.type,
                gang_id: entity.gang_id,
                allied: entity.allied,
                grade_name: entity.grade_name,
                hospitalized: entity.hospitalized,
              },
              [], // actions will be fetched by the context menu or filled inline
            );
          });
          marker.addTo(group);
          entityMarkers.current.set(key, marker);
        }
      }
    }

    // Remove markers for entities no longer visible
    for (const [key, marker] of entityMarkers.current) {
      if (!activeIds.has(key)) {
        marker.remove();
        entityMarkers.current.delete(key);
      }
    }
  }, [visiblePlayers, visibleGangsters, visibleThreats, filteredBuildings, visibleVehicles, filteredPOIs, visiblePolice, playerId]);

  // === PHASE 7 MARKERS (2026-05-07) — Mission markers géolocalisés ===
  // Render un marker par MissionProgress 'in_progress' du joueur dont la
  // cible a été résolue. Icône : MISSION_MARKERS[mission.category].
  // Click : popup titre + statut. Pas de map-pick (pas une cible cliquable).
  useEffect(() => {
    const map = mapInstance.current;
    const group = layerGroups.current['missions'];
    if (!map || !group) return;

    const activeIds = new Set<string>();
    for (const m of visibleMissions) {
      activeIds.add(m.id);
      const cfg = resolveMissionMarker(m.category);
      if (!cfg) continue;
      const icon = buildMarkerIcon(cfg);

      const existing = missionMarkersRef.current.get(m.id);
      if (existing) {
        existing.setLatLng([m.lat, m.lon]);
        existing.setIcon(icon);
      } else {
        const marker = L.marker([m.lat, m.lon], { icon, zIndexOffset: 800 }).addTo(group);
        marker.bindPopup(
          `<div style="min-width:140px">` +
            `<div style="font-weight:700;color:#facc15">${m.name || 'Mission'}</div>` +
            `<div style="font-size:10px;color:#94a3b8;margin-top:2px">Catégorie : ${m.category}</div>` +
            `<div style="font-size:10px;color:#22c55e;margin-top:2px">Statut : ${m.status}</div>` +
          `</div>`,
        );
        missionMarkersRef.current.set(m.id, marker);
      }
    }

    // Retire les markers de missions qui ne sont plus actives
    for (const [id, marker] of missionMarkersRef.current) {
      if (!activeIds.has(id)) {
        marker.remove();
        missionMarkersRef.current.delete(id);
      }
    }
  }, [visibleMissions]);

  // === PHASE 15 COMMIT 3 (20-04-2026) — Cartel Territory markers par palier heat ===
  // Les territoires cartel sont rendus via des DivIcon losanges violets/rouges
  // avec opacité/détails variables selon visibility_level :
  //   - 'gps'   → losange translucide 20% opacity, pas de popup détaillé
  //   - 'name'  → opacity 55%, popup : nom cartel + HP
  //   - 'full'  → opacity 90%, popup complet + cercle d'influence autour
  //   - 'owned' → couleur dorée (votre cartel), opacity 100%, influence visible
  const cartelTerritoryMarkersRef = useRef<Map<string, { marker: L.Marker; circle?: L.Circle }>>(new Map());
  // Phase 7 markers (2026-05-07) — markers de missions actives géolocalisées.
  const missionMarkersRef = useRef<Map<string, L.Marker>>(new Map());
  useEffect(() => {
    const map = mapInstance.current;
    if (!map) return;

    const activeIds = new Set<string>();

    for (const t of visibleCartelTerritories) {
      activeIds.add(t.id);
      const level = t.visibility_level;

      // Phase 16 (2026-04-21) — consigne user #433 :
      //   VIOLET = Joueur (point de territoire propre sans cartel) — géré ailleurs
      //   VERT VIF = cartel du joueur (owned)
      //   VERT FONCÉ = cartel allié (alliance accepted)
      //   ROUGE = cartel étranger (ennemi par défaut)
      const fill =
        level === 'owned' ? '#22c55e'    // vert vif — mon cartel
        : level === 'ally'  ? '#166534'  // vert foncé — cartel allié
        : '#ef4444';                      // rouge — cartel étranger (full/name/gps)
      const opacity =
        level === 'owned' ? 1.0
        : level === 'ally' ? 0.95
        : level === 'full' ? 0.9
        : level === 'name' ? 0.55
        : 0.25;
      const size = level === 'gps' ? 12 : 18;
      const borderColor =
        t.is_origin && (level === 'owned' || level === 'ally' || level === 'full') ? '#fde047' : 'rgba(0,0,0,0.6)';

      const html = `
        <div style="
          width:${size}px;height:${size}px;
          background:${fill};
          opacity:${opacity};
          transform: rotate(45deg);
          border: 2px solid ${borderColor};
          box-shadow: 0 0 6px rgba(0,0,0,0.5);
          ${t.custody_active ? 'filter: grayscale(0.6);' : ''}
        "></div>
      `;
      const icon = L.divIcon({
        className: 'cartel-territory-marker',
        html,
        iconSize: [size, size],
        iconAnchor: [size / 2, size / 2],
      });

      const existing = cartelTerritoryMarkersRef.current.get(t.id);
      let marker = existing?.marker;
      if (marker) {
        marker.setLatLng([t.lat, t.lng]);
        marker.setIcon(icon);
      } else {
        marker = L.marker([t.lat, t.lng], { icon, zIndexOffset: 200 }).addTo(map);
      }

      // Popup (uniquement si palier ≥ name)
      if (level !== 'gps') {
        const hpPct = t.hp && t.hp_max ? Math.round((t.hp / t.hp_max) * 100) : null;
        const heatBadge = t.cartel_heat !== null && t.cartel_heat !== undefined
          ? `<span style="color:#ef4444">🔥 ${Math.round(t.cartel_heat)}</span>`
          : '';
        const custodyBadge = t.custody_active
          ? '<div style="color:#f59e0b;font-size:10px;margin-top:3px">⚠ Administration arrêtée</div>'
          : '';
        const popupHtml = `
          <div style="min-width:160px">
            <div style="font-weight:700;color:#a855f7">${t.cartel_name || 'Cartel'}</div>
            <div style="font-size:10px;color:#94a3b8">${t.is_origin ? '★ Origine' : 'Annexe'}</div>
            ${hpPct !== null ? `<div style="font-size:10px;margin-top:3px">HP : ${t.hp}/${t.hp_max} (${hpPct}%)</div>` : ''}
            ${heatBadge ? `<div style="font-size:10px;margin-top:3px">${heatBadge}</div>` : ''}
            ${custodyBadge}
          </div>
        `;
        marker.unbindPopup();
        marker.bindPopup(popupHtml);
      } else {
        marker.unbindPopup();
      }

      // Cercle d'influence (full, owned ou ally)
      let circle = existing?.circle;
      if ((level === 'full' || level === 'owned' || level === 'ally') && t.influence_radius_m) {
        if (circle) {
          circle.setLatLng([t.lat, t.lng]);
          circle.setRadius(t.influence_radius_m);
        } else {
          circle = L.circle([t.lat, t.lng], {
            radius: t.influence_radius_m,
            color: fill,
            weight: 1,
            fillColor: fill,
            fillOpacity: 0.08,
            interactive: false,
          }).addTo(map);
        }
      } else if (circle) {
        circle.remove();
        circle = undefined;
      }

      cartelTerritoryMarkersRef.current.set(t.id, { marker, circle });
    }

    // Remove stale markers
    for (const [id, obj] of cartelTerritoryMarkersRef.current) {
      if (!activeIds.has(id)) {
        obj.marker.remove();
        obj.circle?.remove();
        cartelTerritoryMarkersRef.current.delete(id);
      }
    }
  }, [visibleCartelTerritories]);

  // === PHASE 15 ITER 8.2 (19-04-2026) — Combat flash animation ===
  // Écoute 'combat-flash' (dispatché par useMapSocket sur 'combat:resolved').
  // Flash CSS sur le marker du POI ciblé : vert si victoire côté attaquant, rouge sinon.
  useEffect(() => {
    const handler = (e: Event) => {
      const d = (e as CustomEvent).detail as any;
      if (!d?.poi_id) return;
      const keyPoi = `poi:${d.poi_id}`;
      const keyBuilding = `buildings:${d.poi_id}`;
      const marker = entityMarkers.current.get(keyPoi) || entityMarkers.current.get(keyBuilding);
      if (!marker) return;
      const el = (marker as any).getElement?.() as HTMLElement | null;
      if (!el) return;
      // Couleur : victoire côté attaquant ou défaite côté défenseur = vert (attaquant perçoit victoire)
      const isWin = d.side === 'attacker' ? d.victory : !d.victory;
      const cls = isWin ? 'combat-flash-green' : 'combat-flash-red';
      el.classList.remove('combat-flash-green', 'combat-flash-red');
      // Force reflow pour relancer l'animation CSS
      void el.offsetWidth;
      el.classList.add(cls);
      window.setTimeout(() => el.classList.remove(cls), 1600);
    };
    window.addEventListener('combat-flash', handler);
    return () => window.removeEventListener('combat-flash', handler);
  }, []);

  // === RACKET ZONE POLYGONS ===
  const racketPolygonsRef = useRef<L.Polygon[]>([]);
  const [racketZonesLoaded, setRacketZonesLoaded] = useState(false);

  useEffect(() => {
    if (!mapInstance.current) return;
    // Fetch racket zones on mount + every 60s
    const fetchAndDraw = async () => {
      try {
        const zones = await apiFetch<any[]>('/api/racket/mine').catch(() => null);
        if (!Array.isArray(zones) || !mapInstance.current) return;
        // Clean previous
        racketPolygonsRef.current.forEach((p) => p.remove());
        racketPolygonsRef.current = [];
        // Draw new
        for (const zone of zones) {
          const hull: number[][] = zone.convex_hull;
          if (!Array.isArray(hull) || hull.length < 3) continue;
          const latLngs: L.LatLngExpression[] = hull.map((p: number[]) => [p[1], p[0]]);
          const polygon = L.polygon(latLngs, {
            color: '#a855f7',
            fillColor: '#a855f7',
            fillOpacity: 0.12,
            weight: 2,
            dashArray: '6, 4',
          });
          polygon.bindPopup(
            `<div style="font-family:system-ui;"><b style="color:#a855f7">\u{1F4B0} Zone de racket</b><br>` +
            `<small>Revenus: ${zone.revenue_per_cycle || 0} I\u221E/cycle</small><br>` +
            `<small>Batiments: ${zone.building_ids?.length || 0}</small><br>` +
            `<small>Gangsters: ${zone.assigned_gangster_ids?.length || 0}</small></div>`
          );
          polygon.addTo(mapInstance.current!);
          racketPolygonsRef.current.push(polygon);
        }
        setRacketZonesLoaded(true);
      } catch {
        // Silent: racket feature may not be unlocked
      }
    };

    fetchAndDraw();
    const interval = setInterval(fetchAndDraw, 60_000);
    return () => {
      clearInterval(interval);
      racketPolygonsRef.current.forEach((p) => p.remove());
      racketPolygonsRef.current = [];
    };
  }, [mapInstance.current]);

  // === JOURNEY INTERPOLATION TICK (smooth 60fps) ===
  useEffect(() => {
    if (!activeJourney || activeJourney.status !== 'in_transit') return;

    let rafId: number;
    const startTime = new Date(activeJourney.started_at).getTime();
    const endTime = new Date(activeJourney.estimated_arrival).getTime();

    const tick = () => {
      const progress = clamp(calculateProgress(Date.now(), startTime, endTime), 0, 1);
      const pos = interpolatePositionEased(
        { lat: activeJourney.start_lat, lon: activeJourney.start_lon },
        { lat: activeJourney.end_lat, lon: activeJourney.end_lon },
        progress,
      );
      playerMarkerRef.current?.setLatLng([pos.lat, pos.lon]);
      visibilityCircleRef.current?.setLatLng([pos.lat, pos.lon]);

      if (progress < 1) {
        rafId = requestAnimationFrame(tick);
      }
    };

    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [activeJourney]);

  // === CONTROLS ===
  const centerOnPlayer = () => {
    mapInstance.current?.flyTo(
      [effectivePosition.lat, effectivePosition.lon],
      15,
      { duration: 0.5 },
    );
  };

  const toggleLayer = (id: string) => {
    setLayers((prev) =>
      prev.map((l) => {
        if (l.id !== id) return l;
        const newVisible = !l.visible;
        const group = layerGroups.current[id];
        if (group && mapInstance.current) {
          if (newVisible) group.addTo(mapInstance.current);
          else group.remove();
        }
        return { ...l, visible: newVisible };
      }),
    );
  };

  return (
    <div className="relative w-full h-full" style={{ isolation: 'isolate', zIndex: 0 }}>
      <div ref={mapRef} className="absolute inset-0" />

      {/* Phase 8 v2 (2026-05-01) — POI Croix rouge soin urgentiste, posé
          sur la map quand session active (poll 30s). Clic ouvre la lightbox
          via window event 'urgentist-care-open-lightbox'. */}
      <UrgentistPoiMarker map={mapInstance.current} />

      {/* Map controls overlay */}
      <div className="absolute top-3 right-3 z-[1000] flex flex-col gap-2">
        {/* Center on player */}
        <button
          onClick={centerOnPlayer}
          className="w-9 h-9 rounded-lg flex items-center justify-center transition-colors hover:scale-105"
          style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
          title={t('map.centerPlayer')}
        >
          <Crosshair size={16} style={{ color: 'var(--color-gold)' }} />
        </button>

        {/* Filter toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className="w-9 h-9 rounded-lg flex items-center justify-center transition-colors hover:scale-105"
          style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
          title={t('map.filters')}
        >
          <Filter size={16} style={{ color: showFilters ? 'var(--color-gold)' : 'var(--text-muted)' }} />
        </button>
      </div>

      {/* Layer filter panel — audit 15-04-2026 feedback : 2 sections distinctes.
          Haut : couches systeme (influence/visibility/entites).
          Bas : 5 super-categories POI (commerces/residences/act_illicites/entrepots/services).
          Empty filter = tout visible (UX standard). */}
      {showFilters && (
        <div
          className="absolute top-3 right-14 z-[1000] rounded-lg p-3 min-w-[200px]"
          style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
        >
          {/* Section 1 : Couches systeme */}
          <div className="flex items-center gap-2 mb-2">
            <Layers size={14} style={{ color: 'var(--color-gold)' }} />
            <span className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>Couches</span>
          </div>
          {layers.map((layer) => (
            <label key={layer.id} className="flex items-center gap-2 py-1 cursor-pointer">
              <input
                type="checkbox"
                checked={layer.visible}
                onChange={() => toggleLayer(layer.id)}
                className="accent-[var(--color-gold)]"
              />
              <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>{layer.label}</span>
            </label>
          ))}

          {/* Section 2 : Super-categories POI (5 filtres top-level) */}
          <div
            className="mt-3 pt-3"
            style={{ borderTop: '1px solid var(--border-dark)' }}
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>Batiments</span>
              {poiSuperCategoryFilter.size > 0 && (
                <button
                  onClick={clearPoiSuperCategoryFilter}
                  className="text-[10px] px-1.5 py-0.5 rounded hover:opacity-80"
                  style={{
                    background: 'rgba(212,168,67,0.15)',
                    border: '1px solid rgba(212,168,67,0.3)',
                    color: 'var(--color-gold)',
                  }}
                  title="Afficher tous les batiments"
                >
                  Tout
                </button>
              )}
            </div>
            {POI_SUPER_CATEGORIES.map((sc) => {
              const active = poiSuperCategoryFilter.has(sc);
              return (
                <label
                  key={sc}
                  className="flex items-center gap-2 py-1 cursor-pointer"
                  title={
                    poiSuperCategoryFilter.size === 0
                      ? `Filtrer uniquement : ${POI_SUPER_CATEGORY_LABELS[sc]}`
                      : active
                        ? 'Retirer ce filtre'
                        : 'Ajouter a la selection'
                  }
                >
                  <input
                    type="checkbox"
                    checked={active}
                    onChange={() => togglePoiSuperCategory(sc)}
                    className="accent-[var(--color-gold)]"
                  />
                  <span style={{ color: active ? 'var(--color-gold)' : 'var(--text-muted)' }}>
                    {SUPER_CATEGORY_ICONS[sc]}
                  </span>
                  <span
                    className="text-xs"
                    style={{ color: active ? 'var(--text-primary)' : 'var(--text-secondary)' }}
                  >
                    {POI_SUPER_CATEGORY_LABELS[sc]}
                  </span>
                </label>
              );
            })}
            {poiSuperCategoryFilter.size === 0 && (
              <p className="text-[10px] mt-1 italic" style={{ color: 'var(--text-muted)' }}>
                Aucun filtre = tout visible
              </p>
            )}
          </div>
        </div>
      )}

      {/* Gangster panel — top left, multi-selection */}
      <GangsterPanel
        onReturnToBase={(gangsterKeys) => {
          if (player?.start_lat && player?.start_lon) {
            startMultiGangsterJourney(gangsterKeys, { lat: player.start_lat, lon: player.start_lon });
          }
        }}
      />

      {/* Gangster move mode indicator (legacy single) */}
      {selectedGangster && !useMapStore.getState().selectionMode && (
        <div
          className="absolute top-4 left-1/2 -translate-x-1/2 z-[1000] rounded-lg px-4 py-2 text-xs flex items-center gap-3"
          style={{ background: 'var(--bg-panel)', border: '1px solid #22c55e', color: '#22c55e' }}
        >
          <span>Cliquez sur la carte pour deplacer <b>{selectedGangster.name}</b></span>
          <button
            onClick={() => setSelectedGangster(null)}
            className="px-2 py-0.5 rounded text-[10px]"
            style={{ background: 'rgba(239,68,68,0.2)', color: '#ef4444', border: '1px solid #ef4444' }}
          >
            Annuler
          </button>
        </div>
      )}

      {/* Active journey indicator */}
      {activeJourney && activeJourney.status === 'in_transit' && (
        <div
          className="absolute bottom-4 left-1/2 -translate-x-1/2 z-[1000] rounded-lg px-4 py-2 text-xs"
          style={{ background: 'var(--bg-panel)', border: '1px solid var(--color-gold)', color: 'var(--color-gold)' }}
        >
          En route... ETA: {new Date(activeJourney.estimated_arrival).toLocaleTimeString()}
        </div>
      )}

      <POILightbox
        open={!!selectedPoiId}
        poiId={selectedPoiId}
        onClose={() => setSelectedPoiId(null)}
      />

      {/* Phase 15 v2 (2026-04-22) — vehicle actions handler (carjack / recovery / garage) */}
      <VehicleActionHandler />

      {/* Phase 4 (2026-04-26) — Soudoyer POI gouvernemental (police/townhall/courthouse).
          Listen sur 'poi-bribe-open' event dispatché par POILightbox. */}
      <PoiBribeModal />

      {/* Context menu (right-click / long-press) */}
      <MapContextMenu
        onMove={(lat, lon) => {
          startJourney({ lat, lon }, player?.active_vehicle_id || undefined);
        }}
        onMoveGangster={(gangId, gangsterPlayerId, lat, lon) => {
          startGangsterJourney(gangId, gangsterPlayerId, { lat, lon });
        }}
        onMoveMultiGangsters={(gangsterKeys, lat, lon) => {
          startMultiGangsterJourney(gangsterKeys, { lat, lon });
        }}
        onAction={(actionCode, targetType, targetId) => {
          executeAction(actionCode, targetType, targetId);
        }}
        onEnterVehicle={(vehicleId) => {
          enterVehicle(vehicleId);
        }}
        onExitVehicle={() => {
          exitVehicle();
        }}
        onOpenPOI={(poiId) => {
          setSelectedPoiId(poiId);
        }}
      />
    </div>
  );
}

