import maplibregl, { type LayerSpecification } from 'maplibre-gl';

export function ensureSeamarkOverlay(map: maplibregl.Map, beforeLayerId?: string) {
  const srcId = 'seamark';
  const layerId = 'seamark';

  if (!map.getSource(srcId)) {
    map.addSource(srcId, {
      type: 'raster',
      tiles: ['https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png'],
      tileSize: 256,
      attribution: '© OpenSeaMap contributors',
    });
  }

  if (!map.getLayer(layerId)) {
    const layer: LayerSpecification = {
      id: layerId,
      type: 'raster',
      source: srcId,
      paint: { 'raster-opacity': 0.85 },
    } as unknown as LayerSpecification;

    const before = beforeLayerId && map.getLayer(beforeLayerId) ? beforeLayerId : undefined;
    map.addLayer(layer, before);
  }
}
