<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Component;

final class DesignerComponentDefinition
{
    public function __construct(
        private readonly string $type,
        private readonly string $title,
        private readonly string $category,
        private readonly string $icon = '',
        private readonly string $description = '',
        private readonly string $version = '1.0.0',
        private readonly array $tags = [],
        private readonly array $properties = [],
        private readonly array $defaultProps = [],
        private readonly array $events = [],
        private readonly array $slots = [],
        private readonly string $renderer = ''
    ) {}

    public static function create(string $type, string $title, string $category, array $options = []): self
    {
        return new self(
            $type,
            $title,
            $category,
            (string)($options['icon'] ?? ''),
            (string)($options['description'] ?? ''),
            (string)($options['version'] ?? '1.0.0'),
            (array)($options['tags'] ?? []),
            (array)($options['properties'] ?? []),
            (array)($options['defaultProps'] ?? []),
            (array)($options['events'] ?? []),
            (array)($options['slots'] ?? []),
            (string)($options['renderer'] ?? $type)
        );
    }

    public function type(): string { return $this->type; }
    public function title(): string { return $this->title; }
    public function category(): string { return $this->category; }
    public function renderer(): string { return $this->renderer !== '' ? $this->renderer : $this->type; }

    public function defaultProperties(): array
    {
        $props = $this->defaultProps;
        foreach ($this->properties as $property) {
            $name = (string)($property['name'] ?? '');
            if ($name !== '' && !array_key_exists($name, $props)) {
                $props[$name] = $property['default'] ?? null;
            }
        }
        return $props;
    }

    public function toArray(): array
    {
        return [
            'type' => $this->type,
            'title' => $this->title,
            'category' => $this->category,
            'icon' => $this->icon,
            'description' => $this->description,
            'version' => $this->version,
            'tags' => $this->tags,
            'properties' => $this->properties,
            'defaultProps' => $this->defaultProperties(),
            'events' => $this->events,
            'slots' => $this->slots,
            'renderer' => $this->renderer(),
        ];
    }
}
