from playwright.async_api import Page

from app.automation.helpers import human_delay
from app.automation.selectors import (
    HUDL_MODAL_CLOSE,
    HUDL_MODAL_CLOSE_ALT,
    HUDL_MODAL_CLOSE_DIV,
)


async def _dismiss_activation_guide(page: Page) -> bool:
    """
    Hudl's #activation-guide-container (onboarding calendar) sits on top of
    Exchange and intercepts clicks on suggested teams. Close / remove it.
    """
    closed = False
    try:
        guide = page.locator("#activation-guide-container")
        if await guide.count() == 0:
            # Still nuke leftover calendar nodes that may float without the root id.
            removed = await page.evaluate(
                """() => {
                  let n = 0;
                  document.querySelectorAll(
                    '.DateRangePicker, .CalendarMonth, [class*="activation-guide"]'
                  ).forEach((el) => {
                    const root =
                      el.closest('#activation-guide-container') ||
                      el.closest('[class*="activation-guide"]') ||
                      el;
                    try { root.remove(); n += 1; } catch (_) {}
                  });
                  return n;
                }"""
            )
            return bool(removed)

        close_selectors = (
            "#activation-guide-container button[aria-label='Close']",
            "#activation-guide-container button[aria-label='close']",
            "#activation-guide-container .uni-dismiss",
            "#activation-guide-container button.uni-dismiss",
            "#activation-guide-container [class*='close']",
            "#activation-guide-container button:has-text('Skip')",
            "#activation-guide-container button:has-text('Got it')",
            "#activation-guide-container button:has-text('Not now')",
            "#activation-guide-container button:has-text('Dismiss')",
            "#activation-guide-container button:has-text('Close')",
            "#activation-guide-container button:has-text('×')",
        )
        for selector in close_selectors:
            btn = page.locator(selector).first
            try:
                if await btn.count() > 0 and await btn.is_visible():
                    await btn.click(timeout=1500, force=True)
                    await human_delay(0.2, 0.4)
                    closed = True
                    break
            except Exception:
                continue

        # Always disable pointer events + remove so clicks never wait 30s.
        await page.evaluate(
            """() => {
              const kill = (el) => {
                if (!el) return;
                try {
                  el.style.pointerEvents = 'none';
                  el.style.display = 'none';
                  el.setAttribute('aria-hidden', 'true');
                  el.remove();
                } catch (_) {}
              };
              kill(document.querySelector('#activation-guide-container'));
              document.querySelectorAll(
                '.DateRangePicker, .CalendarMonth, [class*="activation-guide"], [id*="activation-guide"]'
              ).forEach((n) => {
                const root =
                  n.closest('#activation-guide-container') ||
                  n.closest('[class*="activation-guide"]') ||
                  n;
                kill(root);
              });
            }"""
        )
        closed = True
        await human_delay(0.15, 0.3)
    except Exception as exc:
        print(f"dismiss activation guide failed: {exc}")
    return closed


async def close_hudl_popups(page: Page) -> bool:
    """Close Hudl modal overlays that block automation clicks."""
    closed = False

    if await _dismiss_activation_guide(page):
        closed = True

    for selector in (HUDL_MODAL_CLOSE_DIV, HUDL_MODAL_CLOSE):
        modal_btn = page.locator(selector)
        try:
            if await modal_btn.count() > 0 and await modal_btn.first.is_visible():
                await modal_btn.first.click(timeout=2000, force=True)
                await human_delay(0.3, 0.6)
                closed = True
                break
        except Exception:
            continue

    alt = page.locator(HUDL_MODAL_CLOSE_ALT)
    try:
        if await alt.count() > 0 and await alt.first.is_visible():
            await alt.first.click(timeout=2000, force=True)
            await human_delay(0.3, 0.6)
            closed = True
    except Exception:
        pass

    # Escape often closes leftover overlays without navigating away.
    try:
        if await page.locator("#activation-guide-container").count() > 0:
            await page.keyboard.press("Escape")
            await human_delay(0.2, 0.4)
            await _dismiss_activation_guide(page)
            closed = True
    except Exception:
        pass

    return closed
