<div x-data="{ uploading: false, progress: 0 }" x-on:livewire-upload-start="uploading = true" x-on:livewire-upload-finish="uploading = false"
    x-on:livewire-upload-cancel="uploading = false" x-on:livewire-upload-error="uploading = false"
    x-on:livewire-upload-progress="progress = $event.detail.progress" class="space-y-5">
    <label class="block mb-2 text-sm font-medium text-gray-700 dark:text-gray-200">
        Optional Attachments (5 Max)
    </label>
    <!-- File Input -->
    <label
        class="flex flex-col items-center justify-center p-6 border-2 border-dashed rounded-lg cursor-pointer hover:border-blue-500 text-center">
        Click or drag files here
        <span class="text-sm text-gray-400 mt-1">
            JPG, PNG, WEBP, PDF, DOC, DOCX, XLS, XLSX (max 5MB each, max 5 files)
        </span>
        <input type="file" multiple wire:model="attachments"
            accept=".jpg,.jpeg,.png,.webp,.pdf,.doc,.docx,.xls,.xlsx" class="hidden">
    </label>

    <!-- Upload progress -->
    <div x-show="uploading">
        <progress max="100" x-bind:value="progress" class="w-full h-2 rounded bg-gray-200"></progress>
        <button type="button" wire:click="$cancelUpload('attachments')"
            class="mt-2 px-3 py-1 bg-red-600 text-white rounded">Cancel Upload</button>
    </div>

    <!-- Previews -->
    <div class="flex flex-wrap gap-3 mt-4">
        @foreach ($attachments as $index => $file)
            <div wire:key="attachment_{{ $index }}"
                class="relative w-28 h-28 border rounded p-2 flex flex-col items-center justify-center">

                @if (str_contains($file->getMimeType(), 'image'))
                    <img src="{{ $file->temporaryUrl() }}" class="w-full h-full object-cover rounded">
                @else
                    <div class="text-sm text-center truncate w-full">{{ $file->getClientOriginalName() }}</div>
                @endif

                <button type="button" wire:click="removeAttachment({{ $index }})"
                    class="absolute top-1 right-1 bg-red-600 text-white w-5 h-5 flex items-center justify-center rounded-full">&times;</button>
            </div>
        @endforeach
    </div>

    <!-- Validation errors -->
    @error('attachments')
        <p class="text-red-600 text-sm">{{ $message }}</p>
    @enderror
    @error('attachments.*')
        <p class="text-red-600 text-sm">{{ $message }}</p>
    @enderror
</div>
