/**
 * Language Switcher Module
 *
 * Provides runtime language switching for multi-language tasks.
 * Expects a global TRANSLATIONS object and optionally a TRIALS object
 * keyed by language code (e.g. { en: [...], de: [...], fr: [...] }).
 *
 * Usage:
 *   - Include this script after TRANSLATIONS is defined.
 *   - Add data-i18n="key" attributes to elements whose text should switch.
 *   - Add data-i18n-html="key" for elements that contain HTML markup.
 *   - Call t('key') in JS to get the translated string for current LANG.
 *   - Call tpl('key', { var: value }) for template strings with {var} placeholders.
 */

// Current language — default to browser language or 'en'.
// NOTE: this script may load before the inline <script> that defines
// TRANSLATIONS, so we cannot validate against TRANSLATIONS here. We pick a
// best-guess; initLangSwitcher() re-validates once TRANSLATIONS is in scope.
var LANG = (function() {
  var stored = null;
  try { stored = localStorage.getItem('task_lang'); } catch(e) {}
  if (stored) return stored;
  var browserLang = (navigator.language || '').slice(0, 2).toLowerCase();
  return browserLang || 'en';
})();

/**
 * Look up a translation key for the current LANG.
 * Falls back to English, then returns the key itself.
 */
function t(key) {
  var entry = TRANSLATIONS[key];
  if (!entry) return key;
  return entry[LANG] || entry['en'] || key;
}

/**
 * Template translation: replaces {placeholder} tokens with values.
 * Example: tpl('trial_of', { current: 3, total: 12 })
 */
function tpl(key, vars) {
  var str = t(key);
  if (vars) {
    Object.keys(vars).forEach(function(k) {
      str = str.replace(new RegExp('\\{' + k + '\\}', 'g'), vars[k]);
    });
  }
  return str;
}

/**
 * Update all elements with data-i18n or data-i18n-html attributes.
 */
function updateI18nElements() {
  document.querySelectorAll('[data-i18n]').forEach(function(el) {
    var key = el.getAttribute('data-i18n');
    el.textContent = t(key);
  });
  document.querySelectorAll('[data-i18n-html]').forEach(function(el) {
    var key = el.getAttribute('data-i18n-html');
    el.innerHTML = t(key);
  });
}

/**
 * Set language and update all translated elements.
 */
function setLang(lang) {
  LANG = lang;
  try { localStorage.setItem('task_lang', lang); } catch(e) {}
  updateI18nElements();
  // Update the selector if it exists
  var sel = document.getElementById('lang-select');
  if (sel) sel.value = lang;
  // Fire custom event so task scripts can react
  document.dispatchEvent(new CustomEvent('langchange', { detail: { lang: lang } }));
}

/**
 * Render the language selector into the element with id="lang-switcher-container".
 * Call this after DOM is ready.
 */
function initLangSwitcher(langs) {
  langs = langs || [
    { code: 'en', label: 'English' },
    { code: 'de', label: 'Deutsch' },
    { code: 'fr', label: 'Français' },
  ];

  // Re-validate LANG now that TRANSLATIONS is in scope: if the persisted /
  // browser-detected value isn't a supported language, fall back to 'en'.
  if (typeof TRANSLATIONS === 'object' && TRANSLATIONS) {
    var firstKey = Object.keys(TRANSLATIONS)[0];
    if (firstKey && !TRANSLATIONS[firstKey][LANG]) LANG = 'en';
  }

  var container = document.getElementById('lang-switcher-container');
  if (!container) return;

  var select = document.createElement('select');
  select.id = 'lang-select';
  select.className = 'lang-select';
  langs.forEach(function(l) {
    var opt = document.createElement('option');
    opt.value = l.code;
    opt.textContent = l.label;
    if (l.code === LANG) opt.selected = true;
    select.appendChild(opt);
  });

  select.addEventListener('change', function() {
    setLang(select.value);
  });

  container.appendChild(select);

  // Initial update
  updateI18nElements();
}

/**
 * Resolve a stimulus filename to its actual URL, accounting for files
 * that have language-specific variants (instruction audio, localized
 * images, etc.). Generators set window.PER_LANG_MEDIA to the list of
 * filenames stored under stimuli/<lang>/. Anything else stays in
 * stimuli/.
 */
function mediaUrl(file) {
  var perLang = (typeof window !== 'undefined' && window.PER_LANG_MEDIA) || [];
  if (perLang.indexOf(file) >= 0) {
    return 'stimuli/' + LANG + '/' + file;
  }
  return 'stimuli/' + file;
}
