/* awxct-safe-i18n.js
 * Fallback only (Free): replace AWX placeholders with markers
 * BUT: do nothing if Pro/Plus i18n (i18next) is present.
 */
(function () {
  'use strict';

  function hasProI18n() {
    return !!(window.i18next && typeof window.i18next.t === 'function');
  }

  function markerForKey(key) {
    key = (key || '').trim();
    if (key.indexOf('meta.') === 0 || key.indexOf('aliases.') === 0) {
      return '[AWXCT: Extension required]';
    }
    return '[AWXCT: Extension required]';
  }

  function replaceInTextNodes(root) {
    var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
    var nodes = [];
    while (walker.nextNode()) nodes.push(walker.currentNode);

    // NBSP safe + &nbsp; safe:
    var ws = '(?:\\s|\\u00A0|&nbsp;)*';
    // {{ "key" | awxct }} or {{ 'key' | awxct }}
    var re = new RegExp(
      '\\{\\{' + ws + '([\'"])([^\'"]+)\\1' + ws + '\\|' + ws + 'awxct' + ws + '\\}\\}',
      'gi'
    );

    nodes.forEach(function (n) {
      var v = n.nodeValue;
      if (!v || v.indexOf('{{') === -1) return;

      var changed = false;
      var out = v.replace(re, function (_m, _q, key) {
        changed = true;
        return markerForKey(key);
      });

      if (changed) n.nodeValue = out;
    });
  }

  function runFallback() {
    // If Pro i18n exists, never touch anything.
    if (hasProI18n()) return;

    // Only run if there are placeholders at all.
    if (!document.body || document.body.innerText.indexOf('{{') === -1) return;

    replaceInTextNodes(document.body);
  }

  // IMPORTANT:
  // Run late (after DOMContentLoaded) so Pro has time to load i18next.
  // If Pro is active, i18next will exist and we bail out.
  document.addEventListener('DOMContentLoaded', function () {
    // small delay to be extra-safe with deferred scripts
    setTimeout(runFallback, 50);
  });
})();
