<?php

namespace Daylight\Core\Livewire\Store\Products;

use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Component;

class AttributeSelector extends Component
{
    public Collection|array $categories = [];

    public Collection|array|null $activeCategories = [];

    public Collection|array $availableAttributes = [];

    public Collection|array|null $activeAttributes = [];

    #[Computed]
    public function generalAttributes(): Collection
    {
        return $this->availableAttributes->filter(function ($attr) {
            return collect($attr['categories'])->pluck('id')->isEmpty();
        });
    }

    #[Computed]
    public function filteredAttributes(): Collection
    {
        return $this->availableAttributes->filter(function ($attr) {
            return collect($attr['categories'])->pluck('id')->intersect($this->activeCategories)->isNotEmpty();
        });
    }

    public function mount(): void
    {
        if ($this->activeAttributes) {
            $this->activeAttributes = collect($this->availableAttributes)
                ->mapWithKeys(function ($attr) {
                    return [
                        $attr['id'] => $this->activeAttributes[$attr['id']] ?? [],
                    ];
                });
        } else {
            $this->activeAttributes = collect($this->availableAttributes->pluck('id'))->map(fn ($a) => []);
        }

        $this->activeCategories = $this->activeCategories ?: collect();
    }

    public function render()
    {
        return view('daylight::livewire.store.products.attribute-selector');
    }
}
