"""Reusable app shell primitives for page-level layout."""

from __future__ import annotations

from nicegui import ui

NAV_ITEMS: tuple[tuple[str, str, str], ...] = (
    ("Documents", "/documents", "description"),
    ("People", "/people", "group"),
    ("Sources", "/sources", "folder"),
    ("Jobs", "/jobs", "work_history"),
)

from transcription.ui.theme import VIBESCRIBE_LOGO_SVG

def _is_active_path(*, current_path: str, item_path: str) -> bool:
    if item_path == "/jobs":
        return current_path == "/jobs" or current_path.startswith("/jobs/")
    if item_path == "/documents":
        return current_path == "/documents" or current_path.startswith("/documents/")
    if item_path == "/people":
        return current_path == "/people" or current_path.startswith("/people/")
    if item_path == "/sources":
        return current_path == "/sources" or current_path.startswith("/sources/")
    return current_path == item_path


def _render_nav_button(*, label: str, path: str, icon: str, current_path: str) -> None:
    is_active = _is_active_path(current_path=current_path, item_path=path)
    classes = "app-shell__nav-item"
    if is_active:
        classes = f"{classes} app-shell__nav-item--active"

    ui.button(
        label,
        icon=icon,
        on_click=lambda _=None, route=path: ui.navigate.to(route),
    ).props("flat no-caps").classes(classes)


def _normalize_path(current_path: str | None) -> str:
    normalized = (current_path or "").strip()
    if not normalized:
        return "/homepage"
    return normalized.rstrip("/") or "/"


def render_app_shell(*, current_path: str | None = None) -> None:
    """Render the shared application shell header."""
    normalized_path = _normalize_path(current_path)

    with ui.header().classes("app-shell"), ui.element("div").classes("app-shell__inner"):
        with ui.element("a").props('href="/ui/homepage"').style(
            "display:flex; align-items:center; gap:0.75rem; text-decoration:none; color:inherit;"
        ).classes("app-shell__brand no-wrap"):
            ui.html(VIBESCRIBE_LOGO_SVG).classes("app-shell__brand-mark")
            ui.label("VibeScribe").classes("app-shell__brand-name")

        with ui.element("nav").props('aria-label="Primary navigation"').classes("app-shell__nav"):
            for label, path, icon in NAV_ITEMS:
                _render_nav_button(label=label, path=path, icon=icon, current_path=normalized_path)

        with ui.row().classes("app-shell__actions no-wrap"):
            ui.label("Saved").classes("app-shell__save-state")
            ui.button(icon="more_horiz").props("flat round dense").tooltip("More actions")


def render_navigation_header(*, current_path: str | None = None) -> None:
    """Render the app shell using the legacy page-level entry point."""
    render_app_shell(current_path=current_path)
