(function(){
  const DEFAULT_LANG="tr";
  const LANG_KEY="ecupratix_lang";
  const LANGS=[
    {code:"tr",label:"🇹🇷 TR"},
    {code:"en",label:"🇬🇧 EN"},
    {code:"de",label:"🇩🇪 DE"},
    {code:"fr",label:"🇫🇷 FR"},
    {code:"pt",label:"🇵🇹 PT"},
    {code:"nl",label:"🇳🇱 NL"},
    {code:"ru",label:"🇷🇺 RU"},
    {code:"es",label:"🇪🇸 ES"}
  ];
  let LANG=localStorage.getItem(LANG_KEY)||DEFAULT_LANG;
  let DICT={};

  function t(key){ return (DICT && DICT[key]) ? DICT[key] : null; }

  function apply(){
    document.querySelectorAll("[data-i18n]").forEach(el=>{
      const key=el.getAttribute("data-i18n");
      const val=t(key);
      if(val!==null) el.textContent=val;
    });
  }

  async function load(){
    try{
      const res=await fetch(`assets/i18n/${LANG}.json?v=v62`);
      DICT=await res.json();
    }catch(e){ DICT={}; }
    apply();
  }

  function mountSelector(){
    const sel=document.getElementById("langSelect");
    if(!sel) return;
    sel.innerHTML="";
    LANGS.forEach(it=>{
      const o=document.createElement("option");
      o.value=it.code; o.textContent=it.label;
      sel.appendChild(o);
    });
    sel.value=LANG;
    sel.addEventListener("change", ()=>{
      localStorage.setItem(LANG_KEY, sel.value);
      location.href = location.pathname + location.search;
    });
  }

  document.addEventListener("DOMContentLoaded", ()=>{
    mountSelector();
    load();
  });

  window.ECUPRATIX_I18N={getLang:()=>LANG,setLang:(l)=>{localStorage.setItem(LANG_KEY,l);location.href=location.pathname+location.search;}};
})();
