"use client";

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

import {
  adminHtmlLang,
  applyAdminUiLocale,
  hydrateAdminUiLocale,
  type AdminApiLocale,
} from "@/lib/admin-locale";
import { createAdminLanguageBackend } from "@/i18n/backend";
import zhBundle from "@/i18n/bundles/zh";
import {
  ADMIN_DEFAULT_LANGUAGE,
  ADMIN_SUPPORTED_LANGUAGES,
  normalizeAdminLanguage,
  type AdminLanguage,
} from "@/i18n/languages";
import { ADMIN_I18N_NAMESPACES } from "@/i18n/namespaces";

export {
  ADMIN_DEFAULT_LANGUAGE,
  ADMIN_SUPPORTED_LANGUAGES,
  normalizeAdminLanguage,
  type AdminLanguage,
};

function getInitialAdminLanguage(): AdminLanguage {
  // Keep SSR and first client render aligned to avoid hydration mismatch.
  // Stored locale is applied after mount in `Providers`.
  return ADMIN_DEFAULT_LANGUAGE;
}

function syncAdminLanguage(lang: AdminLanguage): void {
  if (typeof document !== "undefined") {
    document.documentElement.lang = adminHtmlLang(lang);
  }
  applyAdminUiLocale(lang as AdminApiLocale);
}

if (!i18n.isInitialized) {
  if (typeof window !== "undefined") {
    hydrateAdminUiLocale();
  }

  const initialLanguage = getInitialAdminLanguage();

  void i18n
    .use(createAdminLanguageBackend(i18n))
    .use(initReactI18next)
    .init({
      resources: {
        zh: zhBundle,
      },
      lng: initialLanguage,
      fallbackLng: ADMIN_DEFAULT_LANGUAGE,
      supportedLngs: [...ADMIN_SUPPORTED_LANGUAGES],
      defaultNS: "common",
      ns: [...ADMIN_I18N_NAMESPACES],
      load: "languageOnly",
      partialBundledLanguages: true,
      initAsync: false,
      interpolation: {
        escapeValue: false,
      },
      react: {
        useSuspense: false,
      },
    });

  syncAdminLanguage(initialLanguage);
  i18n.on("languageChanged", (lang) => {
    syncAdminLanguage(normalizeAdminLanguage(lang));
  });
}

export function ensureAdminI18nReady(): Promise<void> {
  return Promise.resolve();
}

export default i18n;
