"""Test tab parameter in wait methods."""

from unittest.mock import AsyncMock, patch

from browser_hybrid import Browser, Tab


class TestWaitTab:
    @patch("browser_hybrid.browser.Browser._send_cdp")
    @patch("browser_hybrid.browser.Browser._get_connection")
    def test_wait_for_navigation_respects_tab(self, mock_get_conn, mock_send_cdp):
        """wait_for_navigation should respect tab parameter."""
        tab_a = Tab(id="a", url="u", title="t", type="p", web_socket_debugger_url="w")
        tab_b = Tab(id="b", url="u", title="t", type="p", web_socket_debugger_url="w")

        mock_get_conn.return_value = AsyncMock()
        # Mock result for Runtime.evaluate in wait_for_load_state
        mock_send_cdp.return_value = {"result": {"value": "complete"}}

        browser = Browser()
        browser._current_tab = tab_b  # Current is B

        # Wait on A
        browser.wait_for_navigation(tab=tab_a, timeout=0.1)

        # Check that connection was requested for tab_a
        mock_get_conn.assert_called_with(tab_a)

    @patch("browser_hybrid.browser.Browser._send_cdp")
    @patch("browser_hybrid.browser.Browser._get_connection")
    def test_wait_for_respects_tab(self, mock_get_conn, mock_send_cdp):
        """wait_for should respect tab parameter."""
        tab_a = Tab(id="a", url="u", title="t", type="p", web_socket_debugger_url="w")

        mock_get_conn.return_value = AsyncMock()
        # Mock result for Runtime.evaluate
        mock_send_cdp.return_value = {"result": {"result": {"value": True}}}

        browser = Browser()
        browser.wait_for(selector=".btn", tab=tab_a, timeout=0.1)

        # Verify evaluate was called with the correct tab
        # (check _get_connection which is called by evaluate or directly)
        mock_get_conn.assert_called_with(tab_a)

    @patch("browser_hybrid.browser.Browser._send_cdp")
    @patch("browser_hybrid.browser.Browser._get_connection")
    def test_wait_for_url_respects_tab(self, mock_get_conn, mock_send_cdp):
        """wait_for_url should respect tab parameter."""
        tab_a = Tab(id="a", url="u", title="t", type="p", web_socket_debugger_url="w")

        mock_get_conn.return_value = AsyncMock()
        # Mock result for Runtime.evaluate in wait_for_url
        mock_send_cdp.return_value = {"result": {"result": {"value": "https://example.com"}}}

        browser = Browser()
        browser.wait_for_url(url="https://example.com", tab=tab_a, timeout=0.1)

        mock_get_conn.assert_called_with(tab_a)
