"""Fade overlay widget for closure ritual."""

import asyncio
from typing import Optional
from textual.widgets import Static
from textual.message import Message


class FadeOverlay(Static):
    """Full-screen fade overlay for closure ritual animation.

    Animates a three-phase fade with action-specific timing.
    """

    _TIMINGS = {
        "default": (0.4, 0.2, 0.4),
        "save": (0.2, 0.1, 0.2),
        "quit": (0.5, 0.4, 0.5),
    }

    DEFAULT_CSS = """
    FadeOverlay {
        display: none;
        layer: overlay;
        width: 100%;
        height: 100%;
        background: $background;
        color: #e0e0e0;
        opacity: 0;
        content-align: center middle;
        text-style: bold;
    }

    FadeOverlay.visible {
        display: block;
    }
    """

    class FadeComplete(Message):
        """Posted when fade animation completes."""
        pass

    async def animate(
        self, action_type: str = "default", message: Optional[str] = None
    ) -> None:
        """Run the fade animation sequence."""
        fade_in, hold, fade_out = self._TIMINGS.get(
            action_type, self._TIMINGS["default"]
        )

        # Show the overlay
        self.update(message or "")
        self.add_class("visible")

        # Phase 1: Fade in
        self.styles.opacity = 0.0
        self.styles.animate("opacity", 1.0, duration=fade_in)
        await asyncio.sleep(fade_in)

        # Phase 2: Hold
        await asyncio.sleep(hold)

        # Phase 3: Fade out
        self.styles.animate("opacity", 0.0, duration=fade_out)
        await asyncio.sleep(fade_out)

        # Hide the overlay
        self.remove_class("visible")
        self.update("")

        # Notify that animation is complete
        self.post_message(self.FadeComplete())
