import { useEffect, useRef, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import { applyEncVisibility, applyEncColors } from '../lib/encSettings';
import type { EncMapSettings } from '../model/types';
import type { BaseMapId } from '../../../widgets/map3d/types';

/**
 * Applies ENC map settings changes at runtime (no style reload).
 */
export function useEncMapSettings(
  mapRef: MutableRefObject<maplibregl.Map | null>,
  baseMap: BaseMapId,
  settings: EncMapSettings,
) {
  const prevRef = useRef<EncMapSettings>(settings);

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

    const prev = prevRef.current;
    prevRef.current = settings;

    const toggleKeys = [
      'showBuoys', 'showBeacons', 'showLights', 'showDangers', 'showLandmarks',
      'showSoundings', 'showPilot', 'showAnchorage', 'showRestricted',
      'showDredged', 'showTSS', 'showContours',
    ] as const;

    if (toggleKeys.some((k) => prev[k] !== settings[k])) {
      applyEncVisibility(map, settings);
    }

    const colorKeys = [
      'landColor', 'coastlineColor', 'backgroundColor',
      'depthDrying', 'depthVeryShallow', 'depthSafetyZone', 'depthMedium', 'depthDeep',
    ] as const;
    if (colorKeys.some((k) => prev[k] !== settings[k])) {
      applyEncColors(map, settings);
    }
  }, [baseMap, settings]);
}
