#!/usr/bin/env python3
"""Footer component for the UI."""
from typing import List, Optional, Tuple

from ..display import Display


class FooterComponent:
    """Renders the application footer with help text and controls."""

    def __init__(self, display: Display):
        """Initialize the footer component.

        Args:
            display: Display instance
        """
        self.display = display
        self.default_controls = [
            ("q", "quit"),
            ("c", "sort CPU"),
            ("m", "sort MEM"),
            ("h", "toggle sort"),
            ("arrows", "navigate"),
        ]

    def render(
        self,
        y: Optional[int] = None,
        custom_controls: Optional[List[Tuple[str, str]]] = None,
        attr: Optional[int] = None,
    ) -> int:
        """Render the footer.

        Args:
            y: Y coordinate (ignored, uses layout system)
            custom_controls: Optional custom control mappings
            attr: Custom attribute override

        Returns:
            Y coordinate where footer was rendered
        """
        if attr is None:
            attr = self.display.get_theme_attr("muted")

        # Get footer layout from layout system
        layout = self.display.layout.calculate()
        footer_rect = layout["footer"]
        row_width = max(0, footer_rect.width)

        controls = (
            custom_controls if custom_controls is not None else self.default_controls
        )

        chip_attr = self.display.get_theme_attr("chip")
        right_x = row_width - 1

        x = 1
        for index, (key, action) in enumerate(controls):
            key_chip = f"[{key}]"
            action_text = f" {action}"
            chunk_len = len(key_chip) + len(action_text)
            if x + chunk_len >= right_x:
                break

            self.display.safe_addstr(footer_rect.y, x, key_chip, chip_attr)
            x += len(key_chip)
            self.display.safe_addstr(footer_rect.y, x, action_text, attr)
            x += len(action_text)

            if index < len(controls) - 1 and x + 2 < right_x:
                self.display.safe_addstr(footer_rect.y, x, "  ", attr)
                x += 2

        return footer_rect.y

    def create_custom_footer(self, *controls: Tuple[str, str]) -> List[Tuple[str, str]]:
        """Create a custom footer control mapping.

        Args:
            *controls: Variable number of (key, action) tuples

        Returns:
            List of control tuples
        """
        return list(controls)

    def add_control(
        self, controls: List[Tuple[str, str]], key: str, action: str
    ) -> List[Tuple[str, str]]:
        """Add a control to an existing control list.

        Args:
            controls: Existing controls list
            key: Key binding
            action: Action description

        Returns:
            Updated controls list
        """
        return controls + [(key, action)]
