"""Textual modal screen for pawn promotion piece selection."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, Label


class PromotionModal(ModalScreen[str]):
    """Modal dialog that prompts the player to choose a promotion piece.

    Dismisses with one of ``"Q"``, ``"R"``, ``"B"``, or ``"N"``.
    """

    DEFAULT_CSS = """
    PromotionModal {
        align: center middle;
        background: rgba(0, 0, 0, 0.6);
    }

    PromotionModal #promotion-container {
        width: auto;
        max-width: 60;
        height: auto;
        padding: 1 2;
        background: $surface;
        border: thick $primary;
    }

    PromotionModal #promotion-title {
        width: 100%;
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    PromotionModal #promotion-buttons {
        width: auto;
        height: auto;
        align-horizontal: center;
    }

    PromotionModal #promotion-buttons Button {
        margin: 0 1;
        min-width: 16;
    }
    """

    BINDINGS = [
        Binding("q", "select('Q')", "Queen", show=False),
        Binding("r", "select('R')", "Rook", show=False),
        Binding("b", "select('B')", "Bishop", show=False),
        Binding("n", "select('N')", "Knight", show=False),
        Binding("escape", "select('Q')", "Cancel", show=False),
    ]

    def compose(self) -> ComposeResult:
        with Vertical(id="promotion-container"):
            yield Label("Promote to?", id="promotion-title")
            with Horizontal(id="promotion-buttons"):
                yield Button("\u265b Queen (Q)", id="btn-queen", variant="primary")
                yield Button("\u265c Rook (R)", id="btn-rook")
                yield Button("\u265d Bishop (B)", id="btn-bishop")
                yield Button("\u265e Knight (N)", id="btn-knight")

    _BUTTON_MAP: dict[str, str] = {
        "btn-queen": "Q",
        "btn-rook": "R",
        "btn-bishop": "B",
        "btn-knight": "N",
    }

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Dismiss the modal when any promotion button is pressed."""
        piece = self._BUTTON_MAP.get(event.button.id or "", "Q")
        self.dismiss(piece)

    def action_select(self, piece: str) -> None:
        """Handle key-binding actions for piece selection."""
        self.dismiss(piece)
