<div
    x-data="{
        showModal: false,

        handleSort(item, position) {
            // Get all UIDs in current order
            const order = Array.from($refs.sortableContainer.children).map(el => {
                return el.getAttribute('data-uid');
            }).filter(Boolean);

            $wire.reorderComponents(order);
        }
    }"
    x-on:keydown.escape.window="showModal = false"
>
    <!-- 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 textarea to preserve all component data on form submission (textarea handles long JSON better than input) -->
                <textarea
                    name="{{ $name }}_json[{{ $index }}]"
                    style="display: none;"
                    readonly
                    data-component-index="{{ $index }}"
                >@json($component)</textarea>

                <!-- 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>

                <!-- Hidden fields for form submission -->
                <input type="hidden" name="{{ $name }}[{{ $index }}][id]" value="{{ $component['id'] ?? '' }}">
                <input type="hidden" name="{{ $name }}[{{ $index }}][type]" value="{{ $component['type'] }}">

                <!-- 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
//                                $fieldArray = is_array($field) ? $field : (array) $field;
//                                $isRequired = isset($fieldArray['options']['required']) && $fieldArray['options']['required'];
//                                $fieldId = "field-{$component['_uid']}-{$fieldArray['name']}";
//                                $errorKey = "{$name}.{$index}.data.{$fieldArray['name']}";
//                                $fieldLabel = $fieldArray['label'] . ($isRequired ? ' *' : '');
//                                $fieldError = $errors->first($errorKey);
                                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;
                                }

                                // Double-check: ensure $fieldArray is actually an array
                                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"
                                                name="{{ $name }}[{{ $index }}][data][{{ $fieldArray['name'] }}]"
                                                wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}"
                                                :value="old($name . '.' . $index . '.data.' . $fieldArray['name'])"
                                            />

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

                                        @elseif($fieldArray['type'] === 'wysiwyg')
                                            <div wire:ignore x-data="{ content: @js($component['data'][$fieldArray['name']] ?? '') }">
                                                <x-daylight::input.wysiwyg
                                                    x-model="content"
                                                    name="{{ $name }}[{{ $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
                                                        name="{{ $name }}[{{ $index }}][data][{{ $fieldArray['name'] }}][url]"
                                                        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
                                                        name="{{ $name }}[{{ $index }}][data][{{ $fieldArray['name'] }}][label]"
                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.label"
                                                    />
                                                </div>
                                            </div>

                                        @elseif($fieldArray['type'] === 'media')
                                            @php
                                                $mediaKey = 'media-' . $component['_uid'] . '-' . $fieldArray['name'];
                                                $oldMedia = old($name . '.' . $index . '.data.' . $fieldArray['name']);
                                                if (is_string($oldMedia)) {
                                                    $decoded = json_decode($oldMedia, true);
                                                    $oldMedia = is_array($decoded) ? $decoded : [];
                                                }
                                                $initialMedia = $oldMedia ?: ($component['data'][$fieldArray['name']] ?? []);
                                                if (!is_array($initialMedia)) {
                                                    $initialMedia = [];
                                                }
                                            @endphp

                                            <livewire:daylight::media-selector
                                                :name="$name . '[' . $index . '][data][' . $fieldArray['name'] . ']'"
                                                :initial-media="$initialMedia"
                                                :single-file="($fieldArray['amountOfFiles'] ?? 0) === 1"
                                                wire:key="{{ $mediaKey }}"
                                            />

                                        @elseif($fieldArray['type'] === 'related')
                                            @php
                                                $relatedKey = 'related-' . $component['_uid'] . '-' . $fieldArray['name'];
                                            @endphp
                                            <livewire:daylight::related-field-selector
                                                :selected="old($name . '.' . $index . '.data.' . $fieldArray['name'], $component['data'][$fieldArray['name']] ?? [])"
                                                :related-type="$fieldArray['relatedType']"
                                                :name="$name . '[' . $index . '][data][' . $fieldArray['name'] . ']'"
                                                :placeholder="$fieldArray['options']['placeholder'] ?? __('daylight::general.search')"
                                                :required="$isRequired"
                                                wire:key="{{ $relatedKey }}"
                                            />

                                        @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;
                                                                }
                                                            @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
                                                                        name="{{ $name }}[{{ $index }}][data][{{ $fieldArray['name'] }}][{{ $rowIndex }}][{{ $subFieldArray['name'] }}]"
                                                                        wire:model.blur="components.{{ $index }}.data.{{ $fieldArray['name'] }}.{{ $rowIndex }}.{{ $subFieldArray['name'] }}"
                                                                    />

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

                                                                @elseif($subFieldArray['type'] === 'wysiwyg')
                                                                    <div wire:ignore x-data="{ content: @js($row[$subFieldArray['name']] ?? '') }">
                                                                        <x-daylight::input.wysiwyg
                                                                            x-model="content"
                                                                            name="{{ $name }}[{{ $index }}][data][{{ $fieldArray['name'] }}][{{ $rowIndex }}][{{ $subFieldArray['name'] }}]"
                                                                        />
                                                                    </div>

                                                                @elseif($subFieldArray['type'] === 'media')
                                                                    @php
                                                                        $repeaterMediaKey = 'media-repeater-' . $component['_uid'] . '-' . $fieldArray['name'] . '-' . $rowIndex . '-' . $subFieldArray['name'];
                                                                        $oldRepeaterMedia = old($name . '.' . $index . '.data.' . $fieldArray['name'] . '.' . $rowIndex . '.' . $subFieldArray['name']);
                                                                        if (is_string($oldRepeaterMedia)) {
                                                                            $decoded = json_decode($oldRepeaterMedia, true);
                                                                            $oldRepeaterMedia = is_array($decoded) ? $decoded : [];
                                                                        }
                                                                        $repeaterInitialMedia = $oldRepeaterMedia ?: ($row[$subFieldArray['name']] ?? []);
                                                                        if (!is_array($repeaterInitialMedia)) {
                                                                            $repeaterInitialMedia = [];
                                                                        }
                                                                    @endphp
                                                                    <livewire:daylight::media-selector
                                                                        :name="$name . '[' . $index . '][data][' . $fieldArray['name'] . '][' . $rowIndex . '][' . $subFieldArray['name'] . ']'"
                                                                        :initial-media="$repeaterInitialMedia"
                                                                        :single-file="($subFieldArray['amountOfFiles'] ?? 0) === 1"
                                                                        wire:key="{{ $repeaterMediaKey }}"
                                                                    />
                                                                @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;">
            <div class="fixed inset-0 bg-gray-500 opacity-75" 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-lg shadow-xl max-w-4xl w-full" x-on:click.away="showModal = false">
                        <div class="bg-sky-600 px-6 py-4 rounded-t-lg flex items-center justify-between">
                            <h2 class="text-lg font-semibold text-white">{{ __('daylight::general.select_component') }}</h2>
                            <button x-on:click="showModal = false" 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 class="p-6">
                            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                                @foreach($availableComponents as $availableComponent)
                                    <button
                                        type="button"
                                        wire:click="addComponent('{{ $availableComponent['type'] }}')"
                                        x-on:click="showModal = false"
                                        class="border border-gray-200 rounded-lg hover:border-sky-500 hover:shadow-lg transition text-left overflow-hidden group"
                                    >
                                        <div class="bg-gray-100 aspect-video rounded-t-lg flex items-center justify-center group-hover:bg-sky-50 transition">
                                            <svg class="w-12 h-12 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>
                                        </div>

                                        <div class="p-4">
                                            <h3 class="font-medium text-gray-900 mb-1">{{ $availableComponent['name'] }}</h3>
                                            @if(!empty($availableComponent['description']))
                                                <p class="text-sm text-gray-500">{{ $availableComponent['description'] }}</p>
                                            @endif
                                        </div>
                                    </button>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>

