<div
    x-data="{
        showModal: false,
        showMediaModal: false,
        mediaCallback: null,
        mediaModalInstanceId: 'page-builder-media',

        handleSort(item, position) {
            if (document.activeElement && document.activeElement.blur) {
                document.activeElement.blur();
            }

            setTimeout(() => {
                const order = Array.from($refs.sortableContainer.children).map(el => {
                    return el.getAttribute('data-uid');
                }).filter(Boolean);

                $wire.reorderComponents(order);
            }, 100);
        },

        openMediaModal(componentIndex, fieldName, currentMedia, singleFile, repeaterInfo) {
            this.mediaCallback = { componentIndex, fieldName, singleFile: !!singleFile, ...repeaterInfo };
            this.showMediaModal = true;

            this.$nextTick(() => {
                $wire.dispatch('sync-media-library-selection', { data: {
                    instanceId: this.mediaModalInstanceId,
                    selectedItems: currentMedia || [],
                    singleFile: !!singleFile,
                }});
            });
        },

        closeMediaModal() {
            this.showMediaModal = false;
            this.mediaCallback = null;
        },

        handleMediaSelected(detail) {
            let data = detail;
            if (Array.isArray(data)) data = data[0];
            if (!data) return;

            const files = data.files || [];
            const instanceId = data.instanceId;

            if (instanceId !== this.mediaModalInstanceId || !this.mediaCallback) return;

            const cb = this.mediaCallback;
            if (cb.rowIndex !== undefined && cb.subFieldName) {
                $wire.setRepeaterMediaForField(cb.componentIndex, cb.fieldName, cb.rowIndex, cb.subFieldName, files);
            } else {
                $wire.setMediaForField(cb.componentIndex, cb.fieldName, files);
            }

            this.closeMediaModal();
        },

        syncWysiwygBeforeSubmit() {
            this.$root.querySelectorAll('li[data-uid]').forEach(li => {
                const jsonInput = li.querySelector('input[type=hidden][name*=_json]');
                if (!jsonInput) return;

                let componentData;
                try { componentData = JSON.parse(jsonInput.value); } catch(e) { return; }

                let changed = false;

                li.querySelectorAll('[data-wysiwyg-field]').forEach(wrapper => {
                    const fieldPath = wrapper.getAttribute('data-wysiwyg-field');
                    const hiddenInput = wrapper.querySelector('input[type=hidden]');
                    if (!hiddenInput || !fieldPath) return;

                    const keys = fieldPath.split('.');
                    let target = componentData.data;
                    for (let i = 0; i < keys.length - 1; i++) {
                        if (target && typeof target === 'object') {
                            target = target[keys[i]];
                        } else {
                            return;
                        }
                    }
                    if (target && typeof target === 'object') {
                        const lastKey = keys[keys.length - 1];
                        if (target[lastKey] !== hiddenInput.value) {
                            target[lastKey] = hiddenInput.value;
                            changed = true;
                        }
                    }
                });

                if (changed) {
                    jsonInput.value = JSON.stringify(componentData);
                }
            });
        }
    }"
    x-on:keydown.escape.window="showModal = false"
    x-on:submit.window="syncWysiwygBeforeSubmit()"
    x-on:media-files-selected.window="handleMediaSelected($event.detail)"
    x-on:close-media-library.window="closeMediaModal()"
    x-on:media-selector-close.window="closeMediaModal()"
