import { unzipSync } from 'fflate'
import type { ImportResult, ParsedBookmark } from './types.ts'

export type { ImportResult, ParsedBookmark } from './types.ts'

export function parseKml(text: string): ImportResult {
  const doc = new DOMParser().parseFromString(text, 'text/xml')
  const folders: ImportResult['folders'] = []
  const bookmarks: ParsedBookmark[] = []
  let counter = 0

  // Prefer <Document> as root container, fall back to document element
  const root = doc.querySelector('Document') ?? doc.documentElement

  for (const child of root.children) {
    if (child.localName === 'Folder') {
      const tempId = `f${counter++}`
      const name = child.querySelector('name')?.textContent?.trim() ??
        'Imported Folder'
      folders.push({ tempId, name })
      // Collect all placemarks inside this folder (nested folders are flattened)
      for (const pm of child.querySelectorAll('Placemark')) {
        const bm = parsePlacemark(pm, tempId)
        if (bm) bookmarks.push(bm)
      }
    } else if (child.localName === 'Placemark') {
      const bm = parsePlacemark(child, null)
      if (bm) bookmarks.push(bm)
    }
  }

  return { folders, bookmarks }
}

export function parseKmz(buffer: ArrayBuffer): ImportResult {
  const files = unzipSync(new Uint8Array(buffer))
  const entry = Object.keys(files).find((k) => k === 'doc.kml') ??
    Object.keys(files).find((k) => k.endsWith('.kml'))
  if (!entry) throw new Error('No KML file found in KMZ archive')
  return parseKml(new TextDecoder().decode(files[entry]))
}

function parsePlacemark(
  el: Element,
  folderTempId: string | null,
): ParsedBookmark | null {
  const coordText = el.querySelector('coordinates')?.textContent?.trim()
  if (!coordText) return null
  // KML coordinates are lng,lat,alt — take the first point
  const parts = coordText.split(/\s+/)[0].split(',')
  if (parts.length < 2) return null
  const lng = parseFloat(parts[0])
  const lat = parseFloat(parts[1])
  if (isNaN(lat) || isNaN(lng)) return null

  const name = el.querySelector('name')?.textContent?.trim() || undefined
  const addressText = el.querySelector('address')?.textContent?.trim() ||
    undefined
  const description = el.querySelector('description')?.textContent?.trim() ||
    undefined

  return {
    lat,
    lng,
    folderTempId,
    properties: {
      name,
      description,
      address: addressText ? { displayText: addressText } : undefined,
    },
  }
}
