<?php

namespace Filament\Navigation\Concerns;

use Closure;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\View\ComponentAttributeBag;

trait HasExtraSidebarAttributes
{
    /**
     * @var array<array<mixed> | Closure>
     */
    protected array $extraSidebarAttributes = [];

    /**
     * @param  array<mixed> | Closure  $attributes
     */
    public function extraSidebarAttributes(array | Closure $attributes, bool $merge = false): static
    {
        // Security: Attribute values are not escaped when rendered. Never
        // pass unsanitized user input as attribute names or values.

        if ($merge) {
            $this->extraSidebarAttributes[] = $attributes;
        } else {
            $this->extraSidebarAttributes = [$attributes];
        }

        return $this;
    }

    /**
     * @return array<mixed>
     */
    public function getExtraSidebarAttributes(): array
    {
        $temporaryAttributeBag = new FilamentComponentAttributeBag;

        foreach ($this->extraSidebarAttributes as $extraSidebarAttributes) {
            $temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraSidebarAttributes), escape: false);
        }

        return $temporaryAttributeBag->getAttributes();
    }

    public function getExtraSidebarAttributeBag(): ComponentAttributeBag
    {
        return new FilamentComponentAttributeBag($this->getExtraSidebarAttributes());
    }
}
