<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Contract;

final class DesignerComponentRegistry
{
    private array $definitions = [];

    public function __construct(array $definitions = [])
    {
        foreach ($definitions as $type => $definition) {
            if (is_array($definition)) {
                $this->register((string) $type, $definition);
            }
        }
    }

    public function register(string $type, array $definition): void
    {
        $type = DesignerJsonSchema::safeId(str_replace('-', '_', $type));
        $this->definitions[$type] = array_replace_recursive([
            'type' => $type,
            'label' => ucwords(str_replace('_', ' ', $type)),
            'category' => 'general',
            'icon' => '',
            'defaults' => [],
            'inspector' => [
                'tabs' => ['properties', 'style', 'events', 'visibility', 'resources', 'advanced'],
            ],
            'parts' => [],
        ], $definition);
    }

    public function has(string $type): bool
    {
        return isset($this->definitions[$this->normalizeType($type)]);
    }

    public function get(string $type): ?array
    {
        return $this->definitions[$this->normalizeType($type)] ?? null;
    }

    public function all(): array
    {
        return $this->definitions;
    }

    public static function defaults(): self
    {
        $registry = new self();

        foreach ([
            'breadcrumb' => ['category' => 'navigation', 'icon' => 'house'],
            'heading' => ['category' => 'content', 'icon' => 'type-h1'],
            'text' => ['category' => 'content', 'icon' => 'text-left'],
            'button' => ['category' => 'actions', 'icon' => 'cursor'],
            'button_group' => ['category' => 'actions', 'icon' => 'collection'],
            'row' => ['category' => 'layout', 'icon' => 'layout-three-columns'],
            'section' => ['category' => 'layout', 'icon' => 'window'],
            'field' => ['category' => 'forms', 'icon' => 'input-cursor-text'],
            'table_grid' => [
                'label' => 'Data Grid',
                'category' => 'data',
                'icon' => 'table',
                'parts' => ['toolbar', 'search', 'columns', 'actions', 'pagination', 'footer'],
            ],
            'pagination' => ['category' => 'data', 'icon' => 'three-dots'],
            'page_size' => ['category' => 'data', 'icon' => 'list-ol'],
            'validation_summary' => ['category' => 'forms', 'icon' => 'exclamation-triangle'],
        ] as $type => $definition) {
            $registry->register($type, $definition);
        }

        return $registry;
    }

    private function normalizeType(string $type): string
    {
        return DesignerJsonSchema::safeId(str_replace('-', '_', $type));
    }
}
