<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Toolbox;

final class DesignerToolboxItem
{
    public function __construct(
        private readonly string $type,
        private readonly string $title,
        private readonly string $category,
        private readonly string $icon = '',
        private readonly array $tags = [],
        private readonly bool $favorite = false,
        private readonly int $recentRank = 0,
        private readonly array $metadata = []
    ) {}

    public static function fromComponent(array $component, bool $favorite = false, int $recentRank = 0): self
    {
        return new self(
            (string) ($component['type'] ?? ''),
            (string) ($component['title'] ?? $component['type'] ?? ''),
            (string) ($component['category'] ?? 'custom'),
            (string) ($component['icon'] ?? ''),
            (array) ($component['tags'] ?? []),
            $favorite,
            $recentRank,
            [
                'renderer' => $component['renderer'] ?? '',
                'version' => $component['version'] ?? '1.0.0',
                'description' => $component['description'] ?? '',
            ]
        );
    }

    public function type(): string { return $this->type; }
    public function category(): string { return $this->category; }
    public function favorite(): bool { return $this->favorite; }
    public function recentRank(): int { return $this->recentRank; }

    public function matches(string $query): bool
    {
        $query = strtolower(trim($query));
        if ($query === '') {
            return true;
        }

        $haystack = strtolower($this->type . ' ' . $this->title . ' ' . $this->category . ' ' . implode(' ', $this->tags) . ' ' . ($this->metadata['description'] ?? ''));
        return str_contains($haystack, $query);
    }

    public function toArray(): array
    {
        return [
            'type' => $this->type,
            'title' => $this->title,
            'category' => $this->category,
            'icon' => $this->icon,
            'tags' => $this->tags,
            'favorite' => $this->favorite,
            'recentRank' => $this->recentRank,
            'metadata' => $this->metadata,
            'drag' => [
                'mime' => 'application/x-ppphp-component',
                'payload' => [
                    'type' => $this->type,
                    'source' => 'toolbox',
                ],
            ],
        ];
    }
}
