// SOCIOS dynamic URL bridge - FIXED VERSION
// Corrección: NO detectar por texto visible (ej. "INSTALAR EL CRM") porque
// eso intercepta respuestas rápidas dentro de WhatsApp y abre socioscrm.site.
// Ahora solo abre URLs cuando el botón/enlace tenga atributo explícito:
// data-url-action="open_install_url" o data-url-key="install_url".
(function () {
  'use strict';

  const ACTION_MAP = {
    open_login_panel_url: 'open_login_panel_url',
    open_free_account_url: 'open_free_account_url',
    open_recover_access_url: 'open_recover_access_url',
    open_client_panel_url: 'open_client_panel_url',
    open_checkout_url: 'open_checkout_url',
    open_install_url: 'open_install_url',
    open_uninstall_url: 'open_uninstall_url',
    open_support_whatsapp: 'open_support_whatsapp',

    login_panel_url: 'open_login_panel_url',
    free_account_url: 'open_free_account_url',
    recover_access_url: 'open_recover_access_url',
    client_panel_url: 'open_client_panel_url',
    checkout_url: 'open_checkout_url',
    install_url: 'open_install_url',
    uninstall_url: 'open_uninstall_url',
    support_whatsapp: 'open_support_whatsapp'
  };

  function norm(value) {
    return (value || '').toString().trim().toLowerCase();
  }

  function isTypingArea(target) {
    let node = target;
    for (let i = 0; node && i < 6; i++, node = node.parentElement) {
      const tag = (node.tagName || '').toLowerCase();
      const role = norm(node.getAttribute && node.getAttribute('role'));
      if (tag === 'textarea' || tag === 'input' || role === 'textbox') return true;
      if (node.isContentEditable) return true;
    }
    return false;
  }

  function findExplicitAction(target) {
    if (!target || isTypingArea(target)) return null;

    let node = target;
    for (let depth = 0; node && depth < 8; depth++, node = node.parentElement) {
      if (node === document.body || node === document.documentElement) break;

      const action = norm(node.getAttribute && node.getAttribute('data-url-action'));
      const key = norm(node.getAttribute && node.getAttribute('data-url-key'));
      const value = action || key;

      if (value && ACTION_MAP[value]) return ACTION_MAP[value];
    }
    return null;
  }

  document.addEventListener('click', function (event) {
    const message = findExplicitAction(event.target);
    if (!message) return;

    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();

    try {
      chrome.runtime.sendMessage({ message });
    } catch (error) {
      console.warn('[SOCIOS] No se pudo enviar acción URL:', error);
    }
  }, true);
})();
