"""Scrollable two-column chess move notation list widget."""

from __future__ import annotations

from rich.text import Text
from textual.widgets import Static


class MoveListWidget(Static):
    """Displays chess moves in standard two-column notation with move numbers."""

    DEFAULT_CSS = """
    MoveListWidget {
        width: 100%;
        height: 100%;
        padding: 1 2;
    }
    """

    def update_moves(self, san_history: list[str]) -> None:
        """Rebuild and display the move list from a flat SAN history.

        Args:
            san_history: Flat list of SAN strings, alternating white/black moves.
        """
        text = Text()

        # Header row
        text.append(" #", style="dim")
        text.append("   ")
        text.append("White", style="dim")
        text.append("   ")
        text.append("Black", style="dim")
        text.append("\n")

        total_moves = len(san_history)

        # Pair moves into (white, black) tuples per full move
        for i in range(0, total_moves, 2):
            move_number = i // 2 + 1
            white_san = san_history[i]
            black_san = san_history[i + 1] if i + 1 < total_moves else None

            # Move number column: right-aligned to 2 chars, followed by '.'
            number_str = f"{move_number:>2}."
            text.append(number_str, style="dim")
            text.append(" ")

            # Determine if white or black move is the last move
            white_is_last = (i == total_moves - 1)
            black_is_last = (i + 1 == total_moves - 1) if black_san else False

            # White move column: left-aligned, padded to 7 chars
            white_style = "bold green" if white_is_last else ""
            text.append(f"{white_san:<7}", style=white_style)
            text.append(" ")

            # Black move column
            if black_san is not None:
                black_style = "bold green" if black_is_last else ""
                text.append(black_san, style=black_style)

            text.append("\n")

        self.update(text)
