<?php include_once __DIR__.'/components/includes/Aside.php'; ?>

<div class="p-5 rounded-lg bg-zinc-50">
    <span class="text-sm text-zinc-700 ">Gestiona la configuración del proyecto.</span>
    <div class="flex flex-col gap-4 mt-2">
        <div class="flex flex-col gap-2 border p-5 rounded-lg border-zinc-200">
            <div class="flex items-center justify-between">
                <div class="flex flex-col gap-1">
                    <h3 class="font-medium">Configuración de proyecto</h3>
                    <p class="text-sm text-zinc-700">Añade o modifica la estructura base de tus futuros proyectos.</p>
                    <div class="text-xs text-zinc-500 mt-1 flex items-center gap-4">
                        <span>💡 <strong>Tip:</strong> Arrastra elementos para reorganizar</span>
                        <span class="hidden md:inline">• Suelta en la parte superior = antes • Inferior = después • Centro = hijo</span>
                    </div>
                </div>
                <button id="saveStructureBtn" class="text-white bg-zinc-900 text-sm cursor-pointer hover:bg-zinc-800 p-2 rounded-md hover:scale-105 transition-all ease-in-out flex items-center gap-2 outline-none">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-5">
                        <path fill-rule="evenodd" d="M6 3a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3H6Zm1.5 1.5a.75.75 0 0 0-.75.75V16.5a.75.75 0 0 0 1.085.67L12 15.089l4.165 2.083a.75.75 0 0 0 1.085-.671V5.25a.75.75 0 0 0-.75-.75h-9Z" clip-rule="evenodd" />
                    </svg>
                    <span class="font-medium hidden sm:block">Guardar configuración</span>
                </button>
            </div>
            <div id="projectTree" class="  bg-white rounded-xl shadow-sm border border-zinc-200 overflow-hidden overflow-x-auto"></div>
        </div>
    </div>
</div>

<?php $projectStructure = json_decode(file_get_contents(__DIR__ . "/../../../ProjectDefaultStructure.json"), true);?>

<style>
    /* Estados de drag & drop - No disponibles en Tailwind estándar */
    .dragging {
        opacity: 0.5;
        background-color: #f0f0f0;
        border: 2px dashed #999;
    }

    .drag-over-before {
        border-top: 3px solid #2196F3 !important;
        margin-top: 4px;
    }

    .drag-over-after {
        border-bottom: 3px solid #2196F3 !important;
        margin-bottom: 4px;
    }

    .drag-over-inside {
        background-color: #e3f2fd !important;
        border: 2px solid #1976D2 !important;
        box-shadow: inset 0 0 8px rgba(25, 118, 210, 0.3);
    }
</style>

