/**
 * Sets the flights-map filter's departure to the nearest city based on
 * browser geolocation, if the user has not already typed a departure or
 * arrival. Fires once per mount. Silent on permission denial or missing
 * geolocation API. Matches Angular `UserLocationService` + `DictionariesService.locate`.
 */

import { useEffect, useRef } from "react";
import {
  findCityByCoord,
  type IDictionaries,
} from "@/shared/dictionaries/index.js";
import type { IFlightsMapFilterState } from "../types.js";

export function useGeolocationDefault(
  dictionaries: IDictionaries | null,
  filterState: IFlightsMapFilterState,
  setFilterState: (
    updater: (prev: IFlightsMapFilterState) => IFlightsMapFilterState,
  ) => void,
): void {
  const appliedRef = useRef(false);
  const dictRef = useRef(dictionaries);
  dictRef.current = dictionaries;
  const filterRef = useRef(filterState);
  filterRef.current = filterState;
  const setFilterRef = useRef(setFilterState);
  setFilterRef.current = setFilterState;

  useEffect(() => {
    if (appliedRef.current) return;
    if (typeof navigator === "undefined" || !navigator.geolocation) {
      appliedRef.current = true;
      return;
    }

    appliedRef.current = true;

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const d = dictRef.current;
        const f = filterRef.current;
        if (!d) return;
        if (f.departure || f.arrival) return;

        const city = findCityByCoord(
          d,
          pos.coords.latitude,
          pos.coords.longitude,
        );
        if (!city) return;

        setFilterRef.current((prev) =>
          prev.departure || prev.arrival
            ? prev
            : { ...prev, departure: city.code },
        );
      },
      () => {
        // Silent: permission denied / timeout / unavailable.
      },
      { enableHighAccuracy: false, timeout: 5000 },
    );
  }, []);
}
