const BASE = 'https://nominatim.openstreetmap.org'

function headers() {
  return { 'Accept-Language': navigator.language || 'en' }
}

export interface NominatimAddress {
  city?: string
  city_district?: string
  country?: string
  country_code?: string
  house_number?: string
  historic?: string
  'ISO3166-2-lvl4'?: string
  'ISO3166-2-lvl6'?: string
  postcode?: string
  region?: string
  road?: string
  suburb?: string
  state?: string
}

export interface NominatimResult {
  place_id: number
  display_name: string
  lat: string
  lon: string
  boundingbox: [string, string, string, string]
  name?: string
  class?: string
  type?: string
  importance?: number
  place_rank?: number
  osm_type?: string
  osm_id?: number
  address?: NominatimAddress
}

export async function nominatimSearch(
  query: string,
  limit = 5,
): Promise<NominatimResult[]> {
  const url = new URL(`${BASE}/search`)
  url.searchParams.set('q', query)
  url.searchParams.set('format', 'json')
  url.searchParams.set('limit', String(limit))
  url.searchParams.set('addressdetails', '1')
  const res = await fetch(url.toString(), { headers: headers() })
  if (!res.ok) throw new Error(`Nominatim error: ${res.status}`)
  return res.json() as Promise<NominatimResult[]>
}

export async function nominatimReverse(
  lat: number,
  lon: number,
): Promise<NominatimResult> {
  const url = new URL(`${BASE}/reverse`)
  url.searchParams.set('lat', String(lat))
  url.searchParams.set('lon', String(lon))
  url.searchParams.set('format', 'json')
  url.searchParams.set('addressdetails', '1')
  const res = await fetch(url.toString(), { headers: headers() })
  if (!res.ok) throw new Error(`Nominatim error: ${res.status}`)
  return res.json() as Promise<NominatimResult>
}
