import type maplibregl from 'maplibre-gl'

export const TRAIN_STATION_ICON = 'train-station'

export function loadImage(src: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = () => resolve(image)
    image.onerror = reject
    image.src = src
  })
}

/** On-map footprint (in the generic station icon's own physical pixels) that
 * network logos are normalized to match — see `loadStationIcon`. */
export const STATION_ICON_SIZE = 36

/**
 * Loads `src` and redraws it onto a `STATION_ICON_SIZE`-square canvas.
 * Network logo PNGs are checked in at whatever resolution they were sourced
 * at (often much larger than the generic icon's 36×36 SVG); registering them
 * as-is under the same `pixelRatio` as the generic icon would render them
 * visibly larger on the map, so every logo is resampled to the same physical
 * size before `addImage`.
 */
export async function loadStationIcon(src: string): Promise<ImageData> {
  const image = await loadImage(src)
  const canvas = document.createElement('canvas')
  canvas.width = STATION_ICON_SIZE
  canvas.height = STATION_ICON_SIZE
  const ctx = canvas.getContext('2d')!
  ctx.drawImage(image, 0, 0, STATION_ICON_SIZE, STATION_ICON_SIZE)
  return ctx.getImageData(0, 0, STATION_ICON_SIZE, STATION_ICON_SIZE)
}

/**
 * Registers the train-station marker image on `map` if it isn't already
 * there. MapLibre has no built-in sprite pipeline here — the style is built
 * entirely in JS (see utils/layers.ts) — so this is the one raster image the
 * app loads by hand, from a pre-composed SVG rather than compositing on a
 * canvas at runtime.
 */
export async function ensureTrainStationIcon(
  map: maplibregl.Map,
): Promise<void> {
  if (map.hasImage(TRAIN_STATION_ICON)) return
  const image = await loadImage('/static/icons/trains/station.svg')
  if (!map.hasImage(TRAIN_STATION_ICON)) {
    map.addImage(TRAIN_STATION_ICON, image, { pixelRatio: 2 })
  }
}
