<div
    x-data="{
        showMediaLibrary: false,
        instanceId: @js($instanceId),
    }"
    x-on:open-media-library.window="
        if ($event.detail.instanceId === instanceId) {
            showMediaLibrary = true;
        }
    "
    x-on:close-media-library.window="showMediaLibrary = false"
    x-on:media-selector-close.window="showMediaLibrary = false"
    x-on:keydown.escape.window="if (showMediaLibrary) { showMediaLibrary = false; $event.stopPropagation(); }"
>
    @if(count($selectedMedia) > 0)
        <ul
            class="mb-4 {{ $displayType === 'gallery' ? 'flex gap-2 flex-wrap' : 'lg:max-w-xl space-y-4' }}"
            x-data="{
                draggedItem: null,
                draggedOverItem: null,
                dragStart(index) {
                    this.draggedItem = index;
                },
                dragOver(index) {
                    this.draggedOverItem = index;
                },
                drop(index) {
                    if (this.draggedItem !== null && this.draggedItem !== index) {
                        $wire.reorderItems(this.draggedItem, index);
                    }
                    this.draggedItem = null;
                    this.draggedOverItem = null;
                }
            }"
        >
            @foreach($selectedMedia as $index => $item)
                <li
                    draggable="true"
                    x-on:dragstart="dragStart({{ $index }})"
                    x-on:dragover.prevent="dragOver({{ $index }})"
                    x-on:drop.prevent="drop({{ $index }})"
                    x-on:dragend="draggedItem = null; draggedOverItem = null"
                    :class="{ 
                        'opacity-50': draggedItem === {{ $index }},
                        'ring-2 ring-sky-500': draggedOverItem === {{ $index }}
                    }"
                    class="group relative cursor-move {{ $displayType === 'gallery' ? 'bg-gray-50 rounded-lg' : '' }}"
                >
                    @php
                        $itemType = is_array($item) ? ($item['type'] ?? '') : ($item->type ?? '');
                        $itemUrl = is_array($item) ? ($item['url'] ?? '') : ($item->url ?? '');
                        $itemName = is_array($item) ? ($item['name'] ?? '') : ($item->name ?? '');
                    @endphp
                    
                    @if($displayType === 'gallery' && in_array($itemType, ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp']))
                        <img
                            src="{{ $itemUrl }}"
                            alt="{{ $itemName }}"
                            class="w-24 h-24 rounded-lg border object-cover pointer-events-none"
                        >
                    @elseif(in_array($itemType, ['video/mp4', 'video/quicktime']))
                        <div class="w-24 h-24 rounded-lg border relative flex items-center justify-center">
                            <div class="absolute bg-black bg-opacity-50 inset-0 flex items-center justify-center backdrop-blur rounded-lg pointer-events-none">
                                <svg class="w-6 h-6 text-white" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z"></path>
                                </svg>
                            </div>
                            <img
                                src="{{ $itemUrl }}"
                                alt="{{ $itemName }}"
                                class="w-full h-full rounded-lg object-cover pointer-events-none"
                            >
                        </div>
                    @else
                        <div class="border w-full p-3 text-gray-600 rounded-lg text-sm flex items-center pointer-events-none">
                            <svg class="w-4 h-4 mr-2 text-gray-600" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="m18.375 12.739-7.693 7.693a4.5 4.5 0 0 1-6.364-6.364l10.94-10.94A3 3 0 1 1 19.5 7.372L8.552 18.32m.009-.01-.01.01m5.699-9.941-7.81 7.81a1.5 1.5 0 0 0 2.112 2.13"></path>
                            </svg>
                            {{ $itemName }}
                        </div>
                    @endif

                    <button
                        wire:click="removeItem({{ $index }})"
                        type="button"
                        class="group-hover:opacity-100 opacity-0 transition absolute top-2 right-2 bg-red-600 p-2 rounded-full hover:bg-red-500 z-10"
                        x-on:click.stop
                    >
                        <svg class="text-white w-3 h-3 pointer-events-none" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"></path>
                        </svg>
                    </button>
                </li>
            @endforeach
        </ul>
    @endif

    <x-daylight::buttons.secondary type="button" x-on:click.prevent="$wire.openMediaLibrary()">
        {{ $displayType === 'gallery' ? __('daylight::media.add_media') : __('daylight::media.add_file') }}
    </x-daylight::buttons.secondary>

    <textarea name="{{ $name }}" class="hidden">{{ json_encode($selectedMedia) }}</textarea>

    <!-- Media Library Modal (teleported to body to avoid nested forms) -->
    <template x-teleport="body">
        <div x-cloak x-show="showMediaLibrary" 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="showMediaLibrary = false"
                        x-show="showMediaLibrary"
                        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-5xl overflow-x-hidden overflow-y-auto z-10"
                        style="max-height: 90vh; min-height: 90vh;"
                        x-show="showMediaLibrary"
                        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"
                    >
                        <livewire:daylight::media-library
                            :selectable="true"
                            :single-file="$singleFile"
                            :active="$selectedMedia"
                            :instance-id="$instanceId"
                        />
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>
