/**
 * Hook Socket.IO pour la carte temps réel.
 *
 * Se connecte au namespace /map du serveur et synchronise
 * les entités visibles, les voyages et les actions dans le mapStore.
 *
 * Usage: appeler useMapSocket(playerId) dans le composant GameMap
 * ou dans un layout parent authentifié.
 */
import { useEffect, useRef, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
import { useMapStore } from '@/stores/mapStore';
import { useGameStore } from '@/stores/gameStore';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.mafiaz.world';

export function useMapSocket(playerId: string | null) {
  const socketRef = useRef<Socket | null>(null);

  const setVisibleEntities = useMapStore((s) => s.setVisibleEntities);
  const setActiveJourney = useMapStore((s) => s.setActiveJourney);
  const setPlayerPosition = useMapStore((s) => s.setPlayerPosition);
  const setPoliceFile = useGameStore((s) => s.setPoliceFile);

  // Connexion au namespace /map
  useEffect(() => {
    if (!playerId) return;

    const token = typeof window !== 'undefined' ? localStorage.getItem('ol_token') : null;
    const socket = io(`${API_URL}/map`, {
      transports: ['polling'],
      withCredentials: true,
      auth: token ? { token } : undefined,
    });
    socketRef.current = socket;

    socket.on('connect', () => {
      console.log('[MAP-WS] Connected to /map namespace');
      // Demander les entités visibles au démarrage
      socket.emit('map:request-visible', { playerId });
    });

    // — Réception des entités visibles —
    socket.on('map:visible-entities', (data) => {
      setVisibleEntities(data);
    });

    socket.on('map:visible-entities-update', (data) => {
      setVisibleEntities(data);
    });

    // — Voyages —
    socket.on('map:journey-confirmed', (journey) => {
      setActiveJourney(journey);
    });

    socket.on('map:journey-arrived', (data) => {
      if (data.entity_type === 'player' && data.entity_id === playerId) {
        setActiveJourney(null);
        setPlayerPosition(data.final_pos.lat, data.final_pos.lon);
      }
    });

    socket.on('map:journey-started', (data) => {
      console.log('[MAP-WS] Journey started:', data.player_id || data.gang_id);
    });

    // — Gangster journey confirmation —
    socket.on('map:gangster-journey-confirmed', (journey) => {
      console.log('[MAP-WS] Gangster journey confirmed:', journey.id);
      // Refresh visible entities to show gangster in_transit
      if (socket.connected) {
        socket.emit('map:request-visible', { playerId });
      }
    });

    // — Multi-gangster journey confirmation —
    socket.on('map:multi-gangster-journey-confirmed', (data) => {
      console.log(`[MAP-WS] Multi-gangster journey: ${data.succeeded}/${data.total} dispatched`);
      if (socket.connected) {
        socket.emit('map:request-visible', { playerId });
      }
    });

    // — Mouvements d'autres joueurs —
    socket.on('map:player-moved', (_data) => {
      // Le mapStore sera rafraîchi via request-visible périodique
    });

    // — Résultats d'actions —
    socket.on('map:action-confirmed', (result) => {
      console.log('[MAP-WS] Action result:', result);
    });

    // — Police file live update (Phase 13.e) —
    // Backend emits after PoliceService.registerCrime or JudicialService
    // convict/release. Keeps Dossier pénal and prison switch in sync live.
    socket.on('police-file:updated', (data) => {
      if (data?.player_id && data.player_id !== playerId) return;
      setPoliceFile({
        arrest_count: data.arrest_count ?? 0,
        incarceration_count: data.incarceration_count ?? 0,
        judicial_status: data.judicial_status ?? 'citoyen',
        degree: data.degree ?? 0,
        total_crimes: data.total_crimes ?? 0,
        imprisoned_until: data.imprisoned_until ?? null,
      });
    });

    // — Phase 15 Iter 8.2 (19-04-2026) — Combat résolu (flash POI carte) —
    socket.on('combat:resolved', (data) => {
      window.dispatchEvent(new CustomEvent('combat-flash', { detail: data }));
    });

    // — Phase 7 (2026-04-29) — Judicial flow step-by-step —
    // step-changed : transitions de l'état (garde_a_vue → jugement → released/imprisoned/fine_active)
    // bakchich-proposed : issue 'bakchich' tirée → JudicialFlowModal ouvre BakchichConfirm lightbox
    socket.on('judicial:step-changed', (data) => {
      window.dispatchEvent(new CustomEvent('judicial-step-changed', { detail: data }));
    });
    socket.on('judicial:bakchich-proposed', (data) => {
      window.dispatchEvent(new CustomEvent('judicial-bakchich-proposed', { detail: data }));
    });

    // — Phase 8.5 (2026-04-29) — GIGN combat events —
    // territory-destroyed : HP territoire = 0 → arrestation 8 jours imminente
    // all-units-killed    : toutes les unités GIGN tuées → -5 chaleur + cooldown 24h
    socket.on('gign:territory-destroyed', (data) => {
      window.dispatchEvent(new CustomEvent('gign:territory-destroyed', { detail: data }));
    });
    socket.on('gign:all-units-killed', (data) => {
      window.dispatchEvent(new CustomEvent('gign:all-units-killed', { detail: data }));
    });
    socket.on('gign:escape-scheduled', (data) => {
      window.dispatchEvent(new CustomEvent('gign:escape-scheduled', { detail: data }));
    });
    // Phase 8.5d (2026-04-29) — Countdown arrivée GIGN au spawn (60s)
    socket.on('gign:incoming', (data) => {
      window.dispatchEvent(new CustomEvent('gign:incoming', { detail: data }));
    });

    // — Erreurs —
    socket.on('map:error', (err) => {
      console.error('[MAP-WS] Error:', err.message);
    });

    socket.on('disconnect', () => {
      console.log('[MAP-WS] Disconnected from /map');
    });

    // Rafraîchir les entités visibles toutes les 15 secondes
    const refreshInterval = setInterval(() => {
      if (socket.connected) {
        socket.emit('map:request-visible', { playerId });
      }
    }, 15_000);

    return () => {
      clearInterval(refreshInterval);
      socket.disconnect();
      socketRef.current = null;
    };
  }, [playerId, setVisibleEntities, setActiveJourney, setPlayerPosition, setPoliceFile]);

  // Actions exposées au composant
  const startJourney = useCallback(
    (destination: { lat: number; lon: number }, vehicleId?: string) => {
      socketRef.current?.emit('map:start-journey', {
        playerId,
        destination,
        vehicle_id: vehicleId,
      });
    },
    [playerId],
  );

  const executeAction = useCallback(
    (actionCode: string, targetType: string, targetId: string, params?: Record<string, unknown>) => {
      socketRef.current?.emit('map:execute-action', {
        playerId,
        action_code: actionCode,
        target_type: targetType,
        target_id: targetId,
        params,
      });
    },
    [playerId],
  );

  const updatePosition = useCallback(
    (lat: number, lon: number, heading: number) => {
      socketRef.current?.emit('map:player-position-update', {
        playerId,
        lat,
        lon,
        heading,
      });
    },
    [playerId],
  );

  const startGangsterJourney = useCallback(
    (gangId: string, gangsterPlayerId: string, destination: { lat: number; lon: number }, vehicleId?: string) => {
      socketRef.current?.emit('map:start-gangster-journey', {
        playerId,
        gangId,
        gangsterPlayerId,
        destination,
        vehicle_id: vehicleId,
      });
    },
    [playerId],
  );

  const startMultiGangsterJourney = useCallback(
    (gangsterKeys: string[], destination: { lat: number; lon: number }) => {
      socketRef.current?.emit('map:start-multi-gangster-journey', {
        playerId,
        gangsterKeys, // format "gangId:playerId"
        destination,
      });
    },
    [playerId],
  );

  const enterVehicle = useCallback(
    (vehicleId: string) => {
      socketRef.current?.emit('map:enter-vehicle', { playerId, vehicleId });
    },
    [playerId],
  );

  const exitVehicle = useCallback(() => {
    socketRef.current?.emit('map:exit-vehicle', { playerId });
  }, [playerId]);

  return {
    startJourney,
    startGangsterJourney,
    startMultiGangsterJourney,
    executeAction,
    updatePosition,
    enterVehicle,
    exitVehicle,
    isConnected: !!socketRef.current?.connected,
  };
}
