"""Category navigation sidebar widget."""

from textual.binding import Binding
from textual.message import Message
from textual.widgets import ListItem, ListView


class CategorySelected(Message):
    """Message emitted when a category is selected."""

    def __init__(self, category: str) -> None:
        self.category = category
        super().__init__()


class CategoryListView(ListView):
    """Custom ListView - highlight changes show page, Enter/right focuses panel."""

    BINDINGS = [
        Binding("right", "select_cursor", "Select", show=False),
        Binding("enter", "select_cursor", "Select", show=False),
        Binding("l", "select_cursor", "Select", show=False),
    ]

    def watch_index(self, old_index: int | None, new_index: int | None) -> None:
        """When index changes, post Highlighted event."""
        super().watch_index(old_index, new_index)
        # new_index can be None when list is cleared
        if new_index is None:
            return
        # Get item at new index directly (highlighted_child may not be updated yet)
        items = list(self.query("ListItem").results())
        if 0 <= new_index < len(items):
            self.post_message(self.Highlighted(self, items[new_index]))

    def action_select_cursor(self) -> None:
        """Select the currently highlighted item (for focusing panel)."""
        if self.highlighted_child is not None:
            self.post_message(self.Selected(self, self.highlighted_child, self.index))
