import en from "./dictionaries/en.json";
import fr from "./dictionaries/fr.json";

export const locales = ["en", "fr"] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = "en";

const dictionaries = { en, fr } as const;
export type Dictionary = typeof en;

/**
 * Return the UI string dictionary for a locale, falling back to the default
 * locale's dictionary when the locale is unknown.
 *
 * @param locale - Requested locale (any string; unknown values fall back).
 * @returns The matching dictionary object.
 */
export function getDictionary(locale: string): Dictionary {
  return dictionaries[(locale as Locale)] ?? dictionaries[defaultLocale];
}

/**
 * Read a localized `{ en, fr }` value with graceful fallback: the requested
 * locale first, then English, then French. Returns `undefined` when the value
 * itself is missing.
 *
 * @typeParam T - The value type stored per language (defaults to `string`).
 * @param value - The localized object, or `null` / `undefined`.
 * @param locale - Requested locale.
 * @returns The best available translation, or `undefined`.
 */
export function pick<T = string>(
  value: { en?: T; fr?: T } | undefined | null,
  locale: string,
): T | undefined {
  if (!value) return undefined;
  const l = locale as Locale;
  return (value[l] ?? value.en ?? value.fr) as T | undefined;
}
