import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";

// Locale bundles live inside this app (src/locales) so they're part of the
// package and survive `turbo prune` in the Docker build.
import en from "../locales/en/translation.json";
import am from "../locales/am/translation.json";
import af from "../locales/af/translation.json";
import fr from "../locales/fr/translation.json";
import or from "../locales/or/translation.json";
import sm from "../locales/sm/translation.json";
import tg from "../locales/tg/translation.json";

export const SUPPORTED_LANGUAGES = ["en", "am", "af", "fr", "or", "sm", "tg"] as const;

/**
 * i18next singleton for the vendored IAM UI (shared/super-admin/
 * user-management), imported as `@/i18n`. Loads the shared translation bundles
 * and enables language detection/persistence so the header language switcher
 * (i18n.changeLanguage) works and survives reloads.
 */
if (!i18n.isInitialized) {
  void i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
      resources: {
        en: { translation: en },
        am: { translation: am },
        af: { translation: af },
        fr: { translation: fr },
        or: { translation: or },
        sm: { translation: sm },
        tg: { translation: tg },
      },
      fallbackLng: "en",
      supportedLngs: SUPPORTED_LANGUAGES as unknown as string[],
      interpolation: { escapeValue: false },
      returnNull: false,
      detection: {
        order: ["localStorage", "navigator", "htmlTag"],
        caches: ["localStorage"],
      },
    });
}

export default i18n;
