/**
 * SensorPulse Enterprise UI localization (DE/EN/FR/ES/IT/PL).
 * Loads /i18n/{lang}.json, persists choice, applies [data-i18n] / [data-i18n-html].
 */
window.SpLocale = (function () {
  const STORAGE_KEY = 'sp.enterprise.lang';
  const SUPPORTED = ['de', 'en', 'fr', 'es', 'it', 'pl'];
  let current = 'de';
  let dict = {};

  function normalize(lang) {
    const code = String(lang || 'de').toLowerCase().slice(0, 2);
    return SUPPORTED.includes(code) ? code : 'de';
  }

  function t(key, fallback) {
    if (!key) return fallback || '';
    const v = dict[key];
    return v != null && v !== '' ? v : (fallback != null ? fallback : key);
  }

  function applyDom(root) {
    const scope = root || document;
    scope.querySelectorAll('[data-i18n]').forEach(el => {
      const key = el.getAttribute('data-i18n');
      if (!key) return;
      el.textContent = t(key, el.textContent);
    });
    scope.querySelectorAll('[data-i18n-html]').forEach(el => {
      const key = el.getAttribute('data-i18n-html');
      if (!key) return;
      el.innerHTML = t(key, el.innerHTML);
    });
    scope.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
      const key = el.getAttribute('data-i18n-placeholder');
      if (!key) return;
      el.setAttribute('placeholder', t(key, el.getAttribute('placeholder') || ''));
    });
    scope.querySelectorAll('[data-i18n-title]').forEach(el => {
      const key = el.getAttribute('data-i18n-title');
      if (!key) return;
      el.setAttribute('title', t(key, el.getAttribute('title') || ''));
    });
    document.documentElement.lang = current;
  }

  async function load(lang) {
    current = normalize(lang || localStorage.getItem(STORAGE_KEY) || navigator.language);
    try {
      const res = await fetch('/i18n/' + current + '.json', { cache: 'no-store' });
      dict = res.ok ? await res.json() : {};
    } catch (_) {
      dict = {};
    }
    localStorage.setItem(STORAGE_KEY, current);
    applyDom(document);
    document.dispatchEvent(new CustomEvent('sp-locale-changed', { detail: { lang: current } }));
    return current;
  }

  function getLang() { return current; }

  function setLang(lang) { return load(lang); }

  return { t, load, applyDom, getLang, setLang, SUPPORTED };
})();
