/**
 * Resolves the map's light/dark palette to the same choice `@civility/ui`'s
 * theme system (`modules/theme.ts`) applies to the rest of the page:
 * `data-theme` on `<html>` when the user picked light/dark explicitly, else
 * the device's `prefers-color-scheme`. MapLibre paint expressions can't read
 * CSS custom properties, so the map can't just inherit this from CSS the way
 * the rest of the app does — it has to be read and re-applied by hand,
 * here and in `layers.ts`'s `buildPalette`.
 */

const DARK_MEDIA_QUERY = '(prefers-color-scheme: dark)'

/** Whether the map should currently render its dark palette. */
export function isDarkTheme(): boolean {
  const theme = document.documentElement.dataset.theme
  if (theme === 'dark') return true
  if (theme === 'light') return false
  return matchMedia(DARK_MEDIA_QUERY).matches
}

/**
 * Calls `onChange` whenever the resolved theme could have flipped: an
 * explicit light/dark/system choice (`data-theme` mutates or clears) or,
 * while following the device, the OS setting itself changing. Returns a
 * cleanup function.
 */
export function watchMapTheme(onChange: (dark: boolean) => void): () => void {
  const media = matchMedia(DARK_MEDIA_QUERY)
  const handleChange = () => onChange(isDarkTheme())
  media.addEventListener('change', handleChange)
  const observer = new MutationObserver(handleChange)
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['data-theme'],
  })
  return () => {
    media.removeEventListener('change', handleChange)
    observer.disconnect()
  }
}
