const langs = [
    "en",
    "es",
    "ja",
    "fr",
    "it",
    "de",
]

function t(key, locale) {
    return key
        .split(".")
        .reduce((obj, part) => obj && obj[part], locale)
}

window.addEventListener("load", async () => {
    let lang = "en";
    let savedLang = localStorage.getItem("lang");

    if (savedLang) {
        lang = savedLang;
    } else {
        let currentLang = navigator.language.split("-")[0];

        if (langs.includes(currentLang)) {
            localStorage.setItem("lang", currentLang);
            lang = currentLang;
        }
    }

    const locale = await fetch(`/locales/${lang}.json`).then(r => r.json());

    document.querySelectorAll("[data-i18n]").forEach(e => {
        e.innerHTML = t(e.dataset.i18n, locale)
    });
})
