"""
Global navigation bar (the top-level switcher) — UI_TREE §Nav.

A calm tab strip in the status bar: Home · Library · Search · Discover, plus
the gear (door to AAhead Control). Reached by D-pad **Up** from the top content
row; **L/R** moves between tabs, **A** switches, **Down/B** returns to content.
The active tab carries a rose→cyan underline; the focused tab (while the bar
has focus) gets the glow.
"""

from __future__ import annotations

import pygame

from ..design import tokens as t
from ..shared import fonts, icons, render

SAFE = t.Space.SAFE_AREA
H = t.Space.STATUS_BAR_HEIGHT

# tab key, label (None label = a right-cluster icon: bell / gear)
TABS = [("home", "Home"), ("library", "Library"),
        ("search", "Search"), ("discover", "Discover"),
        ("notifications", None), ("settings", None)]
_KEYS = [k for k, _ in TABS]


class NavBar:
    def __init__(self, active: str):
        self.active = active
        self.focused = False
        self.idx = _KEYS.index(active) if active in _KEYS else 0

    def focus(self):
        self.focused = True
        self.idx = _KEYS.index(self.active) if self.active in _KEYS else 0

    def blur(self):
        self.focused = False

    def handle(self, app, action) -> bool:
        """Consume input while the bar is focused. Returns True if consumed."""
        if not self.focused:
            return False
        if action == "left":
            self.idx = max(0, self.idx - 1)
        elif action == "right":
            self.idx = min(len(TABS) - 1, self.idx + 1)
        elif action in ("down", "b"):
            self.focused = False
        elif action == "a":
            self.focused = False
            app.go_tab(_KEYS[self.idx])
        # 'up' and anything else are swallowed while focused
        return True

    def draw(self, surf, *, battery=None, clock=None, wifi=None, bt=None,
             app=None):
        # Live system readings by default; explicit kwargs (or AAHEAD_FAKE_*
        # env vars) override for deterministic screenshots. bt only renders
        # when an HCI adapter is present (honest data — no false donglo).
        if battery is None or clock is None or wifi is None or bt is None:
            from ..shared.system import get_status
            s = get_status()
            if battery is None:
                battery = s.battery
            if clock is None:
                clock = s.clock
            if wifi is None:
                wifi = s.wifi
            if bt is None:
                bt = s.bt
        cy = H // 2
        x = SAFE
        for i, (key, label) in enumerate(TABS):
            if label is None:
                continue
            is_active = (key == self.active)
            is_focus = (self.focused and i == self.idx)
            col = (t.Color.TEXT_PRIMARY if (is_active or is_focus)
                   else t.Color.TEXT_MUTED)
            lab = fonts.render(t.Type.LABEL, label, col)
            if is_focus:
                pad = 6
                r = pygame.Rect(x - pad, cy - 11, lab.get_width() + pad * 2, 22)
                surf.blit(render.gradient_border((r.w, r.h), t.Radius.PILL), r.topleft)
            surf.blit(lab, (x, cy - lab.get_height() // 2))
            if is_active:
                pygame.draw.rect(surf, t.Color.ACCENT_ROSE,
                                 (x, cy + 9, lab.get_width(), 2), border_radius=2)
            x += lab.get_width() + 16

        # right cluster (right→left): gear · bell · clock · battery · bt · wifi
        rx = t.VIEWPORT_WIDTH - SAFE
        gear_focus = (self.focused and _KEYS[self.idx] == "settings")
        gi = icons.icon("ph-gear-six", 15,
                        t.Color.TEXT_PRIMARY if gear_focus else t.Color.TEXT_MUTED)
        rx -= gi.get_width()
        if gear_focus:
            r = pygame.Rect(rx - 4, cy - 11, gi.get_width() + 8, 22)
            surf.blit(render.gradient_border((r.w, r.h), t.Radius.PILL), r.topleft)
        surf.blit(gi, (rx, cy - gi.get_height() // 2))
        rx -= 12

        # bell (notifications) — unread dot when there's actionable news
        bell_focus = (self.focused and _KEYS[self.idx] == "notifications")
        unread = 0
        if app is not None:
            try:
                from ..library import notify
                unread = notify.unread_count(app.catalog, app.library.play_state())
            except Exception:                                  # noqa: BLE001
                unread = 0
        beli = icons.icon("ph-bell", 15,
                          t.Color.TEXT_PRIMARY if (bell_focus or unread) else t.Color.TEXT_MUTED)
        rx -= beli.get_width()
        if bell_focus:
            r = pygame.Rect(rx - 4, cy - 11, beli.get_width() + 8, 22)
            surf.blit(render.gradient_border((r.w, r.h), t.Radius.PILL), r.topleft)
        surf.blit(beli, (rx, cy - beli.get_height() // 2))
        if unread:
            pygame.draw.circle(surf, t.Color.ACCENT_ROSE,
                               (rx + beli.get_width() - 1, cy - 6), 3)
        rx -= 14
        clk = fonts.render(t.Type.MONO, clock, t.Color.TEXT_PRIMARY)
        rx -= clk.get_width(); surf.blit(clk, (rx, cy - clk.get_height() // 2))
        rx -= 12
        pct = fonts.render(t.Type.MONO, str(battery), t.Color.TEXT_SECONDARY)
        rx -= pct.get_width(); surf.blit(pct, (rx, cy - pct.get_height() // 2))
        rx -= 4
        bi = icons.icon("ph-battery-full" if battery >= 80 else "ph-battery-high",
                        13, t.Color.TEXT_SECONDARY)
        rx -= bi.get_width(); surf.blit(bi, (rx, cy - bi.get_height() // 2))
        rx -= 12
        if bt:
            bti = icons.icon("ph-bluetooth", 13, t.Color.TEXT_SECONDARY)
            rx -= bti.get_width()
            surf.blit(bti, (rx, cy - bti.get_height() // 2))
            rx -= 8
        wf = icons.icon("ph-wifi-high" if wifi else "ph-wifi-slash", 13,
                        t.Color.TEXT_SECONDARY)
        rx -= wf.get_width(); surf.blit(wf, (rx, cy - wf.get_height() // 2))
