// DeepBlocker visible UI text — English only.
// The multi-language selector was removed in 1.0.7. This helper keeps the
// existing data-db-i18n / deepT API so every page renders unchanged, but it
// always resolves to the English catalog with a plain key fallback.

const catalogURL = new URL('../assets/deepblocker-ui-i18n.json', import.meta.url);

let catalogPromise;

const loadCatalog = async ( ) => {
    if ( catalogPromise === undefined ) {
        catalogPromise = fetch(catalogURL).then(response => {
            if ( response.ok !== true ) {
                throw new Error(`Unable to load DeepBlocker UI text: ${response.status}`);
            }
            return response.json();
        });
    }
    return catalogPromise;
};

const format = (text, replacements = {}) => {
    let out = text;
    for ( const [ key, value ] of Object.entries(replacements) ) {
        out = out.replaceAll(`{{${key}}}`, String(value));
    }
    return out;
};

const translateFromCatalog = (catalog, key, replacements = {}) => {
    const strings = catalog && catalog.strings || {};
    const en = strings.en || {};
    const value = en[key] !== undefined ? en[key] : key;
    return format(value, replacements);
};

const applyText = (node, text) => {
    if ( node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement ) {
        node.value = text;
        return;
    }
    node.textContent = text;
};

const applyDeepI18nWithCatalog = (root, catalog) => {
    const scope = root || document;
    document.documentElement.lang = 'en';
    document.documentElement.dir = 'ltr';
    for ( const node of scope.querySelectorAll('[data-db-i18n]') ) {
        applyText(node, translateFromCatalog(catalog, node.dataset.dbI18n));
    }
    for ( const node of scope.querySelectorAll('[data-db-i18n-title]') ) {
        node.title = translateFromCatalog(catalog, node.dataset.dbI18nTitle);
    }
    for ( const node of scope.querySelectorAll('[data-db-i18n-placeholder]') ) {
        node.placeholder = translateFromCatalog(catalog, node.dataset.dbI18nPlaceholder);
    }
    for ( const node of scope.querySelectorAll('[data-db-i18n-aria-label]') ) {
        node.setAttribute('aria-label',
            translateFromCatalog(catalog, node.dataset.dbI18nAriaLabel)
        );
    }
};

const applyDeepI18n = async (root = document) => {
    const catalog = await loadCatalog();
    applyDeepI18nWithCatalog(root, catalog);
    return 'en';
};

const deepT = async (key, replacements = {}) => {
    const catalog = await loadCatalog();
    return translateFromCatalog(catalog, key, replacements);
};

// Kept for API compatibility; language is always English now.
const deepTFromLanguage = async (_language, key, replacements = {}) => deepT(key, replacements);

const ready = document.readyState === 'loading'
    ? new Promise(resolve => document.addEventListener('DOMContentLoaded', resolve, { once: true }))
    : Promise.resolve();

ready.then(( ) => {
    if ( document.querySelector('[data-db-i18n],[data-db-i18n-title],[data-db-i18n-placeholder],[data-db-i18n-aria-label]') === null ) {
        return;
    }
    applyDeepI18n().catch(ex => {
        console.warn('DeepBlocker UI text failed to apply', ex);
    });
});

export {
    applyDeepI18n,
    deepT,
    deepTFromLanguage,
};
