<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Toolbox;

final class DesignerToolboxState
{
    public function __construct(
        private readonly array $favorites = [],
        private readonly array $recent = [],
        private readonly array $collapsedGroups = [],
        private readonly string $query = ''
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            (array) ($data['favorites'] ?? []),
            (array) ($data['recent'] ?? []),
            (array) ($data['collapsedGroups'] ?? []),
            (string) ($data['query'] ?? '')
        );
    }

    public function favorites(): array { return $this->favorites; }
    public function recent(): array { return $this->recent; }
    public function query(): string { return $this->query; }

    public function isFavorite(string $type): bool
    {
        return in_array($type, $this->favorites, true);
    }

    public function recentRank(string $type): int
    {
        $index = array_search($type, $this->recent, true);
        return $index === false ? 0 : (count($this->recent) - (int) $index);
    }

    public function toArray(): array
    {
        return [
            'favorites' => $this->favorites,
            'recent' => $this->recent,
            'collapsedGroups' => $this->collapsedGroups,
            'query' => $this->query,
        ];
    }
}
