<div 
    x-data="{
        selectedFiles: [],
        isDragging: false,
        maxFiles: @entangle('maxFileUploads'),
        errorMessage: '',
        
        init() {
            // Listen for when Livewire finishes processing
            this.$watch('$wire.uploadingFiles', (files, oldFiles) => {
                if (files.length > 0) {
                    // Merge Livewire updates with local state to preserve immediate feedback
                    this.selectedFiles = files.map((file, index) => ({
                        ...file,
                        // Preserve existing data if available
                        ...(this.selectedFiles[index] || {})
                    }));
                    
                    // Dispatch upload progress to media library
                    window.dispatchEvent(new CustomEvent('upload-progress-update', {
                        detail: { files: this.selectedFiles }
                    }));
                    
                    // Check if all uploads are complete
                    const allComplete = files.every(f => f.status === 'success' || f.status === 'error');
                    if (allComplete) {
                        // Clear after a short delay to show completion status
                        setTimeout(() => {
                            this.selectedFiles = [];
                            // Clear from media library too
                            window.dispatchEvent(new CustomEvent('upload-progress-update', {
                                detail: { files: [] }
                            }));
                        }, 2000);
                    }
                }
            });
        },
        
        validateFileCount(files) {
            if (files.length > this.maxFiles) {
                this.errorMessage = `You can only upload ${this.maxFiles} files at once. Please select fewer files.`;
                setTimeout(() => this.errorMessage = '', 5000);
                return false;
            }
            this.errorMessage = '';
            return true;
        },
        
        handleFileSelect(event) {
            const files = event.target.files;
            if (!this.validateFileCount(files)) {
                event.target.value = ''; // Clear the input
                return;
            }
            this.showFilesImmediately(files);
        },
        
        handleDrop(event) {
            this.isDragging = false;
            const files = event.dataTransfer.files;
            
            if (!this.validateFileCount(files)) {
                return;
            }
            
            // Set files to input element so Livewire can process them
            this.$refs.fileInput.files = files;
            
            this.showFilesImmediately(files);
        },
        
        handleDroppedFilesFromLibrary(event) {
            // Handle files dropped directly on the media library (not in modal)
            const files = event.detail.files;
            if (!files || files.length === 0) return;
            
            if (!this.validateFileCount(files)) {
                return;
            }
            
            // IMMEDIATELY show pending files in the media library
            const pendingFiles = files.map(file => ({
                name: file.name,
                size: file.size,
                status: 'pending',
                progress: 0,
                error: null
            }));
            
            // Dispatch to media library BEFORE Livewire processes
            window.dispatchEvent(new CustomEvent('upload-progress-update', {
                detail: { files: pendingFiles }
            }));
            
            // Set files to the drop zone input
            const dataTransfer = new DataTransfer();
            for (let i = 0; i < files.length; i++) {
                dataTransfer.items.add(files[i]);
            }
            this.$refs.dropZoneInput.files = dataTransfer.files;
            
            // Manually trigger change event to let Livewire know
            this.$refs.dropZoneInput.dispatchEvent(new Event('change', { bubbles: true }));
            
            this.showFilesImmediately(files);
        },
        
        showFilesImmediately(files) {
            if (!files || files.length === 0) return;
            
            // For modal uploads: show skeleton first, then details
            // For library drops: show details immediately
            const isModalUpload = this.$wire.showModal;
            
            if (isModalUpload) {
                // Show skeleton loaders immediately (without file details)
                this.selectedFiles = Array.from(files).map(file => ({
                    status: 'pending',
                    progress: 0,
                    error: null
                    // Note: name and size are NOT set yet, so skeleton shows
                }));
                
                // After a brief moment, populate with actual file data
                setTimeout(() => {
                    this.selectedFiles = Array.from(files).map(file => ({
                        name: file.name,
                        size: file.size,
                        status: 'pending',
                        progress: 0,
                        error: null
                    }));
                }, 100);
            } else {
                // For library drops: show actual file info immediately with pending state
                this.selectedFiles = Array.from(files).map(file => ({
                    name: file.name,
                    size: file.size,
                    status: 'pending',
                    progress: 0,
                    error: null
                }));
            }
        }
    }"
    x-on:uploads-complete.window="$wire.closeModalAfterUpload(); selectedFiles = []"
    x-on:files-dropped.window="handleDroppedFilesFromLibrary($event)"