<script type="module">

    import { useSettingApi } from "<?= $urlAbsolute ?>/js/api/settingsApi.js";

    const projectData = <?php echo json_encode($projectStructure, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?>;
    let draggedNode = null;
    let draggedParentArray = null;

    function renderNode(node, parentArray) {
        const hasChildren = Array.isArray(node.children) && node.children.length > 0;

        const container = document.createElement('div');
        container.className = "p-2 border-zinc-200";
        container.setAttribute('draggable', 'true');
        container.dataset.nodeData = JSON.stringify(node);

        const header = document.createElement('div');
        header.className = "flex items-center p-1 rounded-md hover:bg-zinc-100 cursor-pointer group";

        // Icono de arrastre
        const dragHandle = document.createElement('span');
        dragHandle.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                <path d="M8 6.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM8 12a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM9.5 16a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3ZM13 6.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM13 12a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM14.5 16a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3Z" />
            </svg>
        `;
        dragHandle.className = "text-zinc-400 cursor-move mr-1 md:opacity-0 md:group-hover:opacity-100 transition-opacity";
        dragHandle.title = "Arrastra para mover";

        const toggle = document.createElement('span');
        toggle.innerHTML = hasChildren ? 
            `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                <path fill-rule="evenodd" d="M16.28 11.47a.75.75 0 0 1 0 1.06l-7.5 7.5a.75.75 0 0 1-1.06-1.06L14.69 12 7.72 5.03a.75.75 0 0 1 1.06-1.06l7.5 7.5Z" clip-rule="evenodd" />
            </svg>` : 
            `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                <path fill-rule="evenodd" d="M15.256 3.042a.75.75 0 0 1 .449.962l-6 16.5a.75.75 0 1 1-1.41-.513l6-16.5a.75.75 0 0 1 .961-.449Z" clip-rule="evenodd" />
            </svg>
            `;
        toggle.className = "text-sm text-zinc-500";

        const title = document.createElement('input');
        title.value = node.name;
        title.className = "border-none focus:bg-zinc-100/80 px-2 text-sm rounded outline-none w-fit";

        // Botones de acción
        const btnAdd = document.createElement('button');
        btnAdd.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6">
                <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM12.75 9a.75.75 0 0 0-1.5 0v2.25H9a.75.75 0 0 0 0 1.5h2.25V15a.75.75 0 0 0 1.5 0v-2.25H15a.75.75 0 0 0 0-1.5h-2.25V9Z" clip-rule="evenodd" />
            </svg>

        `;
        btnAdd.title = "Agregar hijo";
        btnAdd.className = "text-zinc-600 hover:text-zinc-800 font-bold md:opacity-0 md:group-hover:opacity-100 transition";

        const btnDelete = document.createElement('button');
        btnDelete.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6">
                <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z" clip-rule="evenodd" />
            </svg>

        `;
        btnDelete.title = "Eliminar nodo";
        btnDelete.className = "text-red-600 hover:text-red-800 font-bold md:opacity-0 md:group-hover:opacity-100 transition";

        header.appendChild(dragHandle);
        header.appendChild(toggle);
        header.appendChild(title);
        header.appendChild(btnAdd);
        header.appendChild(btnDelete);
        container.appendChild(header);

        const childrenContainer = document.createElement('div');
        childrenContainer.className = "ml-2 hidden";

        if (hasChildren) {
            node.children.forEach(child => {
                childrenContainer.appendChild(renderNode(child, node.children));
            });
        }
        
        container.appendChild(childrenContainer);

        // === EVENTOS DRAG & DROP ===
        container.addEventListener('dragstart', (e) => {
            e.stopPropagation();
            draggedNode = node;
            draggedParentArray = parentArray;
            container.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
        });

        container.addEventListener('dragend', (e) => {
            container.classList.remove('dragging');
            document.querySelectorAll('.drag-over').forEach(el => {
                el.classList.remove('drag-over');
            });
        });

        container.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
            
            if (draggedNode !== node && container !== document.querySelector('.dragging')) {
                const rect = header.getBoundingClientRect();
                const midpoint = rect.top + rect.height / 2;
                
                // Si el mouse está en la mitad superior, insertar antes
                // Si está en la mitad inferior, insertar después o como hijo
                if (e.clientY < midpoint) {
                    container.classList.add('drag-over-before');
                    container.classList.remove('drag-over-after', 'drag-over-inside');
                } else {
                    // Si tiene hijos, ofrecer agregar como hijo
                    if (hasChildren || e.shiftKey) {
                        container.classList.add('drag-over-inside');
                        container.classList.remove('drag-over-before', 'drag-over-after');
                    } else {
                        container.classList.add('drag-over-after');
                        container.classList.remove('drag-over-before', 'drag-over-inside');
                    }
                }
            }
        });

        container.addEventListener('dragleave', (e) => {
            e.stopPropagation();
            container.classList.remove('drag-over-before', 'drag-over-after', 'drag-over-inside');
        });

        container.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            
            const dropType = container.classList.contains('drag-over-before') ? 'before' :
                            container.classList.contains('drag-over-after') ? 'after' : 'inside';
            
            container.classList.remove('drag-over-before', 'drag-over-after', 'drag-over-inside');

            if (draggedNode && draggedNode !== node) {
                // Remover del array original
                const oldIndex = draggedParentArray.indexOf(draggedNode);
                if (oldIndex > -1) {
                    draggedParentArray.splice(oldIndex, 1);
                }

                if (dropType === 'inside') {
                    // Agregar como hijo del nodo destino
                    if (!node.children) {
                        node.children = [];
                    }
                    node.children.push(draggedNode);
                } else {
                    // Insertar antes o después del nodo destino (mismo nivel)
                    const targetIndex = parentArray.indexOf(node);
                    const insertIndex = dropType === 'before' ? targetIndex : targetIndex + 1;
                    parentArray.splice(insertIndex, 0, draggedNode);
                }

                // Re-renderizar el árbol
                const root = document.getElementById('projectTree');
                renderTree(projectData, root);
                
                console.log('Nodo movido exitosamente:', dropType);
            }
        });

        // === EVENTOS EXISTENTES ===
        header.addEventListener('click', (e) => {
            if (e.target === btnAdd || e.target === btnDelete || e.target === title) return;
            const isHidden = childrenContainer.classList.toggle('hidden');
            toggle.innerHTML = isHidden ? 
                `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                    <path fill-rule="evenodd" d="M16.28 11.47a.75.75 0 0 1 0 1.06l-7.5 7.5a.75.75 0 0 1-1.06-1.06L14.69 12 7.72 5.03a.75.75 0 0 1 1.06-1.06l7.5 7.5Z" clip-rule="evenodd" />
                </svg>` : 
                `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                    <path fill-rule="evenodd" d="M12.53 16.28a.75.75 0 0 1-1.06 0l-7.5-7.5a.75.75 0 0 1 1.06-1.06L12 14.69l6.97-6.97a.75.75 0 1 1 1.06 1.06l-7.5 7.5Z" clip-rule="evenodd" />
                </svg>
                `;
        });

        // Agregar nuevo hijo
        btnAdd.addEventListener('click', (e) => {
            e.stopPropagation();
            if (!node.children) node.children = [];
            const newNode = { name: "Nuevo elemento", deletable: true, children: [] };
            node.children.push(newNode);
            childrenContainer.appendChild(renderNode(newNode, node.children));
            childrenContainer.classList.remove('hidden');
            toggle.innerHTML = 
                `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-4">
                    <path fill-rule="evenodd" d="M12.53 16.28a.75.75 0 0 1-1.06 0l-7.5-7.5a.75.75 0 0 1 1.06-1.06L12 14.69l6.97-6.97a.75.75 0 1 1 1.06 1.06l-7.5 7.5Z" clip-rule="evenodd" />
                </svg>`;
        });

        // Eliminar nodo
        btnDelete.addEventListener('click', (e) => {
            e.stopPropagation();
            if (confirm('¿Estás seguro de eliminar este elemento y todos sus hijos?')) {
                const index = parentArray.indexOf(node);
                if (index > -1) parentArray.splice(index, 1);
                container.remove();
            }
        });

        // Editar nombre
        title.addEventListener('input', () => {
            node.name = title.value;
        });

        return container;
    }

    function renderTree(data, root) {
        root.innerHTML = "";
        data.forEach(node => {
            root.appendChild(renderNode(node, data));
        });
    }

    // Guardar estructura en el archivo JSON
    document.getElementById('saveStructureBtn').addEventListener('click', async () => {
        const { postClient } = useSettingApi();
        try {
            const response = await postClient(projectData);
            if (response.success) {
                alert('Estructura guardada exitosamente');
                console.log("Estructura guardada:", projectData);
            } else {
                alert('Hubo un problema: ' + response.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error al guardar la estructura');
        }
    });

    document.addEventListener('DOMContentLoaded', () => {
        const root = document.getElementById('projectTree');
        renderTree(projectData, root);
    });
</script>

<?php include_once __DIR__.'/components/includes/Footer.php'; ?>