import type { StyleSpecification } from 'maplibre-gl';

const NAUTICAL_STYLE_URL = 'https://tiles.gcnautical.com/styles/nautical.json';

/** Fonts available on the tile server */
const SERVER_FONTS = ['Noto Sans CJK KR Regular', 'Noto Sans Regular'];

/**
 * Fetch the nautical chart style from gcnautical tile server.
 * Patches text-font arrays to use only server-supported fonts (avoids 404 on composite fontstack).
 */
export async function fetchEncStyle(signal: AbortSignal): Promise<StyleSpecification> {
  const res = await fetch(NAUTICAL_STYLE_URL, { signal });
  if (!res.ok) throw new Error(`ENC style fetch failed: ${res.status}`);
  const style = (await res.json()) as StyleSpecification;

  // Patch text-font to avoid composite fontstack 404 errors
  for (const layer of style.layers) {
    const layout = (layer as { layout?: Record<string, unknown> }).layout;
    if (!layout) continue;
    const tf = layout['text-font'];
    if (Array.isArray(tf) && tf.every((v) => typeof v === 'string')) {
      layout['text-font'] = SERVER_FONTS;
    }
  }

  return style;
}
