"""Bottom status bar shared by all pages."""

from __future__ import annotations

from pyratatui import Constraint, Direction, Frame, Layout, Paragraph, Rect, Style

_DEFAULT_HINT = "q quit"


def split_content_status(area: Rect) -> tuple[Rect, Rect]:
    """Split the frame into content above a one-row status bar."""
    chunks = Layout().direction(Direction.Vertical).constraints([Constraint.fill(1), Constraint.length(1)]).split(area)
    return chunks[0], chunks[1]


def render_status_bar(
    frame: Frame,
    area: Rect,
    text: str,
    style: Style,
    hint: str = _DEFAULT_HINT,
) -> None:
    """Draw the status bar into ``area``."""
    if area.width <= 0 or area.height <= 0:
        return
    line = _format_line(text, hint, area.width)
    frame.render_widget(Paragraph.from_string(line).style(style), area)


def _format_line(left: str, right: str, width: int) -> str:
    if not right:
        return left[:width].ljust(width)
    if len(right) >= width:
        return right[:width].ljust(width)
    space = width - len(right)
    if space <= 1:
        return right[:width].ljust(width)
    clipped_left = left[: space - 1]
    return f"{clipped_left:<{space - 1}} {right}"[:width].ljust(width)