import { ConfigService } from "../../configService/index.mjs";
import { apiMutate } from "../useAxiosMutate.mjs";
import { getCurrentRouteInitialized, getRouteConfig } from "../../routes/routeRegistryStore.mjs";
import { initReactI18next } from "react-i18next";
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
//#region src/utilities/i18n/initializeI18n.js
/**
* @typedef {Object} TenantTranslationItem
* @property {string} label
* @property {string} value
*/
/**
* @callback TranslationLoader
* @param {string} language
* @returns {Promise<Record<string, string>>}
*/
/**
* @typedef {Object} InitializeI18nOptions
* @property {TranslationLoader} [loadTranslations]
* @property {Partial<import('i18next').InitOptions>} [i18nConfig]
* @property {string} [fallbackLanguage]
*/
let isInitialized = false;
/**
* Convert the API response into an i18next resource bundle.
* @param {TenantTranslationItem[]} languageData
* @returns {Record<string, string>}
*/
const buildTranslationMap = (languageData = []) => {
	return languageData.reduce(
		(acc, item) => {
			if (item?.label) acc[item.label] = item?.value ?? "";
			return acc;
		},
		/** @type {Record<string, string>} */
		{}
	);
};
/** @type {TranslationLoader} */
const defaultTranslationLoader = async (language) => {
	await ConfigService.waitForConfig?.();
	const routeConfig = getRouteConfig?.();
	if (!getCurrentRouteInitialized?.() || routeConfig?.isPublic && !routeConfig?.attemptSilentAuth) return {};
	const response = await apiMutate(ConfigService.tenantV1ApiUrl, `translation/language/${language}`, { method: "get" });
	return buildTranslationMap(Array.isArray(response?.data) ? response.data : []);
};
/**
* Initializes the shared i18n instance used across UDP React applications.
* Safe to call multiple times – initialization will only occur once per runtime.
* @param {InitializeI18nOptions} [options]
* @returns {import('i18next').i18n}
*/
const initializeUnityI18n = (options = {}) => {
	if (isInitialized) return i18n;
	const fallbackLanguage = options.fallbackLanguage ?? "en-US";
	const loadTranslations = options.loadTranslations ?? defaultTranslationLoader;
	/**
	* Lazy-load translations when the language changes.
	* @param {string} language
	*/
	const handleLanguageChanged = async (language) => {
		if (i18n.hasResourceBundle(language, "translation")) return;
		try {
			const bundle = await loadTranslations(language);
			i18n.addResourceBundle(language, "translation", bundle, true, true);
			i18n.changeLanguage(language);
		} catch (error) {
			console.error("Failed to load translations", error);
		}
	};
	i18n.on("languageChanged", handleLanguageChanged);
	i18n.use(LanguageDetector).use(initReactI18next).init({
		fallbackLng: fallbackLanguage,
		debug: false,
		detection: {
			order: ["queryString", "cookie"],
			cache: ["cookie"]
		},
		interpolation: { escapeValue: false },
		backend: { loadPath: "" },
		...options.i18nConfig ?? {}
	});
	isInitialized = true;
	return i18n;
};
/**
* Convenience accessor for the shared i18n instance.
* @returns {import('i18next').i18n}
*/
const getI18nInstance = () => i18n;
//#endregion
export { getI18nInstance, initializeUnityI18n };

//# sourceMappingURL=initializeI18n.mjs.map