<?php

declare(strict_types=1);

namespace PpPhp\Core\IconManager;

use PpPhp\Core\Resources\ResourceRegistry;

final class IconManager
{
    /**
     * Returns all registered icon resource packs.
     */
    public static function packs(): array
    {
        return ResourceRegistry::icons();
    }

    /**
     * Collect all CSS and JS assets from icon packs.
     */
    public static function assets(): array
    {
        $assets = [
            'css' => [],
            'js' => [],
        ];

        foreach (self::packs() as $pack) {
            foreach (($pack['assets']['css'] ?? []) as $css) {
                $assets['css'][] = $css;
            }

            foreach (($pack['assets']['js'] ?? []) as $js) {
                $assets['js'][] = $js;
            }
        }

        $assets['css'] = array_values(array_unique($assets['css']));
        $assets['js'] = array_values(array_unique($assets['js']));

        return $assets;
    }

    /**
     * Search across one or all icon packs.
     *
     * @return array<int, IconDefinition>
     */
    public static function search(
        string $query,
        ?string $packId = null,
        int $limit = 100
    ): array {
        $results = [];

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

            $class = $pack['class'] ?? null;

            if (!is_string($class) || !method_exists($class, 'icons')) {
                continue;
            }

            $icons = $class::icons();

            foreach (IconSearch::search($icons, $query, $limit) as $icon) {
                $results[] = $icon;

                if (count($results) >= $limit) {
                    return $results;
                }
            }
        }

        return $results;
    }

    public static function find(string $name, ?string $packId = null): ?IconDefinition
    {
        return (new IconRuntime())->find($name, $packId);
    }

    public static function picker(string $query = '', ?string $packId = null, int $limit = 100): array
    {
        return (new IconRuntime())->picker($query, $packId, $limit);
    }

    public static function stats(): array
    {
        return (new IconRuntime())->stats();
    }
}
