// VibePost Ai brand override — persistent popup + sidepanel patcher
(function(){
  var IN_EXT = location.protocol === 'chrome-extension:';
  var SUPPORT_URL = 'https://wa.me/8801927341627';
  var BRAND_TEXT = 'VibePost Ai';
  var FOOTER_TEXT = 'Developed by VibePost Ai';
  var LICENSE_PLACEHOLDER = 'VibePost-XXXX-XXXX-XXXX';
  var LOGO_PATH = 'assets/icon48.png';
  var popupObserver = null;
  var observedPopupRoot = null;

  function getRuntimeAsset(path) {
    try {
      if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL) {
        return chrome.runtime.getURL(path);
      }
    } catch (e) {}
    return path;
  }

  function cleanText(value) {
    if (!value) return value;
    return value
      .replace(/Developed by\s*VibeX\s*Academy/gi, FOOTER_TEXT)
      .replace(/Developed by\s*EliteSub/gi, FOOTER_TEXT)
      .replace(/Developed by\s*AI\s*GURU/gi, FOOTER_TEXT)
      .replace(/VibeX\s*Academy/gi, BRAND_TEXT)
      .replace(/\bEliteSub\b/gi, BRAND_TEXT)
      .replace(/\bAI\s*GURU\b/gi, BRAND_TEXT)
      .replace(/\bAIGURU\b/gi, BRAND_TEXT)
      .replace(/\bVIBEX\b/gi, BRAND_TEXT)
      .replace(/\bVibeX\b/gi, BRAND_TEXT)
      .replace(/(EliteSub|AIGURU|AI-GURU|VIBEX)-XXXX-XXXX-XXXX/gi, LICENSE_PLACEHOLDER);
  }

  function setText(el, value) {
    if (el && el.textContent !== value) el.textContent = value;
  }

  function patchTextNodes(root) {
    if (!root || !document.createTreeWalker) return;
    var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
    var node;
    while ((node = walker.nextNode())) {
      var current = node.nodeValue || '';
      var next = cleanText(current);
      if (next !== current) node.nodeValue = next;
    }
  }

  function patchInputs(root) {
    if (!root || !root.querySelectorAll) return;
    root.querySelectorAll('input').forEach(function(el){
      var placeholder = el.getAttribute('placeholder') || '';
      if (/VIBEX|VibeX|AI-?GURU|AIGURU|EliteSub|XXXX-XXXX-XXXX/i.test(placeholder)) {
        el.setAttribute('placeholder', LICENSE_PLACEHOLDER);
      }
      if (/^(VIBEX|AI-?GURU|AIGURU|EliteSub)/i.test(el.value || '')) {
        el.value = (el.value || '').replace(/^(VIBEX|AI-?GURU|AIGURU|EliteSub)/i, 'VibePost');
      }
    });
  }

  function patchLinks(root) {
    if (!root || !root.querySelectorAll) return;
    root.querySelectorAll('a[href*="wa.me/"], .ql-support-link, .sp-support-link').forEach(function(el){
      el.setAttribute('href', SUPPORT_URL);
      el.setAttribute('target', '_blank');
      el.setAttribute('rel', 'noopener noreferrer');
      el.style.setProperty('pointer-events', 'auto', 'important');
      el.style.setProperty('cursor', 'pointer', 'important');
    });
  }

  function patchLogos(root) {
    if (!root || !root.querySelectorAll) return;
    var logoUrl = getRuntimeAsset(LOGO_PATH);
    root.querySelectorAll('.ql-brand-logo, .ql-title-logo, .sp-brand-logo, img[src*="logo-master-lovable"], img[src*="gringow-logo"]').forEach(function(el){
      if (el.getAttribute('src') !== logoUrl) el.setAttribute('src', logoUrl);
      if (!el.getAttribute('alt') || /vibex|elitesub|aiguru/i.test(el.getAttribute('alt'))) {
        el.setAttribute('alt', BRAND_TEXT);
      }
    });
  }

  function patchBrand(root) {
    if (!root || !root.querySelectorAll) return;

    root.querySelectorAll('.sp-brand-text, .ql-brand-text, .ql-title').forEach(function(el){
      if (/VibeX|VIBEX|EliteSub|AI\s*GURU|AIGURU/i.test(el.textContent || '')) {
        setText(el, BRAND_TEXT);
      }
    });

    root.querySelectorAll('.ql-gate-title').forEach(function(el){
      var text = el.textContent || '';
      if (/VIBEX|VibeX|AI-?GURU|AIGURU|EliteSub/i.test(text)) {
        setText(el, cleanText(text));
      }
    });

    function applyBadge(el) {
      var span = el.querySelector('span');
      if (span) {
        setText(span, 'VibePost Ai Native Active');
      } else {
        Array.prototype.forEach.call(el.childNodes, function(node) {
          if (node.nodeType === 3 && /VibeX\s*Academy|VibePost\s*Ai/i.test(node.nodeValue)) {
            var next = node.nodeValue.replace(/VibeX\s*Academy|VibePost\s*Ai/gi, 'VibePost Ai Native Active');
            if (node.nodeValue !== next) node.nodeValue = next;
          }
        });
      }
    }

    root.querySelectorAll('#ql-native-badge, .ql-native-badge, [id*="native-badge"], [class*="native-badge"]').forEach(applyBadge);
    try {
      document.querySelectorAll('#ql-native-badge, .ql-native-badge, [id*="native-badge"], [class*="native-badge"]').forEach(applyBadge);
    } catch(e) {}

    root.querySelectorAll('.sp-footer-badge, .ql-footer-version, [data-i18n="footer.brand"]').forEach(function(el){
      setText(el, FOOTER_TEXT);
      el.removeAttribute('href');
      el.removeAttribute('target');
      el.removeAttribute('rel');
      el.style.cursor = 'default';
      el.style.textDecoration = 'none';
      el.style.pointerEvents = 'none';
    });
  }

  function patch(root) {
    try {
      patchBrand(root);
      patchTextNodes(root);
      patchInputs(root);
      patchLinks(root);
      patchLogos(root);
    } catch (e) {}
  }

  function schedulePatch(root) {
    if (!root) return;
    if (root.__aiguruPatchQueued) return;
    root.__aiguruPatchQueued = true;
    requestAnimationFrame(function(){
      root.__aiguruPatchQueued = false;
      patch(root);
    });
  }

  function observeScoped(root) {
    if (!root) return;
    if (observedPopupRoot === root && popupObserver) {
      schedulePatch(root);
      return;
    }
    if (popupObserver) { try { popupObserver.disconnect(); } catch (e) {} }
    observedPopupRoot = root;
    schedulePatch(root);
    popupObserver = new MutationObserver(function(){ schedulePatch(root); });
    popupObserver.observe(root, {
      childList: true, subtree: true, characterData: true,
      attributes: true, attributeFilter: ['href', 'src', 'placeholder', 'value']
    });
  }

  function initExtension() {
    var root = document.body || document.documentElement;
    if (!root) return;
    observeScoped(root);
  }

  function initPage() {
    function getPopup() { return document.getElementById('ql-floating'); }
    function scan() {
      var popup = getPopup();
      if (popup) observeScoped(popup);
      else if (popupObserver) {
        try { popupObserver.disconnect(); } catch (e) {}
        popupObserver = null; observedPopupRoot = null;
      }
    }
    function startWatch() {
      if (!document.body) { setTimeout(startWatch, 50); return; }
      scan();
      var scheduled = false;
      var bodyObserver = new MutationObserver(function(){
        if (scheduled) return;
        scheduled = true;
        requestAnimationFrame(function(){ scheduled = false; scan(); });
      });
      bodyObserver.observe(document.body, { childList: true, subtree: true });
    }
    startWatch();
  }

  function init() { if (IN_EXT) initExtension(); else initPage(); }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, { once: true });
  else init();
})();
