import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { apiMutate } from '../useAxiosMutate';
import { ConfigService } from '../../configService';
import { getRouteConfig, getCurrentRouteInitialized } from '../../routes/routeRegistryStore';
/**
 * @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) => {
        var _a;
        if (item === null || item === void 0 ? void 0 : item.label) {
            acc[item.label] = (_a = item === null || item === void 0 ? void 0 : item.value) !== null && _a !== void 0 ? _a : '';
        }
        return acc;
    }, /** @type {Record<string, string>} */ {});
};
/** @type {TranslationLoader} */
const defaultTranslationLoader = async (language) => {
    var _a;
    await ((_a = ConfigService.waitForConfig) === null || _a === void 0 ? void 0 : _a.call(ConfigService));
    const routeConfig = getRouteConfig === null || getRouteConfig === void 0 ? void 0 : getRouteConfig();
    const routeInitialized = getCurrentRouteInitialized === null || getCurrentRouteInitialized === void 0 ? void 0 : getCurrentRouteInitialized();
    const shouldSkip = !routeInitialized ||
        ((routeConfig === null || routeConfig === void 0 ? void 0 : routeConfig.isPublic) && !(routeConfig === null || routeConfig === void 0 ? void 0 : routeConfig.attemptSilentAuth));
    if (shouldSkip) {
        return {};
    }
    const response = await apiMutate(ConfigService.tenantV1ApiUrl, `translation/language/${language}`, { method: 'get' });
    const languageData = Array.isArray(response === null || response === void 0 ? void 0 : response.data) ? response.data : [];
    return buildTranslationMap(languageData);
};
/**
 * 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}
 */
export const initializeUnityI18n = (options = {}) => {
    var _a, _b, _c;
    if (isInitialized) {
        return i18n;
    }
    const fallbackLanguage = (_a = options.fallbackLanguage) !== null && _a !== void 0 ? _a : 'en-US';
    const loadTranslations = (_b = options.loadTranslations) !== null && _b !== void 0 ? _b : 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) {
            // eslint-disable-next-line no-console
            console.error('Failed to load translations', error);
        }
    };
    i18n.on('languageChanged', handleLanguageChanged);
    i18n
        .use(LanguageDetector)
        .use(initReactI18next)
        .init(Object.assign({ fallbackLng: fallbackLanguage, debug: false, detection: {
            order: ['queryString', 'cookie'],
            cache: ['cookie']
        }, interpolation: {
            escapeValue: false
        }, backend: {
            loadPath: ''
        } }, ((_c = options.i18nConfig) !== null && _c !== void 0 ? _c : {})));
    isInitialized = true;
    return i18n;
};
/**
 * Convenience accessor for the shared i18n instance.
 * @returns {import('i18next').i18n}
 */
export const getI18nInstance = () => i18n;
//# sourceMappingURL=initializeI18n.js.map