/* assets/js/ua_i18n.js - global UI language activator */
(function(){
  'use strict';
  var cfg = window.UA_I18N || {};
  var lang = cfg.lang || document.documentElement.lang || 'ar';
  if (lang !== 'en') return;

  var exact = cfg.exact || {};
  var phrases = cfg.phrases || {};
  var phraseKeys = Object.keys(phrases).filter(Boolean).sort(function(a,b){ return b.length - a.length; });
  var arabicRe = /[\u0600-\u06FF]/;
  var wsRe = /\s+/g;
  var protectedSelector = '[data-no-i18n], [data-i18n="off"], .no-i18n, .ua-no-i18n, script, style, code, pre, textarea';
  // Do not mutate action carriers. Some pages route clicks by data-go/data-action; translation must not touch them.
  var interactiveSelector = '[data-go], [data-action], [data-bulk-action], .js-secure-modal-link, .js-page-modal-link, .row-selector, .bulk-master-checkbox';

  document.documentElement.lang = 'en';
  // Do not flip document.dir. The project layout is RTL-fixed; language changes text only.
  document.documentElement.dir = 'rtl';
  try { document.body && document.body.classList.add('ua-lang-en'); } catch(e) {}

  function norm(s){ return String(s == null ? '' : s).replace(/[\u200e\u200f\ufeff]/g,'').replace(wsRe,' ').trim(); }
  function escRx(s){ return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
  function translate(s){
    s = String(s == null ? '' : s);
    if (!arabicRe.test(s)) return s;
    if (Object.prototype.hasOwnProperty.call(exact, s)) return exact[s];
    var n = norm(s);
    if (Object.prototype.hasOwnProperty.call(exact, n)) {
      // Preserve leading/trailing whitespace around pure labels.
      return s.replace(n, exact[n]);
    }
    var out = s;
    for (var i=0;i<phraseKeys.length;i++) {
      var k = phraseKeys[i];
      if (out.indexOf(k) === -1) continue;
      var v = phrases[k];
      // Replace bare Arabic words only as tokens; multi-word phrases stay exact.
      if (/^[\u0600-\u06FF]+$/.test(k)) {
        try {
          out = out.replace(new RegExp('(^|[^\\u0600-\\u06FF])' + escRx(k) + '(?=$|[^\\u0600-\\u06FF])', 'g'), function(m,p1){ return p1 + v; });
        } catch(e) { out = out.split(k).join(v); }
      } else {
        out = out.split(k).join(v);
      }
    }
    out = out.replace(wsRe, ' ').trim();
    // Safety rule: avoid partial/broken UI such as "Subscribers قائمة".
    // Complete exact translations are applied; unknown text stays Arabic.
    if (arabicRe.test(out)) return s;
    return out;
  }

  window.UA_T = translate;

  try {
    var _alert = window.alert;
    var _confirm = window.confirm;
    var _prompt = window.prompt;
    window.alert = function(msg){ return _alert.call(window, translate(msg)); };
    window.confirm = function(msg){ return _confirm.call(window, translate(msg)); };
    window.prompt = function(msg, def){ return _prompt.call(window, translate(msg), def); };
  } catch(e) {}

  function isProtected(el){
    if (!el || el.nodeType !== 1) return false;
    try { return !!el.closest(protectedSelector); } catch(e) { return false; }
  }
  function isInteractiveCarrier(el){
    if (!el || el.nodeType !== 1) return false;
    try { return !!el.closest(interactiveSelector); } catch(e) { return false; }
  }
  function translateTextNode(node){
    if (!node || !node.nodeValue || !arabicRe.test(node.nodeValue)) return;
    if (isProtected(node.parentElement)) return;
    // Keep protected action buttons stable; their labels are cosmetic but their containers are functional.
    if (isInteractiveCarrier(node.parentElement)) return;
    var before = node.nodeValue;
    var after = translate(before);
    if (after !== before) node.nodeValue = after;
  }
  function translateAttr(el, attr){
    if (!el || !el.hasAttribute || !el.hasAttribute(attr)) return;
    var before = el.getAttribute(attr);
    if (!before || !arabicRe.test(before)) return;
    var after = translate(before);
    if (after !== before) el.setAttribute(attr, after);
  }
  function translateElement(el){
    if (!el || el.nodeType !== 1 || isProtected(el)) return;
    if (!isInteractiveCarrier(el)) ['title','aria-label','alt','placeholder','data-ua-tip','data-title','data-label'].forEach(function(a){ translateAttr(el,a); });
    var tag = (el.tagName || '').toLowerCase();
    if (tag === 'input') {
      var type = (el.getAttribute('type') || '').toLowerCase();
      if (['button','submit','reset'].indexOf(type) !== -1 && el.value && arabicRe.test(el.value)) el.value = translate(el.value);
    }
    if (tag === 'option' && el.textContent && arabicRe.test(el.textContent)) {
      el.textContent = translate(el.textContent);
    }
  }
  function walk(root){
    if (!root) return;
    if (root.nodeType === 3) { translateTextNode(root); return; }
    if (root.nodeType !== 1 && root.nodeType !== 9 && root.nodeType !== 11) return;
    if (root.nodeType === 1) translateElement(root);
    var walker;
    try {
      walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
        acceptNode: function(node){
          if (node.nodeType === 1 && isProtected(node)) return NodeFilter.FILTER_REJECT;
          return NodeFilter.FILTER_ACCEPT;
        }
      });
    } catch(e) { return; }
    var n;
    while ((n = walker.nextNode())) {
      if (n.nodeType === 3) translateTextNode(n);
      else if (n.nodeType === 1) translateElement(n);
    }
  }

  function run(){
    try { document.title = translate(document.title); } catch(e) {}
    walk(document.body || document.documentElement);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run, {once:true}); else run();

  try {
    var pending = false;
    var obs = new MutationObserver(function(list){
      if (pending) return;
      pending = true;
      requestAnimationFrame(function(){
        pending = false;
        list.forEach(function(m){
          if (m.type === 'characterData') translateTextNode(m.target);
          if (m.type === 'childList') Array.prototype.forEach.call(m.addedNodes || [], walk);
          if (m.type === 'attributes') translateElement(m.target);
        });
      });
    });
    if (document.documentElement) {
      obs.observe(document.documentElement, {subtree:true, childList:true, characterData:true, attributes:true, attributeFilter:['title','aria-label','alt','placeholder','data-ua-tip','data-title','data-label','value']});
    }
  } catch(e) {}
})();
