"""
Backlog — First-launch warning modal (single tab / no private browsing)
- test_modal_appears_on_fresh_db: Modal appears on first load of a fresh database
- test_modal_shows_both_messages: Both the single-tab and private-browsing messages are shown
- test_dismiss_persists_flag: Dismissing sets the settings flag and hides the modal
- test_modal_does_not_reappear_after_reload: Modal does not reappear on reload once dismissed
"""
import pytest
from playwright.sync_api import Page, expect

# The conftest `page` fixture auto-dismisses this modal for every other test file
# (since a fresh browser context = a fresh DB = "first launch" every time); opt out
# here since these tests exercise the modal directly.
pytestmark = pytest.mark.keep_first_load_warning


def _wait_for_db(page: Page, app_url: str):
    """Navigate and wait for the database to be ready."""
    page.goto(app_url)
    page.wait_for_function(
        "document.documentElement.getAttribute('data-db-ready') === 'true'",
        timeout=15000,
    )


def test_modal_appears_on_fresh_db(page: Page, app_url: str):
    """Modal appears on first load of a fresh database."""
    _wait_for_db(page, app_url)

    expect(page.locator('[data-testid="first-load-warning-modal"]')).to_be_visible()


def test_modal_shows_both_messages(page: Page, app_url: str):
    """Both the single-tab and private-browsing messages are shown together."""
    _wait_for_db(page, app_url)

    expect(page.locator('[data-testid="first-load-warning-single-tab"]')).to_be_visible()
    expect(page.locator('[data-testid="first-load-warning-private-mode"]')).to_be_visible()


def test_dismiss_persists_flag(page: Page, app_url: str):
    """Dismissing the modal sets the settings flag and hides the modal."""
    _wait_for_db(page, app_url)

    modal = page.locator('[data-testid="first-load-warning-modal"]')
    expect(modal).to_be_visible()

    page.locator('[data-testid="first-load-warning-dismiss"]').click()
    expect(modal).not_to_be_visible()

    flag = page.evaluate(
        "async () => await window.__repos.settings.get('first_load_warning_seen')"
    )
    assert flag == 'true', f"first_load_warning_seen should be 'true', got '{flag}'"


def test_modal_does_not_reappear_after_reload(page: Page, app_url: str):
    """Once dismissed, the modal does not reappear on reload."""
    _wait_for_db(page, app_url)

    page.locator('[data-testid="first-load-warning-dismiss"]').click()

    page.reload()
    page.wait_for_function(
        "document.documentElement.getAttribute('data-db-ready') === 'true'",
        timeout=15000,
    )

    expect(page.locator('[data-testid="first-load-warning-modal"]')).not_to_be_visible()
