import { useEffect, useMemo, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { BaseMapId } from '../types';
import { computeShipLabelColors, type ShipLabelColors } from '../lib/labelColor';
import type { EncMapSettings } from '../../../features/encMap/model/types';
import { DEFAULT_ENC_MAP_SETTINGS } from '../../../features/encMap/model/types';

/** Default colors for non-ENC basemaps (dark background) */
const DARK_BG_COLORS = computeShipLabelColors('#010610');

/**
 * Compute ship label colors based on the current basemap background.
 * Updates Globe MapLibre text-color paint property on style changes.
 */
export function useShipLabelColor(
  mapRef: MutableRefObject<maplibregl.Map | null>,
  baseMap: BaseMapId,
  mapSyncEpoch: number,
  encMapSettings?: EncMapSettings,
): ShipLabelColors {
  const bgHex = baseMap === 'enc'
    ? (encMapSettings ?? DEFAULT_ENC_MAP_SETTINGS).backgroundColor
    : '#010610';

  const colors = useMemo(() => computeShipLabelColors(bgHex), [bgHex]);

  // Update Globe label paint properties when colors change
  useEffect(() => {
    const map = mapRef.current;
    if (!map) return;

    const applyGlobeLabelColor = () => {
      const labelLayerId = 'ships-globe-label';
      try {
        if (!map.getLayer(labelLayerId)) return;

        // Preserve selected/highlighted colors, only change default
        map.setPaintProperty(labelLayerId, 'text-color', [
          'case',
          ['==', ['feature-state', 'selected'], 1], 'rgba(14,234,255,0.95)',
          ['==', ['feature-state', 'highlighted'], 1], 'rgba(245,158,11,0.95)',
          colors.mlDefault,
        ] as never);
        map.setPaintProperty(labelLayerId, 'text-halo-color', colors.mlHalo);
      } catch {
        // layer may not exist yet
      }
    };

    // Apply immediately and also on next style ready
    applyGlobeLabelColor();
  }, [colors, mapSyncEpoch]);

  return baseMap === 'enc' ? colors : DARK_BG_COLORS;
}
