"""Keyboard-driven confirmation modal im Mountain-Stil."""
from __future__ import annotations

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import ModalScreen
from textual.widgets import Static

from taninux.core import theme as T


def _escape_markup(s: str) -> str:
    """Escape Textual/rich markup brackets — wir wollen body als plain text."""
    return s.replace("[", "\\[").replace("]", "\\]")


class ConfirmModal(ModalScreen[bool]):
    """Yes/No-Modal — `y` bestätigt, `n`/`esc` bricht ab."""

    BINDINGS = [
        Binding("y", "confirm", "ja"),
        Binding("n", "cancel", "nein"),
        Binding("enter", "confirm", "ja", show=False),
        Binding("escape", "cancel", "abbruch"),
    ]

    CSS = f"""
    ConfirmModal {{
        align: center middle;
        background: rgba(0, 0, 0, 0.6);
    }}
    ConfirmModal #dialog {{
        width: 80;
        height: auto;
        max-height: 90%;
        padding: 1 2;
        background: {T.YORU};
        border: round {T.BASE3};
    }}
    ConfirmModal #c-title {{
        height: 1;
        background: {T.YORU};
    }}
    ConfirmModal #c-body {{
        height: auto;
        margin-top: 1;
        background: {T.YORU};
        color: {T.YUKI};
    }}
    ConfirmModal #c-hint {{
        height: 1;
        margin-top: 1;
        background: {T.YORU};
        color: {T.BASE4};
    }}
    """

    def __init__(self, title: str, body: str, danger: bool = False) -> None:
        super().__init__()
        self._title = title
        self._body = body
        self._danger = danger

    def compose(self) -> ComposeResult:
        title_color = T.RED if self._danger else T.UME
        with Vertical(id="dialog"):
            yield Static(
                f"[{title_color}]{self._title}[/]",
                id="c-title",
                markup=True,
            )
            # Body: markup escaped — sonst crashen brackets aus argv-output
            yield Static(
                _escape_markup(self._body),
                id="c-body",
            )
            yield Static(
                f"[{T.BASE5}]y[/]/[{T.BASE5}]enter[/] [{T.BASE4}]bestätigen[/]   "
                f"[{T.BASE5}]n[/]/[{T.BASE5}]esc[/] [{T.BASE4}]abbrechen[/]",
                id="c-hint",
                markup=True,
            )

    def action_confirm(self) -> None:
        self.dismiss(True)

    def action_cancel(self) -> None:
        self.dismiss(False)
