@props(['items' => []])

<!-- Hidden textarea to submit items with the form -->
<textarea name="items" x-ref="itemsInput" class="hidden"></textarea>

<div
    x-data="{
        menuItems: @js($items).map(item => ({
            ...item,
            _uid: item.id || 'item-' + Math.random().toString(36).substr(2, 9),
            children: (item.children || []).map(child => ({
                ...child,
                _uid: child.id || 'child-' + Math.random().toString(36).substr(2, 9),
                children: (child.children || []).map(grandchild => ({
                    ...grandchild,
                    _uid: grandchild.id || 'grandchild-' + Math.random().toString(36).substr(2, 9)
                }))
            }))
        })),
        editForm: null,
        isCreating: false,
        
        init() {
            // Initialize the textarea with current data
            this.updateTextarea();
            
            // Watch for changes to menuItems and re-initialize sortable
            this.$watch('menuItems', () => {
                this.$nextTick(() => {
                    this.initSortable();
                });
            });
            
            this.$nextTick(() => {
                this.initSortable();
            });
        },
        
        initSortable() {
            const self = this;
            
            // Destroy existing sortable instances first
            const allContainers = this.$el.querySelectorAll('.sortable-list');
            allContainers.forEach(container => {
                if (container.sortable) {
                    container.sortable.destroy();
                }
            });
            
            // Initialize sortable for root container
            const rootContainer = this.$refs.sortableContainer;
            if (rootContainer) {
                rootContainer.sortable = Sortable.create(rootContainer, {
                    group: 'nested-menu',
                    handle: '.handle',
                    animation: 150,
                    fallbackOnBody: true,
                    swapThreshold: 0.65,
                    onEnd: function(evt) {
                        setTimeout(() => {
                            self.syncMenuItems();
                        }, 100);
                    }
                });
            }
            
            // Initialize sortable for all nested containers
            const nestedContainers = this.$el.querySelectorAll('[data-nested-container]');
            nestedContainers.forEach(container => {
                container.sortable = Sortable.create(container, {
                    group: 'nested-menu',
                    handle: '.handle',
                    animation: 150,
                    fallbackOnBody: true,
                    swapThreshold: 0.65,
                    onEnd: function(evt) {
                        setTimeout(() => {
                            self.syncMenuItems();
                        }, 100);
                    }
                });
            });
        },
        
        syncMenuItems() {
            const syncFromContainer = (container) => {
                const items = [];
                
                Array.from(container.children).forEach(child => {
                    if (!child.hasAttribute('data-menu-item')) return;
                    
                    const uid = child.getAttribute('data-uid');
                    const mainDiv = child.querySelector(':scope > div');
                    if (!mainDiv || !uid) return;
                    
                    const nameEl = mainDiv.querySelector('[data-item-name]');
                    const urlEl = mainDiv.querySelector('[data-item-url]');
                    const nestedContainer = child.querySelector(':scope > [data-nested-container]');
                    
                    if (nameEl && urlEl) {
                        const item = {
                            _uid: uid,
                            name: nameEl.textContent.trim(),
                            url: urlEl.textContent.trim(),
                            children: []
                        };
                        
                        if (nestedContainer) {
                            const nestedChildren = syncFromContainer(nestedContainer);
                            if (nestedChildren.length > 0) {
                                item.children = nestedChildren;
                            }
                        }
                        
                        items.push(item);
                    }
                });
                
                return items;
            };
            
            const rootContainer = this.$refs.sortableContainer;
            if (rootContainer) {
                this.menuItems = syncFromContainer(rootContainer);
                this.updateTextarea();
            }
        },
        
        addItem() {
            this.isCreating = true;
            this.editForm = {
                path: null,
                name: '',
                url: '',
                _uid: 'new-' + Math.random().toString(36).substr(2, 9),
                children: []
            };
        },
        
        openEditModal(item, itemPath) {
            this.isCreating = false;
            this.editForm = {
                path: itemPath,
                name: item.name,
                url: item.url,
                children: item.children || []
            };
        },
        
        saveEditModal() {
            if (!this.editForm) return;
            
            if (this.isCreating) {
                // Add new item
                this.menuItems.push({
                    _uid: this.editForm._uid,
                    name: this.editForm.name,
                    url: this.editForm.url,
                    children: []
                });
            } else {
                // Update existing item
                const item = this.getItemByPath(this.editForm.path);
                if (item) {
                    item.name = this.editForm.name;
                    item.url = this.editForm.url;
                }
            }
            
            this.editForm = null;
            this.isCreating = false;
            this.updateTextarea();
        },
        
        cancelEditModal() {
            this.editForm = null;
            this.isCreating = false;
        },
        
        deleteItem(itemPath) {
            const pathParts = itemPath.split('.');
            const lastIndex = parseInt(pathParts.pop());
            
            if (pathParts.length === 0) {
                // Root level
                this.menuItems.splice(lastIndex, 1);
            } else {
                // Nested level
                const parent = this.getItemByPath(pathParts.join('.'));
                if (parent && parent.children) {
                    parent.children.splice(lastIndex, 1);
                }
            }
            
            this.updateTextarea();
        },
        
        getItemByPath(path) {
            const parts = path.split('.').map(p => parseInt(p));
            let current = { children: this.menuItems };
            
            for (let i = 0; i < parts.length; i++) {
                if (!current.children || !current.children[parts[i]]) {
                    return null;
                }
                current = current.children[parts[i]];
            }
            
            return current;
        },
        
        
        updateTextarea() {
            if (this.$refs.itemsInput) {
                this.$refs.itemsInput.value = JSON.stringify(this.menuItems);
            }
        },
    }"
    x-on:keydown.escape.window="cancelEditModal()"
