<?php

namespace App\Support;

class CatalogThemeRegistry
{
    /**
     * @return list<array{key: string, label: string, body_class: string}>
     */
    public static function forTemplate(string $template): array
    {
        $themes = config('catalog-themes.'.$template, []);

        if (! is_array($themes) || $themes === []) {
            return [];
        }

        $options = [];

        foreach ($themes as $key => $definition) {
            if (! is_string($key) || ! is_array($definition)) {
                continue;
            }

            $options[] = [
                'key' => $key,
                'label' => (string) ($definition['label'] ?? $key),
                'body_class' => (string) ($definition['body_class'] ?? ''),
            ];
        }

        return $options;
    }

    public static function isValidForTemplate(string $template, string $themeKey): bool
    {
        foreach (self::forTemplate($template) as $theme) {
            if ($theme['key'] === $themeKey) {
                return true;
            }
        }

        return false;
    }

    public static function label(string $template, ?string $themeKey): string
    {
        $themeKey = trim((string) $themeKey);

        if ($themeKey === '') {
            return 'Default';
        }

        foreach (self::forTemplate($template) as $theme) {
            if ($theme['key'] === $themeKey) {
                return $theme['label'];
            }
        }

        return $themeKey;
    }

    public static function bodyClass(string $template, string $themeKey): string
    {
        foreach (self::forTemplate($template) as $theme) {
            if ($theme['key'] === $themeKey) {
                return $theme['body_class'];
            }
        }

        return '';
    }
}
