/**
 * Локализация админ-панели (NFR-016). Поддержка русского и английского.
 * Использование: window.__t('key') или data-i18n="key" на элементах.
 */
(function() {
    const STORAGE_KEY = 'cascad360_admin_locale';
    const DEFAULT_LOCALE = 'ru';
    const SUPPORTED = ['ru', 'en'];

    let currentLocale = localStorage.getItem(STORAGE_KEY) || DEFAULT_LOCALE;
    if (!SUPPORTED.includes(currentLocale)) currentLocale = DEFAULT_LOCALE;

    let translations = {};

    function getLocale() {
        return currentLocale;
    }

    function setLocale(locale) {
        if (!SUPPORTED.includes(locale)) return false;
        currentLocale = locale;
        localStorage.setItem(STORAGE_KEY, locale);
        document.documentElement.lang = locale === 'en' ? 'en' : 'ru';
        return true;
    }

    async function loadLocale(locale) {
        const path = '/static/lang/' + locale + '.json';
        try {
            const r = await fetch(path);
            if (!r.ok) return false;
            translations[locale] = await r.json();
            return true;
        } catch (e) {
            return false;
        }
    }

    function t(key) {
        const dict = translations[currentLocale] || translations[DEFAULT_LOCALE];
        if (!dict) return key;
        return dict[key] != null ? dict[key] : key;
    }

    function applyToPage() {
        document.querySelectorAll('[data-i18n]').forEach(function(el) {
            const key = el.getAttribute('data-i18n');
            const value = t(key);
            if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
                if (el.placeholder !== undefined) el.placeholder = value;
            } else {
                el.textContent = value;
            }
        });
        document.querySelectorAll('[data-i18n-attr]').forEach(function(el) {
            const spec = el.getAttribute('data-i18n-attr');
            if (!spec) return;
            const idx = spec.indexOf(':');
            if (idx === -1) return;
            const attr = spec.slice(0, idx).trim();
            const key = spec.slice(idx + 1).trim();
            if (attr && key) el.setAttribute(attr, t(key));
        });
        document.title = t('app.title') + ' - ' + t('app.name');
    }

    window.__i18n = {
        getLocale: getLocale,
        setLocale: setLocale,
        supported: SUPPORTED,
        load: loadLocale,
        t: t,
        apply: applyToPage
    };
    window.__t = t;

    document.addEventListener('DOMContentLoaded', function() {
        loadLocale(currentLocale).then(function(ok) {
            if (ok) loadLocale(DEFAULT_LOCALE);
            applyToPage();
        });
    });
})();
