import dompurify from "dompurify";
import i18next_http_backend from "i18next-http-backend";
import { getAssetPath } from "../../../utils/asset-path-utils.js";
import availableLocales from "../../../generated/availableLocales.js";
const i18nTranslationNamespace = 'translation';
function i18nBackendOptions(atomicInterface) {
    return {
        loadPath: `${getAssetPath(atomicInterface.languageAssetsPath)}/{{lng}}.json?lng={{lng}}&ns={{ns}}`,
        request: async (_options, url, _payload, callback)=>{
            try {
                const [fetchUrl, searchParams] = url.split('?');
                const urlParams = new URLSearchParams(searchParams);
                const lng = urlParams.get('lng');
                const ns = urlParams.get('ns');
                if (!isI18nLocaleAvailable(lng)) throw new Error(`Unsupported locale "${lng}"`);
                if (ns !== i18nTranslationNamespace) throw new Error(`Unsupported namespace "${ns}"`);
                const response = await fetch(fetchUrl);
                if (200 !== response.status && 304 !== response.status) throw new Error(`Unsuccessful request returned status "${response.status}"`);
                callback(null, {
                    status: response.status,
                    data: await response.json()
                });
            } catch (error) {
                callback(error, {
                    status: 404,
                    data: ''
                });
            }
        }
    };
}
function init18n(atomicInterface) {
    return atomicInterface.i18n.use(i18next_http_backend).init({
        debug: 'debug' === atomicInterface.logLevel,
        lng: atomicInterface.language,
        nsSeparator: '___',
        fallbackLng: 'en',
        backend: i18nBackendOptions(atomicInterface),
        interpolation: {
            escape: (str)=>dompurify.sanitize(str)
        },
        compatibilityJSON: 'v4'
    });
}
function isI18nLocaleAvailable(locale) {
    return availableLocales.includes(locale.toLowerCase());
}
export { i18nBackendOptions, i18nTranslationNamespace, init18n };
