// Saas/content/bulkLeaver.js
// Automatización para abandonar grupos en lote desde la página de joins de Facebook

(async function() {
  if (window.fbBulkLeaverInstance) return;
  window.fbBulkLeaverInstance = true;

  const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

  function simulateClick(element) {
    if (!element) return;
    element.focus();
    element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window, buttons: 1 }));
    element.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window, buttons: 1 }));
    element.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
    if (typeof element.click === 'function') {
      element.click();
    }
  }

  function findJoinedGroupsHeader() {
    const elements = Array.from(document.querySelectorAll('h1, h2, h3, h4, span, div'));
    const targets = ["todos los grupos a los que te uniste", "groups you've joined", "todos los grupos", "todos tus grupos", "all groups", "your groups"];
    
    return elements.find(el => {
      if (el.offsetWidth === 0 && el.offsetHeight === 0) return false;
      const text = (el.innerText || el.textContent || "").trim().toLowerCase();
      return targets.some(t => text === t || text.includes(t));
    });
  }

  function findFirstGroupCardOptionsButton(minY) {
    const elements = Array.from(document.querySelectorAll('div[role="button"], button, a[role="button"], [tabindex="0"]'));
    const excludeTexts = ["notificaciones", "notifications", "mensajes", "messenger", "cuenta", "account", "buscar", "search", "crear", "create", "menú", "menu", "inicio", "home", "perfil", "profile", "guardados", "saved"];
    
    for (const el of elements) {
      if (el.offsetWidth === 0 && el.offsetHeight === 0) continue;
      
      const rect = el.getBoundingClientRect();
      
      if (rect.top < minY) continue;
      if (rect.left < 280) continue;
      
      const text = (el.innerText || el.textContent || "").trim().toLowerCase();
      const ariaLabel = (el.getAttribute("aria-label") || "").trim().toLowerCase();
      const title = (el.getAttribute("title") || "").trim().toLowerCase();
      
      if (text.includes("ver grupo") || text.includes("view group") || text.includes("visitar") || text.includes("visit")) {
        continue;
      }
      
      if (excludeTexts.some(ex => text.includes(ex) || ariaLabel.includes(ex) || title.includes(ex))) {
        continue;
      }
      
      const isJoinOrInvite = (t) => t.includes("unirse") || t === "join" || t.includes("invitar") || t.includes("invite") || t.includes("join group") || t.includes("unirse al grupo") || t.includes("unirme");
      if (isJoinOrInvite(text) || isJoinOrInvite(ariaLabel) || isJoinOrInvite(title)) {
        continue;
      }
      
      const isOptionsLabel = ["opciones", "options", "más", "more", "configuración", "settings", "miembro", "joined"].some(t => 
        text.includes(t) || ariaLabel.includes(t) || title.includes(t)
      );
      
      const isSmallSquare = rect.width > 20 && rect.width < 80 && rect.height > 20 && rect.height < 80;
      
      if (isOptionsLabel || isSmallSquare) {
        return el;
      }
    }
    return null;
  }

  function findLeaveMenuOption() {
    const elements = Array.from(document.querySelectorAll('span, div, [role="menuitem"], a'));
    const targets = ["abandonar grupo", "leave group", "salir del grupo", "abandonar", "leave"];
    
    let matched = elements.find(el => {
      if (el.offsetWidth === 0 && el.offsetHeight === 0) return false;
      const text = (el.innerText || el.textContent || "").trim().toLowerCase();
      const ariaLabel = (el.getAttribute("aria-label") || "").trim().toLowerCase();
      return targets.some(t => text === t || ariaLabel === t);
    });

    if (matched) return matched;

    matched = elements.find(el => {
      if (el.offsetWidth === 0 && el.offsetHeight === 0) return false;
      if (el.tagName !== 'SPAN' && el.tagName !== 'A' && el.children.length > 2) return false;
      const text = (el.innerText || el.textContent || "").trim().toLowerCase();
      const ariaLabel = (el.getAttribute("aria-label") || "").trim().toLowerCase();
      return targets.some(t => text.includes(t) || ariaLabel.includes(t));
    });

    return matched;
  }

  async function findDialogConfirmButton() {
    const allElements = Array.from(document.querySelectorAll('button, div[role="button"], span, div, a'));
    const targets = ["abandonar grupo", "leave group", "abandonar", "leave", "salir", "confirmar"];
    const candidates = [];
    
    for (const el of allElements) {
      if (el.offsetWidth === 0 && el.offsetHeight === 0) continue;
      
      const text = (el.innerText || el.textContent || "").trim().toLowerCase();
      const ariaLabel = (el.getAttribute("aria-label") || "").trim().toLowerCase();
      
      if (text.includes("cancelar") || text.includes("cancel") || text.includes("cerrar") || text.includes("close")) {
        continue;
      }
      
      if (targets.some(t => text === t || ariaLabel === t || text.includes(t))) {
        candidates.push({
          element: el,
          tag: el.tagName,
          text: text,
          rect: el.getBoundingClientRect()
        });
      }
    }

    if (candidates.length === 0) return null;

    for (let i = candidates.length - 1; i >= 0; i--) {
      const c = candidates[i];
      const isButton = c.tag === 'BUTTON' || c.element.getAttribute('role') === 'button' || c.element.closest('div[role="dialog"]') || c.element.closest('[style*="position: fixed"]');
      if (isButton) return c.element;
    }

    return candidates[candidates.length - 1].element;
  }

  async function run() {
    try {
      console.log("[FB Bulk-Leaver] Esperando a que cargue la lista de grupos...");
      await wait(5000);

      // Verificar si la automatización sigue activa
      const state = await new Promise(r => chrome.storage.local.get({ bulk_leave_active: false }, r));
      if (!state.bulk_leave_active) {
        console.log("[FB Bulk-Leaver] Automatización detenida.");
        return;
      }

      // 1. Localizar la sección de grupos unidos
      const headerEl = findJoinedGroupsHeader();
      let minY = 75; 
      if (headerEl) {
        minY = headerEl.getBoundingClientRect().bottom;
      }

      // 2. Encontrar el primer botón de opciones (...)
      let optionsBtn = findFirstGroupCardOptionsButton(minY);

      if (!optionsBtn) {
        console.log("[FB Bulk-Leaver] No se encontró el botón de tres puntos. Desplazando hacia abajo...");
        window.scrollTo(0, document.body.scrollHeight / 3);
        await wait(3000);

        optionsBtn = findFirstGroupCardOptionsButton(minY);
        if (!optionsBtn) {
          throw new Error("No se encontraron más grupos visibles en la lista.");
        }
      }

      // Obtener nombre del grupo
      let groupName = "Grupo Desconocido";
      try {
        const card = optionsBtn.closest('div[role="listitem"]') || optionsBtn.parentElement?.parentElement?.parentElement || optionsBtn.parentElement?.parentElement;
        if (card) {
          const titleEl = card.querySelector('a[role="link"], h2, h3, span');
          if (titleEl) groupName = titleEl.innerText || titleEl.textContent || groupName;
        }
      } catch(e){}
      groupName = groupName.split('\n')[0].trim();

      // 3. Enfocar y clickear el botón (...)
      optionsBtn.scrollIntoView({ block: 'center', inline: 'nearest' });
      await wait(800);
      
      console.log(`[FB Bulk-Leaver] Haciendo clic en opciones de: "${groupName}"`);
      simulateClick(optionsBtn);
      
      // Esperar menú
      await wait(2000);

      // 4. Clickear "Abandonar grupo"
      const menuOption = findLeaveMenuOption();
      if (!menuOption) {
        throw new Error("No se encontró la opción 'Abandonar grupo' en el menú.");
      }

      console.log("[FB Bulk-Leaver] Haciendo clic en 'Abandonar grupo'...");
      simulateClick(menuOption);

      // Esperar diálogo
      await wait(2000);

      // 5. Confirmar en el modal
      const confirmBtn = await findDialogConfirmButton();
      if (!confirmBtn) {
        throw new Error("No se encontró el botón de confirmación en el modal.");
      }

      console.log("[FB Bulk-Leaver] Confirmando abandono...");
      simulateClick(confirmBtn);

      // Cargar intervalo de espera
      chrome.storage.local.get({ bulk_leave_interval: 5 }, async (store) => {
        const waitTime = (store.bulk_leave_interval || 5) * 1000;
        console.log(`[FB Bulk-Leaver] Esperando ${store.bulk_leave_interval} segundos...`);
        await wait(waitTime);

        chrome.runtime.sendMessage({
          type: "BULK_LEAVE_RESULT",
          data: {
            status: "success",
            groupName: groupName,
            motivo: "Abandonado correctamente"
          }
        });
      });

    } catch (err) {
      console.error("[FB Bulk-Leaver] Error:", err.message);
      chrome.runtime.sendMessage({
        type: "BULK_LEAVE_RESULT",
        data: {
          status: "error",
          groupName: "Grupo Desconocido",
          motivo: err.message
        }
      });
    }
  }

  run();
})();
