import type maplibregl from 'maplibre-gl';
import type { EncMapSettings } from '../model/types';
import { ENC_LAYER_CATEGORIES, ENC_COLOR_TARGETS, ENC_DEPTH_COLOR_TARGETS } from '../model/types';

/**
 * Apply symbol category visibility toggles at runtime.
 */
export function applyEncVisibility(map: maplibregl.Map, settings: EncMapSettings): void {
  for (const [key, layerIds] of Object.entries(ENC_LAYER_CATEGORIES)) {
    const visible = settings[key as keyof EncMapSettings] as boolean;
    const vis = visible ? 'visible' : 'none';
    for (const layerId of layerIds) {
      try {
        if (map.getLayer(layerId)) {
          map.setLayoutProperty(layerId, 'visibility', vis);
        }
      } catch {
        // layer may not exist
      }
    }
  }
}

/**
 * Apply runtime color changes to area/line layers.
 */
export function applyEncColors(map: maplibregl.Map, settings: EncMapSettings): void {
  // 육지/해안선
  for (const [layerId, prop, key] of ENC_COLOR_TARGETS) {
    try {
      if (map.getLayer(layerId)) {
        map.setPaintProperty(layerId, prop, settings[key] as string);
      }
    } catch {
      // ignore
    }
  }

  // 배경색
  try {
    if (map.getLayer('background')) {
      map.setPaintProperty('background', 'background-color', settings.backgroundColor);
    }
  } catch {
    // ignore
  }

  // 수심별 색상
  for (const { key, layerIds } of ENC_DEPTH_COLOR_TARGETS) {
    const color = settings[key] as string;
    for (const layerId of layerIds) {
      try {
        if (map.getLayer(layerId)) {
          map.setPaintProperty(layerId, 'fill-color', color);
        }
      } catch {
        // ignore
      }
    }
  }
}
