<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Daylight\Core\Modules\MediaLibrary\Models\Media as MediaModel;
use Illuminate\View\View;
use Livewire\Attributes\Computed;
use Livewire\Component;

class FileItem extends Component
{
    public ?MediaModel $file = null;

    public bool $selectable = false;

    public bool $singleFile = false;

    public array $selectedItems = [];

    #[Computed]
    public function isSelected(): bool
    {
        return $this->file !== null
            && collect($this->selectedItems)->contains(function ($i) {
                $id = is_array($i) ? ($i['id'] ?? 0) : ($i->id ?? 0);

                return (int) $id === (int) $this->file->id;
            });
    }

    public function select(): void
    {
        if (! $this->file) {
            return;
        }

        if ($this->selectable) {
            // In selectable mode, toggle selection
            $this->dispatch('select-file', id: (int) $this->file->id);
        } else {
            // In normal mode, show file information
            $this->dispatch('select-file', id: (int) $this->file->id);
        }
    }

    public function render(): View
    {
        return view('daylight::livewire.media.file-item');
    }
}
