/**
 * Funcionalidad Drag & Drop para reordenar rotaciones
 */

document.addEventListener('DOMContentLoaded', function() {
    const list = document.getElementById('sortable-list');
    if (!list) return;

    let draggedItem = null;

    // Inicializar eventos para items
    function setupItems() {
        const items = list.querySelectorAll('.drag-item');
        items.forEach(item => {
            item.setAttribute('draggable', true);
            
            item.addEventListener('dragstart', function(e) {
                draggedItem = item;
                setTimeout(() => item.classList.add('dragging'), 0);
            });

            item.addEventListener('dragend', function() {
                setTimeout(() => {
                    item.classList.remove('dragging');
                    draggedItem = null;
                }, 0);
                saveOrder(); // Guardar automáticamente al soltar
            });
        });
    }

    // Eventos de la lista
    list.addEventListener('dragover', function(e) {
        e.preventDefault();
        const afterElement = getDragAfterElement(list, e.clientY);
        const currentItem = document.querySelector('.dragging');
        
        if (afterElement == null) {
            list.appendChild(currentItem);
        } else {
            list.insertBefore(currentItem, afterElement);
        }
    });

    // Helper para determinar posición
    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.drag-item:not(.dragging)')];

        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    // Guardar orden via AJAX
    function saveOrder() {
        const items = list.querySelectorAll('.drag-item');
        const order = Array.from(items).map(item => item.dataset.id);
        
        const feedback = document.getElementById('save-feedback');
        if (feedback) feedback.textContent = 'Guardando...';

        fetch('reorganizar.php?action=save_order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ order: order })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (feedback) {
                    feedback.textContent = 'Orden guardado correctamente';
                    feedback.className = 'text-success';
                    setTimeout(() => feedback.textContent = '', 2000);
                }
            } else {
                if (feedback) {
                    feedback.textContent = 'Error al guardar';
                    feedback.className = 'text-danger';
                }
                alert('Hubo un error al guardar el orden');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (feedback) feedback.textContent = 'Error de conexión';
        });
    }

    setupItems();
});