>
    <!-- Components List -->
    <ul
        x-ref="sortableContainer"
        x-sort="handleSort"
        class="space-y-4"
    >
        @foreach($components as $index => $component)
            <li
                wire:key="component-{{ $component['_uid'] }}"
                x-sort:item="@js($component['_uid'])"
                data-uid="{{ $component['_uid'] }}"
                class="border border-gray-200 rounded-lg bg-white"
            >
                <!-- Hidden input to preserve all component data on form submission -->
                <input type="hidden" name="{{ $name }}_json[{{ $index }}]" x-bind:value="JSON.stringify($wire.components[{{ $index }}])">

                <!-- Header -->
                <div class="p-4 flex items-center justify-between bg-gray-50 rounded-t-lg border-b border-gray-200">
                    <div class="flex items-center gap-3">
                        <span x-sort:handle class="cursor-move p-2 hover:bg-gray-100 rounded">
                            <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
                            </svg>
                        </span>
                        <span class="inline-flex items-center rounded-md bg-gray-400/10 px-2 py-1 text-xs font-medium text-gray-400 inset-ring inset-ring-gray-400/20">
                            {{ $index + 1 }}
                        </span>
                        <span
                            class="font-medium text-gray-800 cursor-pointer hover:text-sky-600"
                            wire:click="toggleCollapse('{{ $component['_uid'] }}')"
                        >
                            {{ $this->getComponentDefinition($component['type'])['name'] ?? $component['type'] }}
                        </span>
                    </div>

                    <div class="flex items-center gap-2">
                        <!-- Collapse Toggle -->
                        <button
                            type="button"
                            wire:click="toggleCollapse('{{ $component['_uid'] }}')"
                            class="p-2 hover:bg-gray-200 rounded-full transition"
                        >
                            <svg
                                class="w-4 h-4 transform transition-transform {{ isset($collapsed[$component['_uid']]) && $collapsed[$component['_uid']] ? '-rotate-90' : '' }}"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>

                        <!-- Delete Button -->
                        <button
                            type="button"
                            wire:click="deleteComponent('{{ $component['_uid'] }}')"
                            wire:confirm="{{ __('daylight::general.confirm_delete') }}"
                            class="p-2 hover:bg-red-100 rounded-full text-gray-600 hover:text-red-600 transition"
                        >
                            <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="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Component data is submitted via the JSON hidden input above -->

                <!-- Fields -->
                @if(!isset($collapsed[$component['_uid']]) || !$collapsed[$component['_uid']])
                    <div class="p-4 space-y-4">
                        @foreach($this->getComponentDefinition($component['type'])['fields'] ?? [] as $field)
                            @php
                                if ($field instanceof \Daylight\Core\Modules\PageBuilder\Entities\Field) {
                                    $fieldArray = $field->toArray();
                                } elseif (is_object($field) && method_exists($field, 'toArray')) {
                                    $fieldArray = $field->toArray();
                                } elseif (is_array($field)) {
                                    $fieldArray = $field;
                                } else {
                                    $fieldArray = (array) $field;
                                }

                                if (!is_array($fieldArray)) {
                                    $fieldArray = [];
                                }

                                $isRequired = isset($fieldArray['options']['required']) && $fieldArray['options']['required'];
                                $fieldName = $fieldArray['name'] ?? '';
                                $fieldId = "field-{$component['_uid']}-{$fieldName}";
                                $errorKey = "{$name}.{$index}.data.{$fieldName}";
                                $fieldLabel = ($fieldArray['label'] ?? '') . ($isRequired ? ' *' : '');
                                $fieldError = $errors->first($errorKey);
                            @endphp

                            <div class="space-y-8 border-b border-gray-900/10 sm:pb-2 sm:space-y-0 sm:divide-y sm:divide-gray-900/10 sm:pb-0">
                                <div class="sm:grid sm:grid-cols-12 sm:items-start sm:gap-4 py-4 sm:py-6">
                                    <label for="{{ $fieldId }}" class="col-span-2 block text-sm font-medium leading-6 text-gray-900 sm:pt-1.5">
                                        {{ $fieldLabel }}
                                    </label>
                                    <div class="mt-2 sm:col-span-10 sm:mt-0">
                                        @if($fieldArray['type'] === 'text')
                                            <x-daylight::input.text
                                                :id="$fieldId"
                                                wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}"
                                            />

                                        @elseif($fieldArray['type'] === 'select')
                                            <x-daylight::input.select
                                                :id="$fieldId"
                                                wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}"
                                            >
                                                @foreach($fieldArray['selectOptions'] ?? [] as $value => $label)
                                                    <option value="{{ $value }}">{{ $label }}</option>
                                                @endforeach
                                            </x-daylight::input.select>

                                        @elseif($fieldArray['type'] === 'wysiwyg')
                                            <div
                                                wire:key="wysiwyg-{{ $components[$index]['_uid'] }}-{{ $fieldArray['name'] }}"
                                                data-wysiwyg-field="{{ $fieldArray['name'] }}"
                                                x-on:focusout="
                                                    const hiddenInput = $el.querySelector('input[type=hidden]');
                                                    if (hiddenInput) {
                                                        $wire.set('components.{{ $index }}.data.{{ $fieldArray['name'] }}', hiddenInput.value);
                                                    }
                                                "
                                            >
                                                <x-daylight::input.wysiwyg
                                                    :id="$fieldId"
                                                    :value="$components[$index]['data'][$fieldArray['name']] ?? ''"
                                                />
                                            </div>

                                        @elseif($fieldArray['type'] === 'button')
                                            <div class="space-y-3">
                                                <div>
                                                    <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('daylight::general.url') }}</label>
                                                    <x-daylight::input.text
                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.url"
                                                        placeholder="https://..."
                                                    />
                                                </div>
                                                <div>
                                                    <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('daylight::general.label') }}</label>
                                                    <x-daylight::input.text
                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.label"
                                                    />
                                                </div>
                                            </div>

                                        @elseif($fieldArray['type'] === 'media')
                                            @php
                                                $mediaItems = $component['data'][$fieldArray['name']] ?? [];
                                                if (!is_array($mediaItems)) $mediaItems = [];
                                                $isSingleFile = ($fieldArray['amountOfFiles'] ?? 0) === 1;
                                            @endphp

                                            <div wire:key="media-field-{{ $component['_uid'] }}-{{ $fieldArray['name'] }}">
                                                @if(count($mediaItems) > 0)
                                                    <ul class="mb-4 flex gap-2 flex-wrap">
                                                        @foreach($mediaItems as $mediaIndex => $mediaItem)
                                                            @php
                                                                $itemType = is_array($mediaItem) ? ($mediaItem['type'] ?? '') : '';
                                                                $itemUrl = is_array($mediaItem) ? ($mediaItem['url'] ?? '') : '';
                                                                $itemName = is_array($mediaItem) ? ($mediaItem['name'] ?? '') : '';
                                                            @endphp
                                                            <li class="group relative bg-gray-50 rounded-lg">
                                                                @if(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="setMediaForField({{ $index }}, '{{ $fieldArray['name'] }}', {{ json_encode(collect($mediaItems)->reject(fn($v, $k) => $k === $mediaIndex)->values()->toArray()) }})"
                                                                    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"
                                                                >
                                                                    <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="openMediaModal({{ $index }}, '{{ $fieldArray['name'] }}', $wire.get('components.{{ $index }}.data.{{ $fieldArray['name'] }}') || [], {{ $isSingleFile ? 'true' : 'false' }})"
                                                >
                                                    {{ __('daylight::media.add_media') }}
                                                </x-daylight::buttons.secondary>
                                            </div>

                                        @elseif($fieldArray['type'] === 'form')
                                            <x-daylight::input.select
                                                :id="$fieldId"
                                                wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}"
                                            >
                                                <option value="">{{ __('daylight::forms.select_form') }}...</option>
                                                @foreach(\Daylight\Core\Modules\FormBuilder\Models\Form::active()->orderBy('name')->get() as $formOption)
                                                    <option value="{{ $formOption->id }}">{{ $formOption->name }}</option>
                                                @endforeach
                                            </x-daylight::input.select>

                                        @elseif($fieldArray['type'] === 'related')
                                            @php
                                                $relatedItems = $component['data'][$fieldArray['name']] ?? [];
                                                if (!is_array($relatedItems)) $relatedItems = [];
                                            @endphp

                                            <div
                                                wire:key="related-field-{{ $component['_uid'] }}-{{ $fieldArray['name'] }}"
                                                x-data="{
                                                    searchQuery: '',
                                                    searchResults: [],
                                                    showDropdown: false,
                                                    isSearching: false,
                                                    searchTimeout: null,

                                                    doSearch() {
                                                        clearTimeout(this.searchTimeout);

                                                        if (this.searchQuery.length < 2) {
                                                            this.searchResults = [];
                                                            this.showDropdown = false;
                                                            return;
                                                        }

                                                        this.isSearching = true;
                                                        this.searchTimeout = setTimeout(async () => {
                                                            const items = $wire.get('components.{{ $index }}.data.{{ $fieldArray['name'] }}') || [];
                                                            const excludeIds = items.map(i => i.id).filter(Boolean);
                                                            this.searchResults = await $wire.searchRelatedItems('{{ addslashes($fieldArray['relatedType'] ?? '') }}', this.searchQuery, excludeIds);
                                                            this.showDropdown = this.searchResults.length > 0;
                                                            this.isSearching = false;
                                                        }, 300);
                                                    },

                                                    selectItem(item) {
                                                        $wire.addRelatedItem({{ $index }}, '{{ $fieldArray['name'] }}', item);
                                                        this.searchQuery = '';
                                                        this.searchResults = [];
                                                        this.showDropdown = false;
                                                    },

                                                    handleRelatedSort(item, position) {
                                                        const order = Array.from(this.$refs.relatedSortContainer.children).map(el => {
                                                            return parseInt(el.getAttribute('data-item-id'));
                                                        }).filter(id => !isNaN(id));

                                                        $wire.reorderRelatedItems({{ $index }}, '{{ $fieldArray['name'] }}', order);
                                                    }
                                                }"
                                                class="relative"
                                            >
                                                <!-- Selected Items -->
                                                @if(count($relatedItems) > 0)
                                                    <div class="mb-2 flex flex-wrap gap-2" x-ref="relatedSortContainer" x-sort="handleRelatedSort">
                                                        @foreach($relatedItems as $relatedIndex => $relatedItem)
                                                            <div
                                                                x-sort:item
                                                                data-item-id="{{ $relatedItem['id'] ?? '' }}"
                                                                class="inline-flex items-center gap-2 px-3 py-1.5 bg-sky-100 text-sky-800 rounded-lg text-sm"
                                                            >
                                                                <span x-sort:handle class="cursor-move">
                                                                    <svg class="w-3.5 h-3.5 text-sky-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
                                                                    </svg>
                                                                </span>
                                                                <span>{{ $relatedItem['name'] ?? 'Unknown' }}</span>
                                                                @if(isset($relatedItem['id']))
                                                                    <span class="text-sky-600 text-xs">(ID: {{ $relatedItem['id'] }})</span>
                                                                @endif
                                                                <button
                                                                    type="button"
                                                                    wire:click="removeRelatedItem({{ $index }}, '{{ $fieldArray['name'] }}', {{ $relatedIndex }})"
                                                                    class="hover:text-sky-900"
                                                                    style="width: 15px;"
                                                                >
                                                                    <svg class="w-3.5 h-3.5" 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>
                                                                </button>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                @endif

                                                <!-- Search Input -->
                                                <div class="relative">
                                                    <input
                                                        type="text"
                                                        x-model="searchQuery"
                                                        x-on:input="doSearch()"
                                                        x-on:focus="if (searchResults.length > 0) showDropdown = true"
                                                        x-on:keydown.escape="showDropdown = false"
                                                        placeholder="{{ $fieldArray['options']['placeholder'] ?? __('daylight::general.search') }}"
                                                        class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-sky-600 sm:text-sm sm:leading-6"
                                                    />

                                                    <!-- Search Results Dropdown -->
                                                    <div
                                                        x-show="showDropdown"
                                                        x-on:click.away="showDropdown = false"
                                                        x-transition:enter="transition ease-out duration-100"
                                                        x-transition:enter-start="transform opacity-0 scale-95"
                                                        x-transition:enter-end="transform opacity-100 scale-100"
                                                        x-transition:leave="transition ease-in duration-75"
                                                        x-transition:leave-start="transform opacity-100 scale-100"
                                                        x-transition:leave-end="transform opacity-0 scale-95"
                                                        class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-gray-200 max-h-60 overflow-auto"
                                                        style="display: none;"
                                                    >
                                                        <template x-for="result in searchResults" :key="result.id">
                                                            <button
                                                                type="button"
                                                                x-on:click="selectItem(result)"
                                                                class="w-full text-left px-4 py-2 hover:bg-gray-50 flex items-center justify-between"
                                                            >
                                                                <div>
                                                                    <div class="text-sm font-medium text-gray-900" x-text="result.name"></div>
                                                                    <div class="text-xs text-gray-500" x-show="result.id" x-text="'ID: ' + result.id"></div>
                                                                    <div class="text-xs text-gray-500" x-show="result.sku" x-text="'SKU: ' + result.sku"></div>
                                                                    <div class="text-xs text-gray-500" x-show="result.brand" x-text="result.brand"></div>
                                                                </div>
                                                            </button>
                                                        </template>
                                                    </div>

                                                    <!-- No Results Message -->
                                                    <template x-if="showDropdown && searchQuery.length >= 2 && searchResults.length === 0 && !isSearching">
                                                        <div class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-gray-200 px-4 py-3">
                                                            <p class="text-sm text-gray-500">{{ __('daylight::general.no_results_found') }}</p>
                                                        </div>
                                                    </template>
                                                </div>

                                                <!-- Hint Text -->
                                                @if(count($relatedItems) === 0)
                                                    <p class="mt-1 text-xs text-gray-500">{{ __('daylight::general.type_to_search') }}</p>
                                                @endif
                                            </div>

                                        @elseif($fieldArray['type'] === 'repeater')
                                            <div class="space-y-3">
                                            @foreach($component['data'][$fieldArray['name']] ?? [] as $rowIndex => $row)
                                                <div wire:key="repeater-{{ $component['_uid'] }}-{{ $fieldArray['name'] }}-{{ $rowIndex }}" class="border border-gray-200 rounded-lg p-4 bg-gray-50">
                                                    <div class="flex items-center justify-between mb-3">
                                                        <span class="text-sm font-medium text-gray-700">
                                                            {{ __('daylight::general.row') }} {{ $rowIndex + 1 }}
                                                        </span>
                                                        <button
                                                            type="button"
                                                            wire:click="deleteRepeaterRow('{{ $component['_uid'] }}', '{{ $fieldArray['name'] }}', {{ $rowIndex }})"
                                                            class="text-sm text-red-600 hover:text-red-800"
                                                        >
                                                            {{ __('daylight::general.delete_row') }}
                                                        </button>
                                                    </div>

                                                    <div class="space-y-3">
                                                        @foreach($fieldArray['items'] ?? [] as $subField)
                                                            @php
                                                                if (is_object($subField) && method_exists($subField, 'toArray')) {
                                                                    $subFieldArray = $subField->toArray();
                                                                } elseif (is_array($subField)) {
                                                                    $subFieldArray = $subField;
                                                                } else {
                                                                    $subFieldArray = (array) $subField;
                                                                }
                                                                $subFieldName = $subFieldArray['name'] ?? '';
                                                                $subFieldValue = $row[$subFieldName] ?? '';
                                                            @endphp

                                                            <div>
                                                                <label class="block text-sm font-medium text-gray-700 mb-1">{{ $subFieldArray['label'] }}</label>

                                                                @if($subFieldArray['type'] === 'text')
                                                                    <x-daylight::input.text
                                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}"
                                                                    />

                                                                @elseif($subFieldArray['type'] === 'select')
                                                                    <x-daylight::input.select
                                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}"
                                                                    >
                                                                        @foreach($subFieldArray['selectOptions'] ?? [] as $value => $label)
                                                                            <option value="{{ $value }}">{{ $label }}</option>
                                                                        @endforeach
                                                                    </x-daylight::input.select>

                                                                @elseif($subFieldArray['type'] === 'wysiwyg')
                                                                    <div
                                                                        wire:key="wysiwyg-{{ $components[$index]['_uid'] }}-{{ $fieldArray['name'] }}-{{ $rowIndex }}-{{ $subFieldArray['name'] }}"
                                                                        data-wysiwyg-field="{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}"
                                                                        x-on:focusout="
                                                                            const hiddenInput = $el.querySelector('input[type=hidden]');
                                                                            if (hiddenInput) {
                                                                                $wire.set('components.{{ $index }}.data.{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}', hiddenInput.value);
                                                                            }
                                                                        "
                                                                    >
                                                                        <x-daylight::input.wysiwyg
                                                                            :value="$subFieldValue ?? ''"
                                                                        />
                                                                    </div>

                                                                @elseif($subFieldArray['type'] === 'media')
                                                                    @php
                                                                        $repeaterMediaItems = $row[$subFieldArray['name']] ?? [];
                                                                        if (!is_array($repeaterMediaItems)) $repeaterMediaItems = [];
                                                                        $repeaterIsSingleFile = ($subFieldArray['amountOfFiles'] ?? 0) === 1;
                                                                    @endphp

                                                                    <div wire:key="media-field-{{ $component['_uid'] }}-{{ $fieldArray['name'] }}-{{ $rowIndex }}-{{ $subFieldArray['name'] }}">
                                                                        @if(count($repeaterMediaItems) > 0)
                                                                            <ul class="mb-4 flex gap-2 flex-wrap">
                                                                                @foreach($repeaterMediaItems as $rMediaIndex => $rMediaItem)
                                                                                    @php
                                                                                        $rItemType = is_array($rMediaItem) ? ($rMediaItem['type'] ?? '') : '';
                                                                                        $rItemUrl = is_array($rMediaItem) ? ($rMediaItem['url'] ?? '') : '';
                                                                                        $rItemName = is_array($rMediaItem) ? ($rMediaItem['name'] ?? '') : '';
                                                                                    @endphp
                                                                                    <li class="group relative bg-gray-50 rounded-lg">
                                                                                        @if(in_array($rItemType, ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp']))
                                                                                            <img src="{{ $rItemUrl }}" alt="{{ $rItemName }}" class="w-24 h-24 rounded-lg border object-cover pointer-events-none">
                                                                                        @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>
                                                                                                {{ $rItemName }}
                                                                                            </div>
                                                                                        @endif

                                                                                        <button
                                                                                            wire:click="setRepeaterMediaForField({{ $index }}, '{{ $fieldArray['name'] }}', {{ $rowIndex }}, '{{ $subFieldArray['name'] }}', {{ json_encode(collect($repeaterMediaItems)->reject(fn($v, $k) => $k === $rMediaIndex)->values()->toArray()) }})"
                                                                                            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"
                                                                                        >
                                                                                            <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="openMediaModal({{ $index }}, '{{ $fieldArray['name'] }}', $wire.get('components.{{ $index }}.data.{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}') || [], {{ $repeaterIsSingleFile ? 'true' : 'false' }}, { rowIndex: {{ $rowIndex }}, subFieldName: '{{ $subFieldArray['name'] }}' })"
                                                                        >
                                                                            {{ __('daylight::media.add_media') }}
                                                                        </x-daylight::buttons.secondary>
                                                                    </div>
                                                                @endif
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            @endforeach

                                            <button
                                                type="button"
                                                wire:click="addRepeaterRow('{{ $component['_uid'] }}', '{{ $fieldArray['name'] }}')"
                                                class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
                                            >
                                                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                                                </svg>
                                                {{ __('daylight::general.add_new_row') }}
                                            </button>
                                        </div>
                                        @endif

                                        @if($fieldError)
                                            <div class="mt-1 text-xs text-red-500">{{ $fieldError }}</div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif
            </li>
        @endforeach
    </ul>

    <!-- Empty State -->
    @if(empty($components))
        <div class="text-center py-12 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
            {{ __('daylight::general.no_components_added') }}
        </div>
    @endif

    <!-- Add Component Button -->
    <button
        type="button"
        x-on:click="showModal = true"
        class="rounded-md mt-4 w-full border border-dashed border-gray-300 hover:border-gray-700 transition text-gray-500 hover:text-gray-900 py-6 font-semibold text-sm flex items-center justify-center"
    >
        <svg class="w-4 h-4 mr-3" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"></path>
        </svg>
        {{ __('daylight::general.add_component') }}
    </button>

    <!-- Component Picker Modal -->
    <template x-teleport="body">
        <div x-show="showModal" x-cloak class="fixed inset-0 z-50" style="display: none;"
             x-data="{
                search: '',
                names: @js(collect($availableComponents)->pluck('name')->map(fn ($n) => strtolower($n))->values()->toArray()),
                get hasResults() {
                    if (!this.search) return true;
                    const q = this.search.toLowerCase();
                    return this.names.some(n => n.includes(q));
                }
             }"
             x-on:keydown.escape.window="showModal = false"
        >
            <div class="fixed inset-0 bg-gray-900/50 backdrop-blur-sm" x-on:click="showModal = false"></div>

            <div class="fixed inset-0 overflow-y-auto px-4 py-6">
                <div class="flex items-center justify-center min-h-full">
                    <div class="relative bg-white rounded-xl shadow-2xl max-w-lg w-full" x-on:click.away="showModal = false">
                        {{-- Header with search --}}
                        <div class="px-5 pt-5 pb-3">
                            <div class="flex items-center justify-between mb-3">
                                <h2 class="text-base font-semibold text-gray-900">{{ __('daylight::general.select_component') }}</h2>
                                <button x-on:click="showModal = false" class="text-gray-400 hover:text-gray-600 transition">
                                    <svg class="h-5 w-5" 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 class="relative">
                                <svg class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
                                </svg>
                                <input
                                    type="text"
                                    x-model="search"
                                    x-ref="componentSearch"
                                    x-init="$watch('showModal', value => { if (value) $nextTick(() => $refs.componentSearch.focus()); else search = ''; })"
                                    placeholder="{{ __('daylight::general.search') }}..."
                                    class="w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm placeholder-gray-400 focus:border-sky-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-sky-500 transition"
                                />
                            </div>
                        </div>

                        {{-- Component list --}}
                        <div class="max-h-80 overflow-y-auto px-2 pb-2">
                            @foreach($availableComponents as $availableComponent)
                                <button
                                    type="button"
                                    wire:click="addComponent('{{ $availableComponent['type'] }}')"
                                    x-on:click="showModal = false"
                                    x-show="!search || '{{ strtolower($availableComponent['name']) }}'.includes(search.toLowerCase())"
                                    class="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left hover:bg-gray-50 transition group"
                                >
                                    <span class="text-sm font-medium text-gray-700 group-hover:text-gray-900 transition">{{ $availableComponent['name'] }}</span>
                                    <div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-white transition overflow-hidden">
                                        @if(!empty($availableComponent['thumbnail']))
                                            <img src="{{ $availableComponent['thumbnail'] }}" alt="" class="h-full w-full object-contain p-1.5">
                                        @else
                                            <svg class="h-5 w-5 text-gray-400 group-hover:text-sky-500 transition" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M6 6.878V6a2.25 2.25 0 0 1 2.25-2.25h7.5A2.25 2.25 0 0 1 18 6v.878m-12 0c.235-.083.487-.128.75-.128h10.5c.263 0 .515.045.75.128m-12 0A2.25 2.25 0 0 0 4.5 9v.878m13.5-3A2.25 2.25 0 0 1 19.5 9v.878m0 0a2.246 2.246 0 0 0-.75-.128H5.25c-.263 0-.515.045-.75.128m15 0A2.25 2.25 0 0 1 21 12v6a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 18v-6c0-.98.626-1.813 1.5-2.122" />
                                            </svg>
                                        @endif
                                    </div>
                                </button>
                            @endforeach

                            {{-- No results --}}
                            <div x-show="search && !hasResults" x-cloak class="py-6 text-center text-sm text-gray-500">
                                {{ __('daylight::general.no_results') }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <!-- Shared Media Library Modal -->
    <template x-teleport="body">
        <div x-cloak x-show="showMediaModal" class="fixed inset-0 z-[60]" style="display: none;">
            <div class="fixed inset-0 overflow-y-auto px-4 py-6 sm:px-0 z-[60]">
                <div class="flex items-center min-h-full">
                    <!-- Backdrop -->
                    <div
                        class="fixed inset-0 bg-gray-500 opacity-75 transition-opacity"
                        x-on:click="closeMediaModal()"
                        x-show="showMediaModal"
                        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="showMediaModal"
                        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="false"
                            :active="[]"
                            :instance-id="'page-builder-media'"
                            wire:key="page-builder-media-library"
                        />
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>
