import type maplibregl from 'maplibre-gl'

export type Bounds = [number, number, number, number]

export function toBounds(bounds: maplibregl.LngLatBounds): Bounds {
  return [
    bounds.getWest(),
    bounds.getSouth(),
    bounds.getEast(),
    bounds.getNorth(),
  ]
}

export function expandBounds(
  bounds: maplibregl.LngLatBounds,
  factor: number,
): Bounds {
  const [w, s, e, n] = toBounds(bounds)
  const dx = (e - w) * factor / 2
  const dy = (n - s) * factor / 2
  return [w - dx, s - dy, e + dx, n + dy]
}

export function boundsIntersect(a: Bounds, b: Bounds): boolean {
  return !(a[2] < b[0] || a[0] > b[2] || a[3] < b[1] || a[1] > b[3])
}

export function pointInBounds(
  point: readonly [number, number],
  bounds: Bounds,
): boolean {
  const [lng, lat] = point
  return lng >= bounds[0] && lng <= bounds[2] && lat >= bounds[1] &&
    lat <= bounds[3]
}

/** Inverse of `bounds.join(',')` — the URL-safe round-trip for handing a
 * viewport across a page navigation (the share-list "import visible only"
 * handoff, which can't carry live component state). */
export function parseBounds(value: string | null): Bounds | null {
  if (!value) return null
  const parts = value.split(',').map(Number)
  if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) return null
  return parts as Bounds
}
