"""
导航操作 Mixin
"""
from typing import Optional, TYPE_CHECKING

from loguru import logger

if TYPE_CHECKING:
    from ..tab import Tab


class NavigationMixin:
    """导航操作功能"""

    # 这些属性由其他 mixin 或 core 定义
    _tabs: dict[str, "Tab"]
    _current_tab: Optional[str]
    config: "Config"

    async def goto(
        self,
        url: str,
        tab_id: Optional[str] = None,
        wait_until: str = "load"
    ) -> "Tab":
        """
        导航到URL

        Args:
            url: 目标URL
            tab_id: 标签页ID
            wait_until: 等待条件

        Returns:
            Tab: 当前标签页
        """
        tab = self.get_tab(tab_id)
        logger.info(f"导航: tab={tab.name}, url={url}")

        await tab.page.goto(url, wait_until=wait_until)
        tab.url = tab.page.url

        logger.info(f"导航完成: url={tab.url}")

        # 自动关闭弹窗
        if self.config.auto_close_popup:
            await self.close_popup(tab_id)

        return tab

    async def close_popup(self, tab_id: Optional[str] = None) -> bool:
        """
        关闭页面弹窗

        Args:
            tab_id: 标签页ID

        Returns:
            bool: 是否成功关闭
        """
        from ...popup import PopupHandler

        tab = self.get_tab(tab_id)
        handler = PopupHandler(tab.page)

        success = await handler.wait_and_close(
            timeout=self.config.popup_close_timeout
        )

        if success:
            logger.info("弹窗已自动关闭")

        return success
