/* FutureMedia — i18n engine
   Loads languages/<lang>.json and applies to any element with [data-i18n] */

const I18N = (() => {
  let dict = {};
  let currentLang = localStorage.getItem('fm_lang') || 'tr';

  async function load(lang) {
    try {
      const res = await fetch(`languages/${lang}.json`);
      dict = await res.json();
      currentLang = lang;
      localStorage.setItem('fm_lang', lang);
      document.documentElement.lang = lang;
      document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
      apply();
    } catch (e) {
      console.error('i18n load failed', e);
    }
  }

  function t(key) {
    return dict[key] || key;
  }

  function apply() {
    document.querySelectorAll('[data-i18n]').forEach((el) => {
      const key = el.getAttribute('data-i18n');
      el.textContent = t(key);
    });
    document.querySelectorAll('[data-i18n-placeholder]').forEach((el) => {
      const key = el.getAttribute('data-i18n-placeholder');
      el.setAttribute('placeholder', t(key));
    });
  }

  function getLang() {
    return currentLang;
  }

  return { load, t, apply, getLang };
})();
