"""Event log widget.

Scrollable panel showing recent creature events with timestamps
and emotional coloring.
"""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import VerticalScroll
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Label, Static

from sibilance.api.types import RecentEvent


# Map emotional colors to ANSI hex codes
EMOTION_COLORS: dict[str, str] = {
    "joy": "#ffd93d",
    "curiosity": "#4ea8de",
    "contentment": "#6bcb77",
    "anxiety": "#ff6b6b",
    "loneliness": "#ee6fff",
    "excitement": "#ffd93d",
    "trust": "#4ecdc4",
    "fear": "#ff6b6b",
    "surprise": "#7b68ee",
    "sadness": "#4a4a6a",
    "anger": "#ff6b6b",
}

DEFAULT_EVENT_COLOR = "#8888aa"


class EventItem(Static):
    """A single event entry in the log."""

    DEFAULT_CSS = """
    EventItem {
        height: auto;
        padding: 0 1;
        margin: 0 0 0 0;
    }
    """

    def __init__(self, event: RecentEvent, **kwargs: object) -> None:
        color = EMOTION_COLORS.get(event.emotional_color, DEFAULT_EVENT_COLOR)
        # Build rich markup
        willingness = "●" if event.share_willingness > 0.5 else "○"
        embellished = " ✦" if event.is_embellished else ""
        text = f"[{color}]{willingness}[/] {event.creature_description}{embellished}"
        super().__init__(text, markup=True, **kwargs)


class EventLog(Widget):
    """Scrollable log of recent creature events."""

    DEFAULT_CSS = """
    EventLog {
        height: 1fr;
        border: solid $secondary;
        background: $surface;
        padding: 0;
    }
    EventLog .log-header {
        color: $text;
        text-style: bold;
        padding: 0 1;
        dock: top;
        height: 1;
        background: $surface;
    }
    EventLog VerticalScroll {
        height: 1fr;
    }
    """

    events: reactive[list[RecentEvent]] = reactive(list, always_update=True)

    def compose(self) -> ComposeResult:
        yield Label("Recent Events", classes="log-header")
        yield VerticalScroll(id="event-scroll")

    def watch_events(self, new_events: list[RecentEvent]) -> None:
        """Rebuild the event list when events change."""
        try:
            scroll = self.query_one("#event-scroll", VerticalScroll)
            scroll.remove_children()
            for event in new_events:
                scroll.mount(EventItem(event))
            # Auto-scroll to bottom
            scroll.scroll_end(animate=False)
        except Exception:
            pass

    def add_event(self, event: RecentEvent) -> None:
        """Append a single event to the log."""
        try:
            scroll = self.query_one("#event-scroll", VerticalScroll)
            scroll.mount(EventItem(event))
            scroll.scroll_end(animate=False)
        except Exception:
            pass