>
    <div>
        <ul x-ref="sortableContainer" class="sortable-list min-h-[50px]">
            <template x-for="(item, index) in menuItems" :key="item._uid">
                <li data-menu-item class="mb-2" :data-uid="item._uid">
                    <div class="flex items-center justify-between p-4 border rounded">
                        <div class="flex items-center">
                            <svg class="handle w-4 h-4 mr-4 text-gray-400 cursor-move" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"></path>
                            </svg>

                            <div class="ml-3">
                                <p class="text-sm font-semibold" data-item-name x-text="item.name"></p>
                                <p class="text-xs opacity-50">URL: <span data-item-url x-text="item.url"></span></p>
                            </div>
                        </div>

                        <div class="flex items-center gap-3">
                            <button 
                                type="button"
                                @click.prevent="openEditModal(item, String(index))"
                                class="p-2 bg-gray-200 rounded-full hover:bg-sky-600 hover:text-white transition"
                            >
                                <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
                                </svg>
                            </button>

                            <button 
                                type="button"
                                @click.prevent="deleteItem(String(index))"
                                class="p-2 bg-gray-200 rounded-full hover:bg-red-500 hover:text-white transition"
                            >
                                <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"></path>
                                </svg>
                            </button>
                        </div>
                    </div>

                    <!-- Nested children container (Level 2) -->
                    <ul 
                        data-nested-container 
                        class="sortable-list ml-8 mt-2 min-h-[20px]"
                    >
                        <template x-for="(child, childIndex) in item.children" :key="child._uid">
                            <li data-menu-item class="mb-2" :data-uid="child._uid">
                                <div class="flex items-center justify-between p-4 border rounded">
                                    <div class="flex items-center">
                                        <svg class="handle w-4 h-4 mr-4 text-gray-400 cursor-move" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"></path>
                                        </svg>

                                        <div class="ml-3">
                                            <p class="text-sm font-semibold" data-item-name x-text="child.name"></p>
                                            <p class="text-xs opacity-50">URL: <span data-item-url x-text="child.url"></span></p>
                                        </div>
                                    </div>

                                    <div class="flex items-center gap-3">
                                        <button 
                                            type="button"
                                            @click.prevent="openEditModal(child, String(index) + '.' + String(childIndex))"
                                            class="p-2 bg-gray-200 rounded-full hover:bg-sky-600 hover:text-white transition"
                                        >
                                            <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
                                            </svg>
                                        </button>

                                        <button 
                                            type="button"
                                            @click.prevent="deleteItem(String(index) + '.' + String(childIndex))"
                                            class="p-2 bg-gray-200 rounded-full hover:bg-red-500 hover:text-white transition"
                                        >
                                            <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>

                                <!-- Nested grandchildren container (Level 3) -->
                                <ul 
                                    data-nested-container 
                                    class="sortable-list ml-8 mt-2 min-h-[20px]"
                                >
                                    <template x-for="(grandchild, grandchildIndex) in child.children" :key="grandchild._uid">
                                        <li data-menu-item class="mb-2" :data-uid="grandchild._uid">
                                            <div class="flex items-center justify-between p-4 border rounded">
                                                <div class="flex items-center">
                                                    <svg class="handle w-4 h-4 mr-4 text-gray-400 cursor-move" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"></path>
                                                    </svg>

                                                    <div class="ml-3">
                                                        <p class="text-sm font-semibold" data-item-name x-text="grandchild.name"></p>
                                                        <p class="text-xs opacity-50">URL: <span data-item-url x-text="grandchild.url"></span></p>
                                                    </div>
                                                </div>

                                                <div class="flex items-center gap-3">
                                                    <button 
                                                        type="button"
                                                        @click.prevent="openEditModal(grandchild, String(index) + '.' + String(childIndex) + '.' + String(grandchildIndex))"
                                                        class="p-2 bg-gray-200 rounded-full hover:bg-sky-600 hover:text-white transition"
                                                    >
                                                        <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                            <path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
                                                        </svg>
                                                    </button>

                                                    <button 
                                                        type="button"
                                                        @click.prevent="deleteItem(String(index) + '.' + String(childIndex) + '.' + String(grandchildIndex))"
                                                        class="p-2 bg-gray-200 rounded-full hover:bg-red-500 hover:text-white transition"
                                                    >
                                                        <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"></path>
                                                        </svg>
                                                    </button>
                                                </div>
                                            </div>
                                        </li>
                                    </template>
                                </ul>
                            </li>
                        </template>
                    </ul>
                </li>
            </template>
        </ul>

        <button 
            type="button" 
            @click.prevent="addItem" 
            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-5 font-semibold text-sm flex items-center justify-center"
        >
            <svg class="w-4 h-4 mr-3" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                <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::content.add_menu_item') }}
        </button>
    </div>

    <!-- Edit Modal -->
    <div 
        class="relative z-150" 
        aria-labelledby="slide-over-title" 
        role="dialog" 
        aria-modal="true"
        x-show="editForm !== null"
        x-cloak
        style="display: none;"
    >
        <div 
            class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
            @click.prevent="cancelEditModal()"
            x-show="editForm !== null"
            x-transition:enter="ease-in-out duration-500"
            x-transition:enter-start="opacity-0"
            x-transition:enter-end="opacity-100"
            x-transition:leave="ease-in-out duration-500"
            x-transition:leave-start="opacity-100"
            x-transition:leave-end="opacity-0"
        ></div>

        <div 
            class="pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10 sm:pl-16"
            x-show="editForm !== null"
            x-transition:enter="transform transition ease-in-out duration-500 sm:duration-700"
            x-transition:enter-start="translate-x-full"
            x-transition:enter-end="translate-x-0"
            x-transition:leave="transform transition ease-in-out duration-500 sm:duration-700"
            x-transition:leave-start="translate-x-0"
            x-transition:leave-end="translate-x-full"
        >
            <div class="pointer-events-auto w-screen max-w-2xl">
                <div class="flex h-full flex-col overflow-y-scroll bg-white shadow-xl">
                    <div class="flex-1">
                        <div class="bg-sky-600 px-4 py-6 sm:px-6">
                            <div class="flex items-start justify-between space-x-3">
                                <div class="space-y-1">
                                    <h2 class="text-base font-semibold leading-6 text-white" id="slide-over-title">{{ __('daylight::content.edit_item') }}</h2>
                                    <p class="text-sm text-white text-opacity-75">{{ __('daylight::content.edit_item_message') }}</p>
                                </div>

                                <div class="flex h-7 items-center">
                                    <button 
                                        type="button"
                                        @click.prevent="cancelEditModal()" 
                                        class="relative text-gray-400 hover:text-gray-500"
                                    >
                                        <span class="absolute -inset-2.5"></span>
                                        <span class="sr-only">{{ __('daylight::general.close_panel') }}</span>
                                        <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Divider container -->
                        <div class="space-y-6 py-6 sm:space-y-0 sm:divide-y sm:divide-gray-200 sm:py-0">
                            <template x-if="editForm">
                                <div>
                                    <!-- Name -->
                                    <div class="space-y-2 px-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:space-y-0 sm:px-6 sm:py-5">
                                        <div>
                                            <label for="edit-name" class="block text-sm font-medium leading-6 text-gray-900 sm:mt-1.5">{{ __('daylight::general.name') }}</label>
                                        </div>
                                        <div class="sm:col-span-2">
                                            <input 
                                                x-model="editForm.name" 
                                                type="text" 
                                                id="edit-name"
                                                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-indigo-600 sm:text-sm sm:leading-6"
                                            >
                                        </div>
                                    </div>

                                    <!-- URL -->
                                    <div class="space-y-2 px-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:space-y-0 sm:px-6 sm:py-5">
                                        <div>
                                            <label for="edit-url" class="block text-sm font-medium leading-6 text-gray-900 sm:mt-1.5">{{ __('daylight::general.url') }}</label>
                                        </div>
                                        <div class="sm:col-span-2">
                                            <input 
                                                x-model="editForm.url" 
                                                type="text" 
                                                id="edit-url"
                                                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-indigo-600 sm:text-sm sm:leading-6"
                                            >
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                    <!-- Action buttons -->
                    <div class="flex-shrink-0 border-t border-gray-200 px-4 py-5 sm:px-6">
                        <div class="flex justify-end space-x-3">
                            <button 
                                type="button" 
                                @click.prevent="cancelEditModal()" 
                                class="bg-white text-sky-600 hover:opacity-75 border-sky-600 py-2.5 px-4 border rounded-md text-sm leading-5 font-medium focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition duration-150 ease-in-out"
                            >
                                {{ __('daylight::general.cancel') }}
                            </button>

                            <button 
                                type="button" 
                                @click.prevent="saveEditModal" 
                                class="bg-sky-600 text-white hover:bg-sky-700 border-sky-600 text-sm py-2.5 px-4 border rounded-md leading-5 font-medium focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition duration-150 ease-in-out"
                            >
                                <span x-text="isCreating ? '{{ __('daylight::general.create') }}' : '{{ __('daylight::general.save') }}'"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

