export const translations = $state({
    values: {}
})

export async function loadTranslation(lang){
    var url = `${location.protocol}//${location.host.replace('5173','8080')}/api/translations/${lang}`;
    translations.values = await fetch(url).then(resp => resp.json());
}

export function t(key,args = {}){
    if (key === undefined) return "";
    if (key instanceof Response) key = 'status.'+key.status;
    let set = translations.values;
    let keys = key.split('.');
    for (let token of keys){
        if (!set[token]){
            console.warn('Missing translation for '+key);
            return keys[keys.length-1].replaceAll('_',' ');
        }
        set = set[token];
    }
    for (var key of Object.keys(args)) set = set.replace(`{${key}}`,args[key]);
    return set;
}