/**
 * One-shot geolocation → city-code hook. Matches Angular's
 * `UserLocationService.location` semantics used by Online-Board,
 * Schedule, and Flight-Map. Silent on permission denial / missing API.
 *
 * Fires at most once per mount. The `shouldApply` predicate is
 * re-evaluated at callback time (after the geo permission resolves),
 * letting the caller opt out if the user has already entered a value.
 */

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

export interface UseGeoCityDefaultOptions {
  dictionaries: IDictionaries | null;
  shouldApply: () => boolean;
  onCity: (cityCode: string) => void;
}

export function useGeoCityDefault(opts: UseGeoCityDefaultOptions): void {
  const appliedRef = useRef(false);
  const optsRef = useRef(opts);
  optsRef.current = opts;

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

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { dictionaries, shouldApply, onCity } = optsRef.current;
        if (!dictionaries) return;
        if (!shouldApply()) return;
        const city = findCityByCoord(
          dictionaries,
          pos.coords.latitude,
          pos.coords.longitude,
        );
        if (!city) return;
        onCity(city.code);
      },
      () => { /* silent */ },
      { enableHighAccuracy: false, timeout: 5000 },
    );
  }, []);
}
