"""
Persistent chrome: the quiet status bar (brand + wifi/battery/clock + the
gear that is the door to AAhead Control) and the footer gamepad legend.
Near-black, hairline only — it recedes so the art is the hero.
"""

from __future__ import annotations

import pygame

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

SAFE = t.Space.SAFE_AREA
STATUS_H = t.Space.STATUS_BAR_HEIGHT
FOOTER_H = t.Space.FOOTER_HINT_HEIGHT


def _battery_icon(level: int) -> str:
    return ("ph-battery-full" if level >= 80 else
            "ph-battery-high" if level >= 55 else
            "ph-battery-medium" if level >= 30 else
            "ph-battery-low")


def status_bar(surf, *, brand="AAhead", title=None, back=None,
               wifi=None, bt=None, battery=None, clock=None, gear=True,
               gear_focused=False):
    """
    Draw the top status bar. `title`+`back` (str) shows a back-chevron + label
    instead of the brand (used on the game card). Otherwise the brand wordmark.

    wifi/bt/battery/clock default to LIVE system readings
    (`shared.system.get_status()`). For deterministic screenshots set
    `AAHEAD_FAKE_CLOCK`/`AAHEAD_FAKE_BATTERY`/`AAHEAD_FAKE_WIFI`/`AAHEAD_FAKE_BT`
    or pass explicit values.

    The BT icon only renders when an HCI adapter is present (honest data —
    nothing shown when there's no donglo plugged in).
    """
    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 = STATUS_H // 2
    # ── left ──
    if back is not None:
        chev = icons.icon("ph-caret-left", 14, t.Color.TEXT_SECONDARY)
        surf.blit(chev, (SAFE, cy - chev.get_height() // 2))
        lab = fonts.render(t.Type.CAPTION, back, t.Color.TEXT_SECONDARY)
        surf.blit(lab, (SAFE + chev.get_width() + 6, cy - lab.get_height() // 2))
    else:
        bw = fonts.render(t.Type.EYEBROW, brand, t.Color.TEXT_SECONDARY, upper=True)
        surf.blit(bw, (SAFE, cy - bw.get_height() // 2))

    # ── right cluster (right→left) ──
    rx = t.VIEWPORT_WIDTH - SAFE
    if gear:
        gi = icons.icon("ph-gear-six", 15,
                        t.Color.TEXT_PRIMARY if gear_focused else t.Color.TEXT_MUTED)
        rx -= gi.get_width()
        if gear_focused:
            r = pygame.Rect(rx - 4, cy - 11, gi.get_width() + 8, 22)
            pygame.draw.rect(surf, t.Color.SURFACE_ELEVATED, r, border_radius=999)
        surf.blit(gi, (rx, cy - gi.get_height() // 2))
        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 -= 14
    # battery: icon + pct
    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(_battery_icon(battery), 13, t.Color.TEXT_SECONDARY)
    rx -= bi.get_width()
    surf.blit(bi, (rx, cy - bi.get_height() // 2))
    rx -= 12
    # BT icon — only when an HCI adapter is actually present (honest data)
    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
    wi = icons.icon("ph-wifi-high" if wifi else "ph-wifi-slash", 13,
                    t.Color.TEXT_SECONDARY if wifi else t.Color.TEXT_MUTED)
    rx -= wi.get_width()
    surf.blit(wi, (rx, cy - wi.get_height() // 2))


def gp_glyph(letter: str) -> pygame.Surface:
    """Ringed gamepad glyph. Single chars get a round chip; multi-char keys
    (L1, R1, L1/R1, RS) get a pill so they actually fit the label."""
    lab = fonts.render(t.Type.GP, letter, t.Color.TEXT_SECONDARY)
    d = 19
    if len(letter) <= 1:
        s = pygame.Surface((d, d), pygame.SRCALPHA)
        pygame.draw.circle(s, t.Color.TEXT_MUTED, (d // 2, d // 2), d // 2 - 1, 1)
        s.blit(lab, ((d - lab.get_width()) // 2, (d - lab.get_height()) // 2))
        return s
    w = lab.get_width() + 12
    s = pygame.Surface((w, d), pygame.SRCALPHA)
    pygame.draw.rect(s, t.Color.TEXT_MUTED, (0, 0, w, d), width=1, border_radius=d // 2)
    s.blit(lab, ((w - lab.get_width()) // 2, (d - lab.get_height()) // 2))
    return s


def footer_hints(surf, hints: list[tuple[str, str]], *, align="left"):
    """hints = [("A","Play"), ("Y","Search"), ...]. Hairline above, near-black."""
    y0 = t.VIEWPORT_HEIGHT - FOOTER_H
    pygame.draw.line(surf, t.Color.BORDER_SOFT, (0, y0), (t.VIEWPORT_WIDTH, y0), 1)
    cy = y0 + FOOTER_H // 2
    items = [(gp_glyph(g), fonts.render(t.Type.CAPTION, l, t.Color.TEXT_SECONDARY))
             for g, l in hints]
    gap_inner, gap_outer = 7, t.Space.XL
    total = sum(g.get_width() + gap_inner + l.get_width() for g, l in items)
    total += gap_outer * (len(items) - 1)
    x = SAFE if align == "left" else (t.VIEWPORT_WIDTH - total) // 2
    for g, l in items:
        surf.blit(g, (x, cy - g.get_height() // 2))
        x += g.get_width() + gap_inner
        surf.blit(l, (x, cy - l.get_height() // 2))
        x += l.get_width() + gap_outer
