"""
Fullscreen image viewer — screenshots & art at full size.

Opened from the game card's media section. L/R steps between images, B closes.
"""

from __future__ import annotations

import pygame

from ..design import tokens as t
from ..shared import fonts
from ..widgets import chrome, images

BODY_BOT = t.VIEWPORT_HEIGHT - t.Space.FOOTER_HINT_HEIGHT


class ImageViewer:
    name = "image_viewer"

    def __init__(self, app, paths, index=0, captions=None):
        self.app = app
        self.paths = list(paths)
        self.index = max(0, min(index, len(self.paths) - 1)) if self.paths else 0
        self.captions = captions or []

    def on_action(self, action):
        if action in ("b", "a"):
            self.app.pop()
        elif action in ("left", "l") and self.paths:
            self.index = (self.index - 1) % len(self.paths)   # wrap
        elif action in ("right", "r") and self.paths:
            self.index = (self.index + 1) % len(self.paths)    # wrap

    def update(self, dt_ms):
        pass

    def draw(self, surf):
        surf.fill((0, 0, 0))
        if not self.paths:
            msg = fonts.render(t.Type.TITLE, "No image", t.Color.TEXT_MUTED)
            surf.blit(msg, ((t.VIEWPORT_WIDTH - msg.get_width()) // 2, 220))
        else:
            # full 640×480 so pixel-art snaps land on an integer nearest ×factor
            img = images.screenshot_fit(self.paths[self.index],
                                        t.VIEWPORT_WIDTH, t.VIEWPORT_HEIGHT)
            surf.blit(img, (0, 0))
            # translucent strip so the footer/caption stay legible over the image
            strip = pygame.Surface((t.VIEWPORT_WIDTH, t.Space.FOOTER_HINT_HEIGHT),
                                   pygame.SRCALPHA)
            strip.fill(t.with_alpha(t.Color.BG_DEEP, 0.7))
            surf.blit(strip, (0, BODY_BOT))
            cap = self.captions[self.index] if self.index < len(self.captions) else ""
            counter = f"{self.index + 1} / {len(self.paths)}"
            label = f"{cap}    {counter}" if cap else counter
            ls = fonts.render(t.Type.MONO, label, t.Color.TEXT_SECONDARY)
            bg = pygame.Surface((ls.get_width() + 20, ls.get_height() + 10),
                                pygame.SRCALPHA)
            bg.fill(t.with_alpha(t.Color.BG_DEEP, 0.6))
            surf.blit(bg, (t.VIEWPORT_WIDTH - bg.get_width() - 12,
                           BODY_BOT - bg.get_height() - 12))
            surf.blit(ls, (t.VIEWPORT_WIDTH - ls.get_width() - 22,
                           BODY_BOT - ls.get_height() - 17))
        hints = [("B", "Close")]
        if len(self.paths) > 1:
            hints.append(("L1/R1", "Browse"))
        chrome.footer_hints(surf, hints)