>
    <!-- Hidden input for drag-and-drop directly on media library -->
    <input
        type="file"
        wire:model="uploads"
        x-ref="dropZoneInput"
        multiple
        class="hidden"
    >
    <!-- Upload Modal -->
    <template x-teleport="body">
        <div x-cloak x-show="$wire.showModal" class="fixed inset-0 z-50" style="display: none;">
            <div class="fixed inset-0 overflow-y-auto px-4 py-6 sm:px-0 z-50">
                <div class="flex items-center min-h-full">
                    <!-- Backdrop -->
                    <div 
                        class="fixed inset-0 bg-gray-500 opacity-75 transition-opacity"
                        x-on:click="$wire.closeModal()"
                        x-show="$wire.showModal"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                    ></div>

                    <!-- Modal Content -->
                    <div
                        class="relative bg-white rounded-lg shadow-xl transform transition-all sm:w-full sm:mx-auto sm:max-w-2xl z-10"
                        x-show="$wire.showModal"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                    >
                        <div class="bg-sky-600 px-6 py-4 rounded-t-lg">
                            <div class="flex items-start justify-between">
                                <h2 class="text-lg font-semibold text-white">{{ __('daylight::media.upload_files') }}</h2>
                                <button x-on:click.prevent="$wire.closeModal(); selectedFiles = [];" type="button" class="text-white hover:text-opacity-75">
                                    <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>
                        </div>

                        <div class="p-6">
                            <!-- Error Message -->
                            <template x-if="errorMessage">
                                <div class="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                                    <div class="flex">
                                        <svg class="h-5 w-5 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                                        </svg>
                                        <p class="ml-3 text-sm text-red-800" x-text="errorMessage"></p>
                                    </div>
                                </div>
                            </template>
                            
                            <template x-if="selectedFiles.length > 0">
                                <div>
                                    <!-- Upload Progress List -->
                                    <div class="space-y-3 mb-6">
                                        <template x-for="(fileInfo, index) in selectedFiles" :key="index">
                                            <div 
                                                class="border rounded-lg overflow-hidden transition-colors"
                                                :class="{
                                                    'bg-green-50 border-green-200': fileInfo.status === 'success',
                                                    'bg-red-50 border-red-200': fileInfo.status === 'error',
                                                    'bg-white border-gray-200': fileInfo.status === 'uploading' || fileInfo.status === 'pending'
                                                }"
                                            >
                                                <div class="flex items-start gap-3 p-3">
                                                    <!-- Skeleton/Icon -->
                                                    <div class="flex-shrink-0 mt-0.5">
                                                        <template x-if="fileInfo.status === 'pending'">
                                                            <div class="w-10 h-10 bg-gray-200 rounded animate-pulse"></div>
                                                        </template>
                                                        <template x-if="fileInfo.status === 'uploading'">
                                                            <div class="w-10 h-10 bg-blue-100 rounded flex items-center justify-center">
                                                                <svg class="animate-spin h-5 w-5 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                                </svg>
                                                            </div>
                                                        </template>
                                                        <template x-if="fileInfo.status === 'success'">
                                                            <div class="w-10 h-10 bg-green-100 rounded flex items-center justify-center">
                                                                <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                                                </svg>
                                                            </div>
                                                        </template>
                                                        <template x-if="fileInfo.status === 'error'">
                                                            <div class="w-10 h-10 bg-red-100 rounded flex items-center justify-center">
                                                                <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                                                </svg>
                                                            </div>
                                                        </template>
                                                    </div>
                                                    
                                                    <!-- File Info -->
                                                    <div class="flex-1 min-w-0">
                                                        <!-- Skeleton loader for pending state -->
                                                        <template x-if="fileInfo.status === 'pending' && !fileInfo.name">
                                                            <div class="space-y-2">
                                                                <div class="h-4 bg-gray-200 rounded w-3/4 animate-pulse"></div>
                                                                <div class="h-3 bg-gray-200 rounded w-1/4 animate-pulse"></div>
                                                            </div>
                                                        </template>
                                                        <!-- Show actual file info -->
                                                        <template x-if="fileInfo.name">
                                                            <div>
                                                                <p class="text-sm font-medium text-gray-900 truncate" x-text="fileInfo.name"></p>
                                                                <div class="flex items-center gap-2 mt-1">
                                                                    <p class="text-xs text-gray-500" x-text="(fileInfo.size / 1024).toFixed(1) + ' KB'"></p>
                                                                    <template x-if="fileInfo.status === 'pending'">
                                                                        <span class="text-xs text-gray-500">• {{ __('daylight::media.waiting') }}</span>
                                                                    </template>
                                                                    <template x-if="fileInfo.status === 'uploading'">
                                                                        <span class="text-xs text-blue-700" x-text="'• ' + fileInfo.progress + '%'"></span>
                                                                    </template>
                                                                    <template x-if="fileInfo.status === 'success'">
                                                                        <span class="text-xs text-green-700">• {{ __('daylight::media.upload_complete') }}</span>
                                                                    </template>
                                                                    <template x-if="fileInfo.status === 'error'">
                                                                        <span class="text-xs text-red-700" x-text="'• ' + fileInfo.error"></span>
                                                                    </template>
                                                                </div>
                                                            </div>
                                                        </template>
                                                    </div>
                                                </div>
                                                
                                                <!-- Progress Bar -->
                                                <template x-if="fileInfo.status === 'uploading' || fileInfo.status === 'pending'">
                                                    <div class="h-1 bg-gray-200 relative overflow-hidden">
                                                        <div 
                                                            class="absolute inset-y-0 left-0 transition-all duration-300 ease-out"
                                                            :class="{
                                                                'bg-blue-500': fileInfo.status === 'uploading',
                                                                'bg-gray-300': fileInfo.status === 'pending'
                                                            }"
                                                            :style="'width: ' + (fileInfo.progress || 0) + '%'"
                                                        ></div>
                                                        <template x-if="fileInfo.status === 'pending'">
                                                            <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent animate-shimmer" style="animation: shimmer 2s infinite;"></div>
                                                        </template>
                                                    </div>
                                                </template>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </template>

                            <template x-if="selectedFiles.length === 0">
                                <!-- Drag and Drop Area -->
                                <div
                                    class="border-2 border-dashed rounded-lg p-12 text-center transition"
                                    :class="isDragging ? 'border-sky-500 bg-sky-50' : 'border-gray-300'"
                                    x-on:dragover.prevent="isDragging = true"
                                    x-on:dragleave.prevent="isDragging = false"
                                    x-on:drop.prevent="handleDrop($event)"
                                >
                                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                                    </svg>
                                    <p class="mt-2 text-sm text-gray-600">{{ __('daylight::media.drag_drop_files') }}</p>
                                    <p class="mt-1 text-xs text-gray-500">{{ __('daylight::media.or') }}</p>
                                    
                                    <div class="mt-4">
                                        <input
                                            type="file"
                                            wire:model="uploads"
                                            x-ref="fileInput"
                                            multiple
                                            id="file-upload"
                                            class="hidden"
                                            x-on:change="handleFileSelect($event)"
                                        >
                                        <label for="file-upload" class="cursor-pointer">
                                            <x-daylight::buttons.primary type="button" x-on:click.prevent="$refs.fileInput.click()">
                                                {{ __('daylight::media.select_files') }}
                                            </x-daylight::buttons.primary>
                                        </label>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>

