"""Tests for the drill BrowserView widget."""

import pytest
from textual.app import App, ComposeResult

from skilark_cli.tui.widgets.browser_view import BrowserView


MOCK_TOPICS = [
    {"topic": "python", "total": 45, "completed": 23, "correct": 18, "accuracy": 0.78},
    {"topic": "go", "total": 30, "completed": 12, "correct": 10, "accuracy": 0.83},
    {"topic": "sql", "total": 25, "completed": 0, "correct": 0, "accuracy": 0.0},
]

MOCK_CATEGORIES = [
    {"category": "arrays", "total": 12, "solved": 5},
    {"category": "strings", "total": 8, "solved": 3},
]


class BrowserApp(App):
    def __init__(self, topics=None, categories=None, configured_topics=None):
        super().__init__()
        self._topics = topics or []
        self._categories = categories or []
        self._configured = configured_topics or []

    def compose(self) -> ComposeResult:
        yield BrowserView(id="browser")

    def on_mount(self) -> None:
        browser = self.query_one("#browser", BrowserView)
        browser.load(self._topics, self._categories, self._configured)


@pytest.mark.asyncio
async def test_browser_mounts():
    """Browser widget mounts without error."""
    app = BrowserApp(topics=MOCK_TOPICS, categories=MOCK_CATEGORIES, configured_topics=["python"])
    async with app.run_test() as pilot:
        browser = app.query_one("#browser", BrowserView)
        assert browser is not None


@pytest.mark.asyncio
async def test_browser_loads_topics():
    """Browser loads quiz items after load()."""
    app = BrowserApp(topics=MOCK_TOPICS, configured_topics=["python", "go"])
    async with app.run_test() as pilot:
        browser = app.query_one("#browser", BrowserView)
        assert len(browser.quiz_items) == 3


@pytest.mark.asyncio
async def test_browser_configured_topics_first():
    """Configured topics appear before unconfigured ones."""
    app = BrowserApp(
        topics=MOCK_TOPICS,
        configured_topics=["go"],  # Only go is configured
    )
    async with app.run_test() as pilot:
        browser = app.query_one("#browser", BrowserView)
        # go should come first (configured), then python, sql
        assert browser.quiz_items[0]["topic"] == "go"


@pytest.mark.asyncio
async def test_browser_loads_categories():
    """Browser loads category items after load()."""
    app = BrowserApp(categories=MOCK_CATEGORIES, configured_topics=[])
    async with app.run_test() as pilot:
        browser = app.query_one("#browser", BrowserView)
        assert len(browser.category_items) == 2
        assert browser.category_items[0]["category"] == "arrays"


@pytest.mark.asyncio
async def test_browser_empty_data():
    """Browser handles empty topics and categories gracefully."""
    app = BrowserApp(topics=[], categories=[], configured_topics=[])
    async with app.run_test() as pilot:
        browser = app.query_one("#browser", BrowserView)
        assert browser.quiz_items == []
        assert browser.category_items == []
