@props(['name', 'label', 'value' => null, 'preview' => null])

<div x-data="mediaPicker('{{ $value }}', '{{ $preview }}')" class="space-y-2">
    <label class="block text-slate-700 text-sm font-bold">{{ $label }}</label>
    
    <div class="flex items-start gap-4">
        <!-- Preview -->
        <div class="relative group w-32 h-32 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50 flex items-center justify-center overflow-hidden shrink-0">
            <template x-if="previewUrl">
                <img :src="previewUrl" class="w-full h-full object-cover">
            </template>
            <template x-if="!previewUrl">
                <svg class="w-8 h-8 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
            </template>
            
            <div x-show="previewUrl" class="absolute inset-0 bg-slate-900/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <button type="button" @click="clearSelection" class="p-1.5 bg-white text-red-500 rounded-lg shadow-sm hover:scale-110 transition-transform">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                </button>
            </div>
        </div>

        <div class="flex-1 space-y-3">
            <input type="hidden" name="{{ $name }}" :value="selectedPath">
            
            <button type="button" @click="openModal" class="px-5 py-3 bg-white border border-slate-200 text-slate-600 font-bold rounded-xl hover:border-brand-primary hover:text-brand-primary transition shadow-sm flex items-center gap-2 text-sm w-fit">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                Select from Library
            </button>
            <p class="text-[11px] text-slate-400">Select an existing image or upload a new one to use here.</p>
        </div>
    </div>

    <!-- Modal -->
    <div x-show="isOpen" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 z-[100] flex items-center justify-center p-4 md:p-12 overflow-hidden" x-cloak>
        
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="isOpen = false"></div>
        
        <div class="relative bg-white w-full max-w-6xl h-full rounded-3xl shadow-2xl flex flex-col overflow-hidden" @click.stop>
            <!-- Header -->
            <div class="p-6 border-b border-slate-100 flex items-center justify-between shrink-0">
                <h3 class="text-xl font-bold text-slate-900">Select Media</h3>
                <div class="flex items-center gap-4">
                    <input type="file" @change="uploadNew" class="hidden" x-ref="inlineUpload">
                    <button type="button" @click="$refs.inlineUpload.click()" class="bg-brand-primary text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-brand-accent transition">Upload New</button>
                    <button type="button" @click="isOpen = false" class="text-slate-400 hover:text-slate-600 transition">
                        <svg class="w-6 h-6" 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"></path></svg>
                    </button>
                </div>
            </div>

            <!-- Content Area -->
            <div class="flex-1 overflow-y-auto p-6" id="pickerGridContainer">
                <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4" id="pickerGrid">
                    <!-- Items loaded via AJAX -->
                </div>
            </div>

            <!-- Footer -->
            <div class="p-6 border-t border-slate-100 flex items-center justify-end gap-3 shrink-0">
                <button type="button" @click="isOpen = false" class="px-6 py-2.5 text-slate-500 font-bold hover:text-slate-900 transition">Cancel</button>
                <button type="button" @click="confirmSelection" class="px-8 py-2.5 bg-brand-primary text-white font-bold rounded-xl shadow-lg shadow-brand-primary/20 hover:bg-brand-accent transition" :disabled="!tempSelection">Confirm Selection</button>
            </div>
        </div>
    </div>

    <style>
        .media-item-selected {
            @apply ring-4 ring-brand-primary border-brand-primary bg-brand-primary/5;
        }
    </style>
</div>

@once
@push('extra_scripts')
<script>
function mediaPicker(initialPath, initialPreview) {
    return {
        isOpen: false,
        selectedPath: initialPath || '',
        previewUrl: initialPreview || (initialPath ? '{{ asset('') }}' + initialPath : ''),
        tempSelection: null,
        isLoading: false,

        async openModal() {
            this.isOpen = true;
            await this.loadItems();
        },

        async loadItems(url = null) {
            this.isLoading = true;
            const fetchUrl = url || '{{ route('admin.media.index') }}';
            try {
                const response = await fetch(fetchUrl, {
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const html = await response.text();
                
                // We want to replace the whole content area if it includes pagination
                const contentArea = document.getElementById('pickerGridContainer');
                contentArea.innerHTML = html;

                // Hijack pagination links
                contentArea.querySelectorAll('.ajax-pagination a').forEach(link => {
                    link.addEventListener('click', (e) => {
                        e.preventDefault();
                        this.loadItems(link.href);
                    });
                });

                // Make items clickable for selection
                contentArea.querySelectorAll('[data-media-id]').forEach(item => {
                    // Remove existing action overlays
                    const overlay = item.querySelector('.absolute.inset-0');
                    if (overlay) overlay.remove();

                    item.classList.add('cursor-pointer');
                    item.addEventListener('click', () => {
                        contentArea.querySelectorAll('[data-media-id]').forEach(i => i.classList.remove('ring-4', 'ring-brand-primary', 'bg-brand-primary/5'));
                        item.classList.add('ring-4', 'ring-brand-primary', 'bg-brand-primary/5');
                        this.tempSelection = {
                            path: item.getAttribute('data-media-url').replace('{{ asset('') }}', ''),
                            url: item.getAttribute('data-media-url')
                        };
                    });
                });
            } catch (error) {
                console.error('Picker load failed:', error);
            } finally {
                this.isLoading = false;
            }
        },

        async uploadNew(e) {
            const file = e.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('files[]', file);
            formData.append('_token', '{{ csrf_token() }}');

            try {
                this.isLoading = true;
                const response = await fetch('{{ route('admin.media.store') }}', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const result = await response.json();
                if (result.success) {
                    await this.loadItems();
                } else {
                    alert('Upload failed: ' + result.message);
                }
            } catch (error) {
                console.error('Upload failed:', error);
                alert('Upload failed. Please check the console for details.');
            } finally {
                this.isLoading = false;
                e.target.value = ''; // Reset input
            }
        },

        confirmSelection() {
            if (this.tempSelection) {
                this.selectedPath = this.tempSelection.path;
                this.previewUrl = this.tempSelection.url;
                this.isOpen = false;
            }
        },

        clearSelection() {
            this.selectedPath = '';
            this.previewUrl = '';
            this.tempSelection = null;
        }
    }
}
</script>
@endpush
@endonce
