/**
 * Live pin filters for the map's "map options" menu — visited status and
 * list membership. Module state rather than route/component props for the
 * same reason as `list-view.ts`: `m-map` lives outside the router and
 * persists across navigations, so it can't receive these as attributes.
 *
 * Distinct from `list-view.ts`'s `getListFilter`, which is the exclusive
 * single-list scope set by a list's own "View on map" action. This filter
 * is additive — it narrows the `/` map view to one or more lists without
 * navigating anywhere — and is ignored while the exclusive scope is active.
 */
export const MAP_FILTER_EVENT = 'map-filter'

export type VisitedFilter = 'all' | 'visited' | 'unvisited'

let visitedFilter: VisitedFilter = 'all'
let favoritesOnly = false
let listFilterIds = new Set<string>()

export function getVisitedFilter(): VisitedFilter {
  return visitedFilter
}

export function setVisitedFilter(value: VisitedFilter): void {
  if (value === visitedFilter) return
  visitedFilter = value
  globalThis.dispatchEvent(new CustomEvent(MAP_FILTER_EVENT))
}

export function getFavoritesFilter(): boolean {
  return favoritesOnly
}

export function setFavoritesFilter(value: boolean): void {
  if (value === favoritesOnly) return
  favoritesOnly = value
  globalThis.dispatchEvent(new CustomEvent(MAP_FILTER_EVENT))
}

export function getListFilterIds(): ReadonlySet<string> {
  return listFilterIds
}

export function toggleListFilterId(id: string, on: boolean): void {
  const next = new Set(listFilterIds)
  if (on) next.add(id)
  else next.delete(id)
  listFilterIds = next
  globalThis.dispatchEvent(new CustomEvent(MAP_FILTER_EVENT))
}
