/**
 * Internationalization — translations, locale detection, text updates.
 */

let currentLocale = 'en';
let translations = {};
let _initialized = false;

const supportedLocales = {
    'en': 'English',
    'ru': 'Русский',
    'zh': '中文'
};

const fallbackTranslations = {
    'app.title': 'LED Grab',
    'auth.placeholder': 'Enter your API key...',
    'auth.button.login': 'Login'
};

export function getCurrentLocale() { return currentLocale; }

function getPluralForm(locale, count) {
    if (locale === 'ru') {
        const mod10 = count % 10, mod100 = count % 100;
        if (mod10 === 1 && mod100 !== 11) return 'one';
        if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'few';
        return 'many';
    }
    return count === 1 ? 'one' : 'other';
}

export function t(key: string, params: Record<string, any> = {}) {
    let text;
    if ('count' in params) {
        const form = getPluralForm(currentLocale, params.count);
        text = translations[`${key}.${form}`] || translations[key] || fallbackTranslations[key] || key;
    } else {
        text = translations[key] || fallbackTranslations[key] || key;
    }
    Object.keys(params).forEach(param => {
        text = text.replace(new RegExp(`\\{${param}\\}`, 'g'), params[param]);
    });
    return text;
}

async function loadTranslations(locale: string) {
    try {
        const response = await fetch(`/static/locales/${locale}.json`);
        if (!response.ok) {
            throw new Error(`Failed to load ${locale}.json`);
        }
        return await response.json();
    } catch (error) {
        console.error(`Error loading translations for ${locale}:`, error);
        if (locale !== 'en') {
            return await loadTranslations('en');
        }
        return {};
    }
}

function detectBrowserLocale() {
    const browserLang = navigator.language || navigator.languages?.[0] || 'en';
    const langCode = browserLang.split('-')[0];
    return supportedLocales[langCode] ? langCode : 'en';
}

export async function initLocale() {
    const savedLocale = localStorage.getItem('locale') || detectBrowserLocale();
    await setLocale(savedLocale);
}

export async function setLocale(locale: string) {
    if (!supportedLocales[locale]) {
        locale = 'en';
    }

    translations = await loadTranslations(locale);
    currentLocale = locale;
    document.documentElement.setAttribute('data-locale', locale);
    document.documentElement.setAttribute('lang', locale);
    localStorage.setItem('locale', locale);

    updateAllText();
    updateLocaleSelect();
}

export function changeLocale() {
    const select = document.getElementById('locale-select') as HTMLSelectElement;
    const newLocale = select.value;
    if (newLocale && newLocale !== currentLocale) {
        localStorage.setItem('locale', newLocale);
        setLocale(newLocale);
    }
}

function updateLocaleSelect() {
    const select = document.getElementById('locale-select') as HTMLSelectElement | null;
    if (select) {
        select.value = currentLocale;
    }
}

export function updateAllText() {
    document.querySelectorAll('[data-i18n]').forEach(el => {
        const key = el.getAttribute('data-i18n')!;
        el.textContent = t(key);
    });

    document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
        const key = el.getAttribute('data-i18n-placeholder')!;
        (el as HTMLInputElement).placeholder = t(key);
    });

    document.querySelectorAll('[data-i18n-title]').forEach(el => {
        const key = el.getAttribute('data-i18n-title')!;
        (el as HTMLElement).title = t(key);
    });

    document.querySelectorAll('[data-i18n-aria-label]').forEach(el => {
        const key = el.getAttribute('data-i18n-aria-label')!;
        el.setAttribute('aria-label', t(key));
    });

    // Notify subscribers that the language changed (skip initial load)
    if (_initialized) {
        document.dispatchEvent(new CustomEvent('languageChanged'));
    }
    _initialized = true;
}
