"""
Custom footer widget with three sections: left, right, and status.

This module provides a custom footer that divides the footer into three sections:
- Left: Items added from the left side of the screen
- Right: Items added from the right side of the screen
- Status: Right edge section separated by a vertical line
"""

from textual.app import ComposeResult
from textual.containers import Horizontal
from textual.widgets import Static
from textual.widget import Widget
from rich.text import Text


class FooterKey(Widget):
    """A key/action pair widget for the footer, styled similar to Textual's original FooterKey."""

    DEFAULT_CSS = """
    FooterKey {
        width: auto;
        height: 1;
        content-align: center middle;
        padding: 0 1;
    }
    
    .footer-key--key {
        text-style: bold;
        color: $text;
    }
    
    .footer-key--description {
        color: $text-muted;
    }
    """

    def __init__(self, key: str, description: str, **kwargs):
        super().__init__(**kwargs)
        self.key = key
        self.description = description

    def render(self) -> Text:
        """Render the key-description pair with proper styling."""
        text = Text()
        text.append(f"{self.key}", style="bold")
        text.append(" ")
        text.append(self.description, style="dim")
        return text


class CustomFooter(Widget):
    """
    A custom footer widget with three sections.

    Layout: [Left items] [spacer] [Right items] | [Status]
    """

    DEFAULT_CSS = """
    CustomFooter {
        background: $surface;
        color: $text;
        dock: bottom;
        height: 1;
        padding: 0 1;
        width: 100%;
    }
    
    CustomFooter > Horizontal {
        height: 1;
        width: 100%;
        align: left middle;
    }
    
    .footer-left {
        width: auto;
        text-align: left;
        height: 1;
        content-align: left middle;
    }
    
    .footer-spacer {
        width: 1fr;
        height: 1;
    }
    
    .footer-right {
        width: auto;
        text-align: right;
        height: 1;
        content-align: right middle;
    }
    
    .footer-separator {
        width: auto;
        color: $primary;
        text-style: dim;
        height: 1;
        content-align: center middle;
    }
    
    .footer-status {
        width: auto;
        text-align: right;
        color: $accent;
        text-style: bold;
        height: 1;
        content-align: right middle;
    }
    
    /* Enhanced styling for footer key components */
    .footer-left .footer-key--key,
    .footer-right .footer-key--key {
        text-style: bold;
        color: $text;
    }
    
    .footer-left .footer-key--description,
    .footer-right .footer-key--description {
        color: $text-muted;
        text-style: dim;
    }
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._left_items = []  # List of FooterKey widgets
        self._right_items = []  # List of FooterKey widgets
        self._status_text = ""

    def compose(self) -> ComposeResult:
        """Create the footer layout."""
        with Horizontal():
            yield Static("", id="footer-left", classes="footer-left")
            yield Static("", id="footer-spacer", classes="footer-spacer")
            yield Static("", id="footer-right", classes="footer-right")
            yield Static(" │ ", id="footer-separator", classes="footer-separator")
            yield Static("", id="footer-status", classes="footer-status")

    def add_left_item(self, key: str, description: str) -> None:
        """Add a key-description pair to the left section."""
        footer_key = FooterKey(key, description)
        self._left_items.append(footer_key)
        self._update_left_section()

    def add_right_item(self, key: str, description: str) -> None:
        """Add a key-description pair to the right section."""
        footer_key = FooterKey(key, description)
        self._right_items.append(footer_key)
        self._update_right_section()

    def add_left_item_legacy(self, item: str) -> None:
        """Add a legacy item (key: description format) to the left section."""
        if ": " in item:
            key, description = item.split(": ", 1)
            self.add_left_item(key, description)
        else:
            self.add_left_item(item, "")

    def add_right_item_legacy(self, item: str) -> None:
        """Add a legacy item (key: description format) to the right section."""
        if ": " in item:
            key, description = item.split(": ", 1)
            self.add_right_item(key, description)
        else:
            self.add_right_item(item, "")

    # Backward compatibility - temporarily add the old single parameter methods
    def add_left_item_old(self, item: str) -> None:
        """Backward compatibility method."""
        self.add_left_item_legacy(item)

    def add_right_item_old(self, item: str) -> None:
        """Backward compatibility method."""
        self.add_right_item_legacy(item)

    def clear_left_items(self) -> None:
        """Clear all items from the left section."""
        self._left_items.clear()
        self._update_left_section()

    def clear_right_items(self) -> None:
        """Clear all items from the right section."""
        self._right_items.clear()
        self._update_right_section()

    def set_status(self, status: str) -> None:
        """Set the status text."""
        self._status_text = status
        self._update_status_section()

    def _update_left_section(self) -> None:
        """Update the left section display."""
        try:
            left_static = self.query_one("#footer-left", Static)
            if self._left_items:
                # Combine all FooterKey renderings with spacing
                combined_text = Text()
                for i, footer_key in enumerate(self._left_items):
                    if i > 0:
                        combined_text.append("  ")  # Add spacing between items
                    # Render individual key-description pair with styling
                    combined_text.append(footer_key.key, style="bold")
                    combined_text.append(" ")
                    combined_text.append(footer_key.description, style="dim")
                left_static.update(combined_text)
            else:
                left_static.update("")
        except Exception:
            pass  # Widget not ready yet

    def _update_right_section(self) -> None:
        """Update the right section display."""
        try:
            right_static = self.query_one("#footer-right", Static)
            if self._right_items:
                # Combine all FooterKey renderings with spacing
                combined_text = Text()
                for i, footer_key in enumerate(self._right_items):
                    if i > 0:
                        combined_text.append("  ")  # Add spacing between items
                    # Render individual key-description pair with styling
                    combined_text.append(footer_key.key, style="bold")
                    combined_text.append(" ")
                    combined_text.append(footer_key.description, style="dim")
                right_static.update(combined_text)
            else:
                right_static.update("")
        except Exception:
            pass  # Widget not ready yet

    def _update_status_section(self) -> None:
        """Update the status section display."""
        try:
            status_static = self.query_one("#footer-status", Static)
            status_static.update(self._status_text)
        except Exception:
            pass  # Widget not ready yet

    def on_mount(self) -> None:
        """Called when the widget is mounted."""
        # Initialize all sections
        self._update_left_section()
        self._update_right_section()
        self._update_status_section()
