"""Frontend E2E tests — dashboard stats and activity."""

import pytest
import requests


def _login(page):
    """Helper: login as admin."""
    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)


@pytest.mark.frontend
def test_dashboard_shows_stats(page, live_server):
    """Dashboard tab shows stats after assets are created."""
    _login(page)

    # Create assets via API
    requests.post(
        f"{live_server}/api/assets",
        json={
            "machine_id": "DASH-001",
            "name": "Dashboard Asset 1",
            "category": "Furniture",
        },
    )
    requests.post(
        f"{live_server}/api/assets",
        json={
            "machine_id": "DASH-002",
            "name": "Dashboard Asset 2",
            "category": "Appliances",
        },
    )

    # Navigate to Dashboard
    page.locator(".tab-btn[data-tab='tabDashboard']").click()
    page.wait_for_selector("#tabDashboard.active", timeout=3000)

    # Wait for stats to load (the app fetches /api/stats)
    page.wait_for_timeout(1000)

    # Verify stats cards are present
    cards = page.locator(".card")
    assert cards.count() >= 2


@pytest.mark.frontend
def test_activity_feed_shows_events(page, live_server):
    """Activity feed shows recent actions."""
    _login(page)

    # Create an asset (triggers activity log entry)
    requests.post(
        f"{live_server}/api/assets",
        json={
            "machine_id": "ACT-001",
            "name": "Activity Test Asset",
            "category": "Other",
        },
    )

    # Navigate to Activity tab (only accessible via drawer)
    page.locator(".hamburger").click()
    page.wait_for_selector("#drawer.open", timeout=3000)
    page.locator(".dn-item[data-tab='tabActivity']").click()
    page.wait_for_selector("#tabActivity.active", timeout=3000)
    page.wait_for_timeout(2000)

    # Should show activity items or empty state (scoped to #actList to avoid
    # matching .empty-state divs in hidden tab panels)
    page.wait_for_selector("#actList .activity-item, #actList .empty-state", timeout=5000)
