"""World clock widget.

Displays the world time, day of week, season, and weather
in a compact format suitable for the header area or info panel.
"""

from __future__ import annotations

from textual.app import ComposeResult
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Label

from sibilance.api.types import WorldState

# Period icons
PERIOD_ICONS: dict[str, str] = {
    "dawn": "🌅",
    "morning": "☀",
    "afternoon": "☀",
    "dusk": "🌇",
    "evening": "🌙",
    "night": "🌑",
}

# Season icons
SEASON_ICONS: dict[str, str] = {
    "spring": "🌱",
    "summer": "🌻",
    "autumn": "🍂",
    "winter": "❄",
}

# Weather icons
WEATHER_ICONS: dict[str, str] = {
    "clear": "☀",
    "misty": "🌫",
    "electric": "⚡",
    "serene": "✨",
    "breezy": "🍃",
    "starlit": "⭐",
}

# Period colors for visual distinction
PERIOD_COLORS: dict[str, str] = {
    "dawn": "#ffd93d",
    "morning": "#ffd93d",
    "afternoon": "#ffd93d",
    "dusk": "#ff6b6b",
    "evening": "#7b68ee",
    "night": "#4a4a6a",
}


class WorldClock(Widget):
    """Compact world clock: time, day, season, weather."""

    DEFAULT_CSS = """
    WorldClock {
        height: auto;
        padding: 0 1;
    }
    WorldClock .clock-time {
        color: $foreground;
        text-style: bold;
    }
    WorldClock .clock-detail {
        color: $text-muted;
    }
    WorldClock .clock-weather {
        color: $text;
    }
    """

    world_state: reactive[WorldState | None] = reactive(None)

    def compose(self) -> ComposeResult:
        yield Label("◷ --:-- ", classes="clock-time", id="clock-time")
        yield Label("", classes="clock-detail", id="clock-detail")
        yield Label("", classes="clock-weather", id="clock-weather")

    def watch_world_state(self, state: WorldState | None) -> None:
        if state is None:
            return
        try:
            t = state.time
            h = str(t.hour).zfill(2)
            m = str(t.minute).zfill(2)
            period_icon = PERIOD_ICONS.get(t.period, "◷")
            period_color = PERIOD_COLORS.get(t.period, "#8888aa")
            season_icon = SEASON_ICONS.get(t.season, "")
            weather_icon = WEATHER_ICONS.get(state.weather, "")

            self.query_one("#clock-time", Label).update(
                f"[{period_color}]{period_icon}[/] [{period_color}]{h}:{m}[/] "
                f"[#4a4a6a]{t.period}[/]"
            )
            self.query_one("#clock-detail", Label).update(
                f"{season_icon} {t.season.capitalize()} · "
                f"{t.day_of_week} · Day {t.day}"
            )
            weather_desc = state.weather_description or state.weather
            self.query_one("#clock-weather", Label).update(
                f"{weather_icon} {weather_desc}"
            )
        except Exception:
            pass

    def update_from_world(self, state: WorldState) -> None:
        """Update display from a WorldState."""
        self.world_state = state
