"""Navigate and interact with the OfficeSite Manage menu."""
from __future__ import annotations

from playwright.sync_api import Page


def _try_click(loc) -> bool:
    try:
        if loc.count() == 0:
            return False
        target = loc.first if hasattr(loc, "first") else loc
        try:
            target.hover(timeout=1500)
        except Exception:
            pass
        target.click(timeout=3000, force=True)
        return True
    except Exception:
        return False


def open_manage_menu(page: Page) -> None:
    """
    Abre el menú Manage desde la barra superior.
    """
    candidates = [
        page.locator("[data-aroflo-menuitem='Manage']"),
        page.locator(".menuBtn.type-manage"),
        page.get_by_role("link", name="Manage"),
        page.get_by_role("button", name="Manage"),
        page.locator("a:has-text('Manage')"),
        page.locator("button:has-text('Manage')"),
        page.locator("text=Manage"),
        page.locator("span:has-text('Manage')"),
        page.locator("div:has-text('Manage')"),
        page.locator("li:has-text('Manage')"),
    ]

    for loc in candidates:
        try:
            if loc.count() == 0:
                continue
            target = loc.first if hasattr(loc, "first") else loc
            try:
                target.hover(timeout=1500)
            except Exception:
                pass
            if _try_click(loc):
                page.wait_for_timeout(250)
                return
        except Exception:
            continue

    raise RuntimeError("Manage menu not found")


def click_manage_item(page: Page, *, label: str) -> None:
    """
    Click en una opción dentro de Manage (ej: Timesheets).
    """
    label = (label or "").strip()
    if not label:
        raise RuntimeError("Missing label for manage item")

    candidates = [
        page.get_by_role("link", name=label),
        page.get_by_role("button", name=label),
        page.locator(f"a:has-text('{label}')"),
        page.locator(f"button:has-text('{label}')"),
        page.locator(f"text={label}"),
    ]

    for loc in candidates:
        if _try_click(loc):
            return

    raise RuntimeError(f"Manage item not found: {label}")


def click_timesheets(page: Page) -> None:
    """
    Shortcut para Timesheets/Timesheet.
    """
    # Prefer selector directo del mega menu
    direct = page.locator("[data-aroflo-menuitem='manage-timesheet']").first
    if direct.count():
        try:
            direct.click(timeout=4000, force=True)
            return
        except Exception:
            pass

    # Fallback: href contiene Timesheet
    href = page.locator("a[href*='Timesheet/Index.cfm']").first
    if href.count():
        try:
            href.click(timeout=4000, force=True)
            return
        except Exception:
            pass

    for label in ("Timesheets", "Timesheet"):
        try:
            click_manage_item(page, label=label)
            return
        except Exception:
            continue
    raise RuntimeError("Timesheets option not found under Manage")
