"""
icons.py — Lazy singleton for the IconsShadow-32 atlas.

Provides a single shared IconAtlas instance loaded on first use.
All scenes import ``get_icon()`` rather than constructing their own atlas.

Usage
-----
::

    from helpers.icons import get_icon, ICO_BACK, ICO_EDIT

    back_surf = get_icon(ICO_BACK, size=18)
"""

from __future__ import annotations

from typing import Optional

import pygame

# ---------------------------------------------------------------------------
# Named icon indices (IconsShadow-32)
# ---------------------------------------------------------------------------

ICO_BACK   = 16
ICO_PLAY   = 99
ICO_DELETE = 72
ICO_NEW    = 74
ICO_FOLDER = 20
ICO_EDIT   = 50   # adjust if the in-game icon looks wrong

# ---------------------------------------------------------------------------
# Lazy singleton
# ---------------------------------------------------------------------------

_atlas = None   # None = not yet loaded; False = load failed


def get_icon(idx: int, size: int = 20) -> Optional[pygame.Surface]:
    """Return icon *idx* at *size*×*size* px, or None if the atlas is unavailable."""
    global _atlas
    if _atlas is None:
        try:
            from helpers.spritesheet import IconAtlas
            _atlas = IconAtlas("IconsShadow-32.png", "IconsShadow-32.json")
        except Exception:
            _atlas = False  # type: ignore[assignment]
    if not _atlas:
        return None
    try:
        return _atlas.icon(idx, size)  # type: ignore[union-attr]
    except Exception:
        return None
