"""Frontend E2E tests — authentication (login/logout)."""

import pytest


@pytest.mark.frontend
def test_login_success(page, live_server):
    """Login with default admin credentials succeeds."""
    # Should see login overlay initially
    assert page.locator("#loginOverlay").is_visible()

    # Fill credentials
    page.locator("#loginUsername").fill("admin")
    page.locator("#loginPassword").fill("changeme")
    page.locator("button:has-text('Sign In')").click()

    # Login overlay should hide (wait for it to become hidden)
    page.wait_for_selector("#loginOverlay", state="hidden", timeout=5000)

    # User badge should show 'A' for admin
    badge = page.locator("#userBadge")
    assert badge.inner_text() == "A"

    # Toast should appear briefly
    page.wait_for_selector("#toast.show", timeout=3000)


@pytest.mark.frontend
def test_login_bad_password(page, live_server):
    """Login with wrong password shows error."""
    page.locator("#loginUsername").fill("admin")
    page.locator("#loginPassword").fill("wrongpassword")
    page.locator("button:has-text('Sign In')").click()

    # Error message should appear
    error = page.locator("#loginError")
    error.wait_for(state="visible", timeout=5000)
    assert error.inner_text() != ""

    # Login overlay should still be visible
    assert page.locator("#loginOverlay").is_visible()


@pytest.mark.frontend
def test_login_empty_credentials(page, live_server):
    """Login with empty fields shows validation error."""
    page.locator("button:has-text('Sign In')").click()
    error = page.locator("#loginError")
    error.wait_for(state="visible", timeout=3000)
    assert "username" in error.inner_text().lower()


@pytest.mark.frontend
def test_logout(page, live_server):
    """Login, then logout — should see login overlay again."""
    # Login first
    page.locator("#loginUsername").fill("admin")
    page.locator("#loginPassword").fill("changeme")
    page.locator("button:has-text('Sign In')").click()
    page.wait_for_selector("#loginOverlay", state="hidden", timeout=5000)

    # Open drawer and click Logout
    page.locator(".hamburger").click()
    page.wait_for_selector("#drawer.open", timeout=3000)
    page.locator("#logoutBtn").click()

    # Should see login overlay again
    page.wait_for_selector("#loginOverlay", state="visible", timeout=5000)
    assert page.locator("#loginOverlay").is_visible()
