// ============================================
// KOMPLETT NEUES DRAG & DROP SYSTEM
// Einfach, klar, funktioniert garantiert
// ============================================

function initDragDropNew(){
    console.log('🚀 Starting NEW Drag & Drop System');
    
    let draggedCard = null;
    let draggedSection = null;
    
    // 1. ALLE CARDS DRAGGABLE MACHEN
    function makeCardsDraggable(){
        document.querySelectorAll('.card').forEach(card => {
            card.setAttribute('draggable', 'true');
            card.style.cursor = 'move';
        });
        console.log('✓ Made all cards draggable');
    }
    
    // 2. DRAG START - Card wird gegriffen
    document.addEventListener('dragstart', e => {
        const card = e.target.closest('.card');
        if(!card) return;
        
        draggedCard = card;
        card.classList.add('dragging');
        card.style.opacity = '0.5';
        
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', card.innerHTML);
        
        console.log('🎯 Dragging:', card.getAttribute('data-card-id'));
    });
    
    // 3. DRAG OVER - Über Drop-Zone schweben
    document.addEventListener('dragover', e => {
        if(!draggedCard) return;
        e.preventDefault(); // WICHTIG!
        
        // Finde Drop-Zone
        const dropZone = e.target.closest('.section-content.cards, #toolboxCards');
        if(!dropZone) return;
        
        // Finde nächste Card unter Maus
        const afterElement = getDragAfterElement(dropZone, e.clientY);
        
        if(afterElement == null){
            dropZone.appendChild(draggedCard);
        } else {
            dropZone.insertBefore(draggedCard, afterElement);
        }
    });
    
    // 4. DROP - Card ablegen
    document.addEventListener('drop', e => {
        e.preventDefault();
        if(draggedCard){
            console.log('✓ Dropped card');
            saveCardOrder();
            updateDeleteIcons();
        }
    });
    
    // 5. DRAG END - Aufräumen
    document.addEventListener('dragend', e => {
        if(draggedCard){
            draggedCard.classList.remove('dragging');
            draggedCard.style.opacity = '';
            draggedCard = null;
        }
    });
    
    // HELPER: Finde Element unter Maus
    function getDragAfterElement(container, y){
        const draggableElements = [...container.querySelectorAll('.card: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;
    }
    
    // DELETE ICON Management
    function updateDeleteIcons(){
        document.querySelectorAll('.card').forEach(card => {
            const isInToolbox = card.closest('#toolboxCards');
            let deleteIcon = card.querySelector('.card-delete-icon');
            
            if(!isInToolbox && !deleteIcon){
                deleteIcon = document.createElement('button');
                deleteIcon.className = 'card-delete-icon';
                deleteIcon.innerHTML = '<i class="fa fa-times"></i>';
                deleteIcon.title = 'Zurück zur Cards Box';
                deleteIcon.onclick = (e) => {
                    e.stopPropagation();
                    returnCardToToolbox(card);
                };
                const actions = card.querySelector('.card-actions');
                if(actions) actions.appendChild(deleteIcon);
            } else if(isInToolbox && deleteIcon){
                deleteIcon.remove();
            }
        });
    }
    
    // Return card mit Animation
    function returnCardToToolbox(card){
        const toolbox = document.getElementById('toolboxCards');
        if(!toolbox) return;
        
        card.style.transition = 'all 0.3s ease';
        card.style.transform = 'scale(0.5)';
        card.style.opacity = '0';
        
        setTimeout(() => {
            toolbox.appendChild(card);
            card.style.transition = '';
            card.style.transform = '';
            card.style.opacity = '';
            updateDeleteIcons();
            saveCardOrder();
            showToast('Karte zurück zur Box', 'success');
        }, 300);
    }
    
    window.returnCardToToolbox = returnCardToToolbox;
    
    // INITIALIZE
    makeCardsDraggable();
    updateDeleteIcons();
    
    // Re-apply nach DOM changes
    const observer = new MutationObserver(makeCardsDraggable);
    const dashboard = document.getElementById('dashboardContainer');
    if(dashboard) observer.observe(dashboard, { childList: true, subtree: true });
    
    // BUTTONS
    const resetBtn = document.getElementById('resetLayout');
    if(resetBtn){
        resetBtn.onclick = () => {
            localStorage.removeItem('dashboardCardOrder');
            localStorage.removeItem('dashboardCardHistory');
            location.reload();
        };
    }
    
    const saveServerBtn = document.getElementById('saveServerLayout');
    if(saveServerBtn){
        saveServerBtn.onclick = async () => {
            const toolbox = document.getElementById('toolboxCards');
            const sections = document.querySelectorAll('.section-content.cards');
            const ids = [];
            
            if(toolbox) ids.push(...[...toolbox.querySelectorAll('.card')].map(c => c.getAttribute('data-card-id')));
            sections.forEach(s => ids.push(...[...s.querySelectorAll('.card')].map(c => c.getAttribute('data-card-id'))));
            
            try {
                const r = await fetch('?action=saveLayout', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({order: ids})
                });
                const j = await r.json();
                if(j && j.success){
                    showToast('Layout gespeichert', 'success');
                } else {
                    showToast('Fehler: ' + (j.error || 'unknown'), 'error');
                }
            } catch(e){
                showToast('Netzwerkfehler: ' + e.message, 'error');
            }
        };
    }
    
    console.log('✓ Drag & Drop System ready!');
}

// Export for use in admin.js
if(typeof window !== 'undefined'){
    window.initDragDropNew = initDragDropNew;
}
