
const LANGUAGES = [
    "ar", "de", "en", "es", "eu",
    "fi", "fr", "he", "ja", "nl",
    "pl", "pt", "to", "tr",
    "zh_Hans", "zh_Hant",
]

let TR: { [key: string]: string } = {}
export async function init_locale(lang?: string) {
    if (!lang) return await init_locale(select_language())
    const res = await fetch(`/locale/${encodeURIComponent(lang)}.json`, { headers: { "Accept": "application/json" } })
    if (!res.ok) throw new Error("language pack download failed");
    TR = await res.json()
}

export function tr(key: string, ...args: string[]): string {
    let s = TR[key];
    if (!s) return key
    if (args.length) s = s.replace(/{(\d+)}/ig, (_m, index) => args[parseInt(index)])
    return s
}

function select_language(): string {
    const plang = (new URLSearchParams(globalThis.location.hash.substring(1))).get("lang")
    if (plang) return plang
    const navlang = navigator.language.split("-")[0] ?? "en"
    if (LANGUAGES.includes(navlang)) return navlang
    console.warn("fallback language selected");
    return "en"
}
