import type { LayerSpecification, StyleSpecification } from 'maplibre-gl';
import { getMapTilerKey } from '../../../shared/lib/map/mapTilerKey';

export async function resolveOceanStyle(signal: AbortSignal): Promise<StyleSpecification> {
  const key = getMapTilerKey();
  if (!key) throw new Error('MapTiler key not found');

  const url = `https://api.maptiler.com/maps/ocean/style.json?key=${encodeURIComponent(key)}`;
  const res = await fetch(url, { signal, headers: { accept: 'application/json' } });
  if (!res.ok) throw new Error(`Ocean style fetch failed: ${res.status}`);
  const style = (await res.json()) as StyleSpecification;

  applyOceanKoreanLabels(style);
  return style;
}

function applyOceanKoreanLabels(style: StyleSpecification) {
  if (!style.layers) return;
  const koTextField = ['coalesce', ['get', 'name:ko'], ['get', 'name']];
  for (const layer of style.layers as unknown as LayerSpecification[]) {
    if ((layer as { type?: string }).type !== 'symbol') continue;
    const layout = (layer as Record<string, unknown>).layout as Record<string, unknown> | undefined;
    if (!layout?.['text-field']) continue;
    layout['text-field'] = koTextField;
  }
}
