window.__i18n = {};

// Cache translations for 1 hour
const I18N_CACHE_KEY = 'i18n';
const I18N_CACHE_TIME = 60 * 60 * 1000; // 1 hour

async function loadTranslations() {
    try {
        const cached = JSON.parse(localStorage.getItem(I18N_CACHE_KEY) || '{}');

        // Use cached translations if they are still valid
        if (
            cached.timestamp &&
            cached.data &&
            (Date.now() - cached.timestamp) < I18N_CACHE_TIME
        ) {
            window.__i18n = cached.data;
            return;
        }

        // Otherwise fetch fresh translations
        const response = await fetch('/api/v1/frontend/locale/');

        if (!response.ok) {
            console.error(`HTTP ${response.status}`);
            return;
        }

        const data = await response.json();

        window.__i18n = data;

        // Save to localStorage with timestamp
        localStorage.setItem(I18N_CACHE_KEY, JSON.stringify({
            timestamp: Date.now(),
            data: data
        }));
    } catch (err) {
        console.error('Failed to load translations:', err);

        // If the fetch failed, try to use any cached translations,
        // even if they are older than 24 hours.
        const cached = JSON.parse(localStorage.getItem(I18N_CACHE_KEY) || '{}');
        if (cached.data) {
            window.__i18n = cached.data;
        }
    }
}

window.i18nReady = loadTranslations();

function __(key) {
    return window.__i18n[key] ?? key;
}