<?php
declare(strict_types=1);

namespace PpPhp\Core\IconManager;

final class IconRuntime
{
    public function packs(): array
    {
        return IconManager::packs();
    }

    /** @return array<int, IconDefinition> */
    public function icons(?string $packId = null, int $limit = 0): array
    {
        $icons = [];

        foreach ($this->packs() as $pack) {
            if ($packId !== null && ($pack['id'] ?? '') !== $packId) {
                continue;
            }

            $class = $pack['class'] ?? null;
            if (!is_string($class) || !method_exists($class, 'icons')) {
                continue;
            }

            foreach ($class::icons() as $icon) {
                if (!$icon instanceof IconDefinition) {
                    continue;
                }

                $icons[] = $icon;

                if ($limit > 0 && count($icons) >= $limit) {
                    return $icons;
                }
            }
        }

        return $icons;
    }

    /** @return array<int, IconDefinition> */
    public function search(string $query, ?string $packId = null, int $limit = 100): array
    {
        return IconManager::search($query, $packId, $limit);
    }

    public function find(string $name, ?string $packId = null): ?IconDefinition
    {
        foreach ($this->icons($packId) as $icon) {
            if ($icon->name === $name || $icon->pack . ':' . $icon->name === $name || $icon->className === $name) {
                return $icon;
            }
        }

        return null;
    }

    public function picker(string $query = '', ?string $packId = null, int $limit = 100): array
    {
        $icons = $this->search($query, $packId, $limit);
        $groups = [];

        foreach ($icons as $icon) {
            $groups[$icon->pack] ??= [
                'pack' => $icon->pack,
                'family' => $icon->family,
                'icons' => [],
            ];

            $groups[$icon->pack]['icons'][] = $icon->toArray();
        }

        return [
            'query' => $query,
            'pack' => $packId,
            'groups' => array_values($groups),
            'total' => count($icons),
        ];
    }

    public function stats(): array
    {
        $packs = $this->packs();
        $icons = $this->icons();
        $fontIcons = 0;
        $svgIcons = 0;

        foreach ($icons as $icon) {
            if ($icon->family === 'custom-svg' || $icon->style === 'svg') {
                $svgIcons++;
                continue;
            }

            $fontIcons++;
        }

        return [
            'packs' => count($packs),
            'icons' => count($icons),
            'fontIcons' => $fontIcons,
            'svgIcons' => $svgIcons,
            'families' => array_values(array_unique(array_map(static fn (IconDefinition $icon): string => $icon->family, $icons))),
        ];
    }
}
