const langs = [
    "en", // [x] English
    "es", // [ ] Spanish
    "ja", // [ ] Japanese
    "fr", // [ ] French
    "it", // [ ] Italian
    "de", // [ ] German
]

async function updateGuide(guide, lang) {
    let buttonsRes = await fetch(`/md/${lang}/buttons.html`);

    if (buttonsRes.ok) {
        let buttonsHTML = await buttonsRes.text();

        document.getElementById("guide-buttons").innerHTML = buttonsHTML;
    }

    let guidePath = `/md/${lang}/${guide}.md`;

    let guideRes = await fetch(guidePath);

    if (!guideRes.ok) throw new Error(`Guide "${guide}" was not found`);

    const guideButton = document.getElementById(guide);
    if (guideButton) guideButton.classList.add("active");

    let text = await guideRes.text();
    const html = marked.parse(text);
    document.getElementById("guide-contents").innerHTML = html;
}

async function updateLang(newLang) {
    localStorage.setItem("lang", newLang);

    const params = new URLSearchParams(window.location.search);
    const guideParam = params.get("guide");

    let guide = "install-wiiu";
    if (guideParam) {
        guide = guideParam;
    }

    await updateGuide(guide, newLang);
}

window.onload = (async () => {
    const params = new URLSearchParams(window.location.search);
    const guideParam = params.get("guide");

    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;
        }
    }

    let guide = "install-wiiu";
    if (guideParam) {
        guide = guideParam;
    }

    await updateGuide(guide, lang)
})
