/**
 * Airport/city dictionary hooks.
 *
 * Resolves an IATA code to its human-readable city/airport name using the
 * loaded dictionaries. Falls back to the code itself while dictionaries
 * are loading or when the code is unknown.
 *
 * Angular equivalent: DictionariesService.getCityOrAirport, which walks
 * a Map<code, CityModel | AirportModel>.
 */

import { useLocale } from "@/i18n/useLocale.js";
import { useDictionaries as useDictionariesState } from "@/shared/dictionaries/useDictionaries.js";

/**
 * Returns the city/airport name for a given IATA code. Uses the locale
 * from the current URL. Returns the code itself until dictionaries load
 * or if the code isn't in the dictionary (matches Angular's fallback —
 * see DictionariesService.getCityOrAirport).
 */
export function useCityName(code: string): string {
  const { language } = useLocale();
  const { dictionaries } = useDictionariesState(language);
  if (!code || !dictionaries) return code;
  const upper = code.toUpperCase();
  const city = dictionaries.cityByCode.get(upper);
  if (city) return city.name;
  const airport = dictionaries.airportByCode.get(upper);
  if (airport) {
    // Angular's `getCityOrAirport` resolves airport codes up to their
    // parent city when possible (SVO → Москва) — only falls back to
    // the airport name when the city isn't dictionarised.
    const parent = airport.city_code
      ? dictionaries.cityByCode.get(airport.city_code.toUpperCase())
      : null;
    if (parent) return parent.name;
    return airport.name;
  }
  return code;
}

/**
 * Resolve a station IATA to its display name following Angular's
 * `getCityOrAirport` rule: city dictionary first (so true city codes
 * like LED → "Санкт-Петербург", MOW → "Москва" win), and only when
 * the code isn't a city does it fall through to the airport dictionary
 * (SVO → "Шереметьево"). Crucially this does NOT escalate from an
 * airport up to its parent city — used by the Onlineboard breadcrumb
 * leaf for departure/arrival URLs.
 */
export function useStationDisplayName(code: string): string {
  const { language } = useLocale();
  const { dictionaries } = useDictionariesState(language);
  if (!code || !dictionaries) return code;
  const upper = code.toUpperCase();
  const city = dictionaries.cityByCode.get(upper);
  if (city) return city.name;
  const airport = dictionaries.airportByCode.get(upper);
  if (airport) return airport.name;
  return code;
}
