import { useEffect, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import type { LegacyAlarmKind } from '../../../features/legacyDashboard/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { Map3DSettings, MapProjectionId } from '../types';
import { onMapStyleReady } from '../lib/mapCore';

/**
 * Mercator 모드 선명 라벨 — 레거시 MapLibre 레이어 정리 전용.
 * 실제 라벨 렌더링은 Deck.gl TextLayer (deckLayerFactories.ts)에서 처리.
 */
export function useGlobeShipLabels(
  mapRef: MutableRefObject<maplibregl.Map | null>,
  _projectionBusyRef: MutableRefObject<boolean>,
  opts: {
    projection: MapProjectionId;
    settings: Map3DSettings;
    shipData: AisTarget[];
    shipHighlightSet: Set<number>;
    overlays: MapToggleState;
    legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
    selectedMmsi: number | null;
    mapSyncEpoch: number;
    alarmMmsiMap?: Map<number, LegacyAlarmKind>;
  },
) {
  const { mapSyncEpoch } = opts;

  useEffect(() => {
    const map = mapRef.current;
    if (!map) return;

    const srcId = 'ship-labels-src';
    const layerId = 'ship-labels';

    const remove = () => {
      try {
        if (map.getLayer(layerId)) map.removeLayer(layerId);
      } catch {
        // ignore
      }
      try {
        if (map.getSource(srcId)) map.removeSource(srcId);
      } catch {
        // ignore
      }
    };

    const ensure = () => {
      // Mercator ship labels are now rendered via Deck.gl TextLayer
      // (see buildMercatorDeckLayers in deckLayerFactories.ts).
      // Always clean up any stale MapLibre label layer.
      if (!map.isStyleLoaded()) return;
      remove();
    };

    const stop = onMapStyleReady(map, ensure);
    return () => {
      stop();
    };
  }, [mapSyncEpoch]);
}
