import type { Bounds } from './bounds.ts'

export type TileManifestEntry = {
  id: string
  filename?: string
  label: string
  description?: string
  /** URL the archive is served from, e.g. `/static/tiles/africa/algeria.pmtiles`. */
  path?: string
  group: string
  bounds?: Bounds
}

/** Fallback label for a group segment with no manifest entry of its own. */
export function slugToLabel(slug: string): string {
  if (slug === 'us') return 'US'
  return slug.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join(' ')
}

/**
 * Label of the region one level up from `tile` (e.g. "Spain" for a Spanish
 * province), or `null` when the tile sits directly under a continent.
 */
export function parentLabel(
  tile: TileManifestEntry,
  manifest: TileManifestEntry[],
): string | null {
  const parts = tile.group.split('/')
  if (parts.length < 2) return null
  const parentId = parts[parts.length - 1]
  const parentGroup = parts.slice(0, -1).join('/')
  const parent = manifest.find(
    (t) => t.id === parentId && t.group === parentGroup,
  )
  return parent?.label ?? slugToLabel(parentId)
}

let _cache: TileManifestEntry[] | null = null

export async function fetchTileManifest(): Promise<TileManifestEntry[]> {
  if (_cache) return _cache
  try {
    const res = await fetch('/static/tiles/tiles.json')
    if (!res.ok) return []
    const entries = (await res.json()) as TileManifestEntry[]
    _cache = entries
    return entries
  } catch {
    return []
  }
}
