let currentLang = localStorage.getItem('keta_lang') || (navigator.language.startsWith('en') ? 'en' : 'fr');
let translations = {};

export async function initI18n(lang = currentLang) {
  currentLang = lang;
  localStorage.setItem('keta_lang', lang);

  try {
    const response = await fetch(`./locales/${lang}.json`);
    translations = await response.json();
    translatePageDOM();
    document.documentElement.lang = lang;
  } catch (error) {
    console.error(`Erreur de chargement de la langue ${lang}:`, error);
  }
}

export function translatePageDOM() {
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const key = el.getAttribute('data-i18n');
    const text = getNestedTranslation(key);
    if (text) el.textContent = text;
  });

  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    const key = el.getAttribute('data-i18n-placeholder');
    const text = getNestedTranslation(key);
    if (text) el.placeholder = text;
  });
}

export function t(key, params = {}) {
  let val = getNestedTranslation(key) || key;
  Object.keys(params).forEach(p => {
    val = val.replace(`{${p}}`, params[p]);
  });
  return val;
}

function getNestedTranslation(key) {
  return key.split('.').reduce((obj, i) => (obj ? obj[i] : null), translations);
}

export function getCurrentLang() {
  return currentLang;
}