"""Multi-tab coordination example.

Demonstrates isolated workflows with temp_tab() and switching
between multiple active tabs with switch_to_tab().

Chrome must be running with --remote-debugging-port=9222
"""

import logging

from browser_hybrid import Browser

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def main():
    # 1. Start browser
    try:
        with Browser() as browser:
            # 2. Open first tab
            logger.info("Opening GitHub in first tab...")
            browser.goto("https://github.com", timeout=30.0)

            # 3. Perform an isolated search in a temporary tab
            logger.info("Starting isolated search in a temp tab...")
            with browser.temp_tab("https://www.google.com") as tab:
                logger.info(f"Isolated tab ID: {tab.id}")
                browser.type_by_name("Search", "python browser automation")
                browser.press_key("Enter")
                browser.wait_for_load_state()
                logger.info("Search results loaded in isolated tab.")

            # 4. Back in the original tab, do more work
            logger.info(f"Main tab ID: {browser.current_tab.id}")
            logger.info("Clicking GitHub Sign in button...")
            browser.click_by_text("Sign in")

            # 5. Coordinate between two long-lived tabs
            logger.info("Opening Hacker News in a second long-lived tab...")
            browser.goto("https://news.ycombinator.com")

            # Switch back to first tab
            logger.info("Switching back to main tab (GitHub)...")
            tabs = browser.list_tabs()
            tab1 = tabs[1] if len(tabs) > 1 else tabs[0]
            prev = browser.switch_to_tab(tab1)
            msg = f"Switched from {prev.title if prev else 'None'} to {browser.current_tab.title}"
            logger.info(msg)

    except ConnectionError as e:
        logger.error(f"Failed to connect to Chrome: {e}")
    except Exception as e:
        logger.exception(f"An unexpected error occurred: {e}")


if __name__ == "__main__":
    main()
