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

from __future__ import annotations

from unicurses import (  # type: ignore[import-untyped]
	A_REVERSE,
	COLOR_BLUE,
	COLOR_PAIR,
	COLOR_WHITE,
	has_colors,
	init_pair,
	mvaddstr,
	start_color,
	use_default_colors,
)

_STATUS_PAIR = 1
_DEFAULT_HINT = "q quit"


def init_status_bar() -> int:
	"""Initialize status bar colors and return the text attribute to use."""
	if has_colors():
		start_color()
		use_default_colors()
		init_pair(_STATUS_PAIR, COLOR_WHITE, COLOR_BLUE)
		return COLOR_PAIR(_STATUS_PAIR)
	return A_REVERSE


def content_height(full_height: int) -> int:
	"""Rows available to page content above the status bar."""
	return max(0, full_height - 1)


def draw_status_bar(row: int, width: int, text: str, attr: int, hint: str = _DEFAULT_HINT) -> None:
	"""Draw the status bar on the last screen row."""
	if width <= 0:
		return
	line = _format_line(text, hint, width)
	mvaddstr(row, 0, line, attr)


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)