// Bare Radio — i18n shared module
(function () {
  'use strict';

  window.LANG = {};
  window.activeLang = localStorage.getItem('lang') || 'no';

  window.t = function (key, vars) {
    const parts = key.split('.');
    let val = window.LANG;
    for (const p of parts) { if (val == null) break; val = val[p]; }
    if (val == null || typeof val !== 'string') return key;
    if (!vars) return val;
    return val.replace(/\{(\w+)\}/g, function (_, k) { return vars[k] != null ? vars[k] : '{' + k + '}'; });
  };

  window.applyI18n = function () {
    document.querySelectorAll('[data-i18n]').forEach(function (el) {
      var key = el.dataset.i18n;
      var translated = window.t(key);
      if (translated !== key) el.textContent = translated;
    });
    document.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) {
      var key = el.dataset.i18nPlaceholder;
      var translated = window.t(key);
      if (translated !== key) el.placeholder = translated;
    });
    document.querySelectorAll('[data-i18n-title]').forEach(function (el) {
      var key = el.dataset.i18nTitle;
      var translated = window.t(key);
      if (translated !== key) el.title = translated;
    });
  };

  window.loadLang = function (code, callback) {
    fetch('/languages/' + code + '.json?v=' + Date.now())
      .then(function (r) { return r.json(); })
      .then(function (data) {
        window.LANG = data;
        window.activeLang = code;
        localStorage.setItem('lang', code);
        window.applyI18n();
        // Highlight active lang button
        document.querySelectorAll('.lang-btn').forEach(function (btn) {
          btn.classList.toggle('active', btn.dataset.lang === code);
        });
        if (typeof callback === 'function') callback();
      })
      .catch(function () { console.warn('i18n: could not load', code); });
  };

  window.initI18n = function (callback) {
    window.loadLang(window.activeLang, callback);
  };
})();
