"""
License Dialog Tests
- test_license_dialog_opens_from_about: Clicking View License in About opens the license modal
- test_license_dialog_contains_agpl_text: The modal displays the GNU AGPL v3 heading
- test_license_dialog_closes: The license modal can be closed independently
- test_about_remains_open_after_license_close: Closing the license dialog keeps About open
"""
from playwright.sync_api import Page, expect


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 _open_license(page: Page, app_url: str):
    """Navigate to Settings, open About, then open the license dialog."""
    _wait_for_db(page, app_url)
    page.click('a[href="#/settings"]')
    page.wait_for_selector('[data-testid="settings-language"]')
    page.click('[data-testid="settings-about"]')
    page.wait_for_selector('[data-testid="modal-card"]')
    page.click('[data-testid="about-license-btn"]')
    page.wait_for_selector('[data-testid="license-dialog-content"]')


def test_license_dialog_opens_from_about(page: Page, app_url: str):
    """Clicking View License in the About dialog opens the license modal."""
    _open_license(page, app_url)
    expect(page.locator('[data-testid="license-dialog-content"]')).to_be_visible()


def test_license_dialog_contains_agpl_text(page: Page, app_url: str):
    """The license modal displays the GNU Affero General Public License heading."""
    _open_license(page, app_url)
    expect(page.locator('[data-testid="license-dialog-content"]')).to_contain_text(
        "GNU AFFERO GENERAL PUBLIC LICENSE"
    )


def test_license_dialog_closes(page: Page, app_url: str):
    """The license modal can be closed with its own close button."""
    _open_license(page, app_url)
    modals = page.locator('[data-testid="modal-close"]')
    modals.last.click()
    expect(page.locator('[data-testid="license-dialog-content"]')).not_to_be_visible()


def test_about_remains_open_after_license_close(page: Page, app_url: str):
    """Closing the license dialog leaves the About dialog still open."""
    _open_license(page, app_url)
    modals = page.locator('[data-testid="modal-close"]')
    modals.last.click()
    expect(page.locator('[data-testid="license-dialog-content"]')).not_to_be_visible()
    expect(page.locator('[data-testid="about-app-version"]')).to_be_visible()
