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

from __future__ import annotations

from pygittools.tui.draw import clear_row, draw_text
from pygittools.tui.git_colors import active_tab_attr, current_theme

_TAB_GAP = "  "


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:
	"""Refresh cached tab attributes from the active Git color theme."""
	return None


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)
	tab_active = active_tab_attr()
	tab_inactive = current_theme().tab_inactive
	for index, label in enumerate(tab_labels):
		if index > 0:
			col = draw_text(row, col, _TAB_GAP, width, 0)
		tab_attr = tab_active if index == active_index else tab_inactive
		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] + "…"