"""Tab bar rendering for the home page header."""

from __future__ import annotations

from unicurses import (  # type: ignore[import-untyped]
	A_BOLD,
	COLOR_BLACK,
	COLOR_PAIR,
	COLOR_YELLOW,
	has_colors,
	init_pair,
)

from pygittools.tui.draw import clear_row, draw_text

_TAB_GAP = "  "
_TAB_ACTIVE_PAIR = 2
_active_tab_attr = 0


def tab_row_layout(prefix: str, tab_labels: tuple[str, ...]) -> list[tuple[int, str]]:
	"""Return the starting column for each tab label."""
	col = len(prefix) + len(_TAB_GAP)
	layout: list[tuple[int, str]] = []
	for index, label in enumerate(tab_labels):
		if index > 0:
			col += len(_TAB_GAP)
		layout.append((col, label))
		col += len(label)
	return layout


def init_tab_colors() -> None:
	"""Initialize the color pair used to highlight the active tab."""
	global _active_tab_attr
	if has_colors():
		init_pair(_TAB_ACTIVE_PAIR, COLOR_BLACK, COLOR_YELLOW)
		_active_tab_attr = COLOR_PAIR(_TAB_ACTIVE_PAIR)
	else:
		_active_tab_attr = A_BOLD


def draw_tab_row(
	row: int,
	width: int,
	prefix: str,
	tab_labels: tuple[str, ...],
	active_index: int,
	*,
	prefix_attr: int = 0,
) -> None:
	"""Draw ``prefix`` followed by selectable tab labels on one row."""
	if width <= 0:
		return
	clear_row(row)
	clipped_prefix = _clip_prefix(prefix, width, tab_labels)
	col = 0
	col = draw_text(row, col, clipped_prefix, width, prefix_attr)
	col = draw_text(row, col, _TAB_GAP, width, 0)
	for index, label in enumerate(tab_labels):
		if index > 0:
			col = draw_text(row, col, _TAB_GAP, width, 0)
		tab_attr = _active_tab_attr if index == active_index else 0
		col = draw_text(row, col, label, width, tab_attr)


def _tabs_reserved_width(tab_labels: tuple[str, ...]) -> int:
	if not tab_labels:
		return 0
	total = len(_TAB_GAP)
	for index, label in enumerate(tab_labels):
		if index > 0:
			total += len(_TAB_GAP)
		total += len(label)
	return total


def _clip_prefix(prefix: str, width: int, tab_labels: tuple[str, ...]) -> str:
	max_prefix = max(0, width - _tabs_reserved_width(tab_labels))
	if len(prefix) <= max_prefix:
		return prefix
	if max_prefix <= 1:
		return prefix[:max_prefix]
	return prefix[: max_prefix - 1] + "…"