import { Page } from "@playwright/test";

/**
 * Cierra todos los toasts/notificaciones de Element que bloquean clicks.
 * Incluye: Notifications, Threads Activity Centre, y cualquier toast generico.
 */
export async function dismissAllToasts(page: Page) {
  // Dar un momento para que los toasts aparezcan
  await page.waitForTimeout(1_500);

  // Estrategia directa: buscar botones conocidos de toasts de Element
  const knownDismissButtons = [
    page.getByRole("button", { name: "Dismiss" }),
    page.locator("button").filter({ hasText: /^OK$/ }),
    page.getByRole("button", { name: "Close" }),
    page.getByRole("button", { name: "Not now" }),
    page.getByRole("button", { name: "Got it" }),
    page.getByRole("button", { name: "Skip" }),
  ];

  for (const btn of knownDismissButtons) {
    try {
      if (await btn.first().isVisible()) {
        const text = await btn.first().textContent().catch(() => "?");
        console.log(`[element] Dismissing toast: clicking "${text}"`);
        await btn.first().click({ force: true });
        await page.waitForTimeout(500);
      }
    } catch {
      // Ignorar errores — el boton pudo desaparecer entre check y click
    }
  }

  // Segunda pasada: verificar si queda algun toast con boton visible
  const remainingToastBtns = page.locator(
    '.mx_ToastContainer button, .mx_Toast_buttons button'
  );
  const remaining = await remainingToastBtns.count();
  if (remaining > 0) {
    for (let i = 0; i < remaining; i++) {
      try {
        if (await remainingToastBtns.nth(i).isVisible()) {
          const text = await remainingToastBtns.nth(i).textContent();
          console.log(`[element] Closing remaining toast button: "${text}"`);
          await remainingToastBtns.nth(i).click({ force: true });
          await page.waitForTimeout(300);
        }
      } catch {
        // Ignorar
      }
    }
  }
}
