// UI localization (spec Task 4): all text lives in /locales/<lang>.json.
// Static DOM nodes are tagged with data-i18n / data-i18n-ph; dynamic strings
// go through t(key, vars).

const LANGS = ['en', 'ru', 'es', 'zh'];
let dict = {};
let lang = localStorage.getItem('tron.lang')
  || (navigator.language || 'en').slice(0, 2).toLowerCase();
if (!LANGS.includes(lang)) lang = 'en';

export const languages = LANGS;
export function currentLang() { return lang; }

export function t(key, vars) {
  let s = dict[key] ?? key;
  if (vars) for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, v);
  return s;
}

function applyStatic() {
  document.documentElement.lang = lang;
  for (const el of document.querySelectorAll('[data-i18n]')) el.textContent = t(el.dataset.i18n);
  for (const el of document.querySelectorAll('[data-i18n-ph]')) el.placeholder = t(el.dataset.i18nPh);
}

export async function loadLang(next) {
  if (!LANGS.includes(next)) next = 'en';
  const res = await fetch(new URL(`./locales/${next}.json`, import.meta.url));
  dict = await res.json();
  lang = next;
  localStorage.setItem('tron.lang', next);
  applyStatic();
}

export async function initI18n() {
  try { await loadLang(lang); } catch { /* untranslated keys still render */ }
}
