/**
 * Fixed Drag and Drop Implementation for GLANCE LED Panel Developer Platform
 * This script focuses only on improving the drag-and-drop functionality
 * without changing the preview behavior.
 */

document.addEventListener('DOMContentLoaded', function() {
    // Only initialize in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    console.log("Initializing Fixed Drag and Drop...");
    initFixedDragDrop();
});

/**
 * Initialize the fixed drag and drop functionality
 */
function initFixedDragDrop() {
    // Add improved visual styles
    addImprovedStyles();
    
    // Setup library drag-to-workflow functionality
    setupLibraryDragDrop();
    
    // Setup workflow block reordering
    setupWorkflowReordering();
    
    // Apply DOM updates to existing blocks
    updateExistingBlocks();
}

/**
 * Add improved visual styles for blocks and drag operations
 */
function addImprovedStyles() {
    const styleId = 'fixed-drag-drop-styles';
    
    // Don't add styles if they already exist
    if (document.getElementById(styleId)) return;
    
    const style = document.createElement('style');
    style.id = styleId;
    style.textContent = `
        .block-library::-webkit-scrollbar {
            width: 8px;
        }

        .block-library::-webkit-scrollbar-track {
            background: var(--bg-darker);
            border-radius: 4px;
        }

        .block-library::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 4px;
        }

        .block-library::-webkit-scrollbar-thumb:hover {
            background: var(--text-muted);
        }

        .block-item.dragging {
            opacity: 0.5;
        }
    `;
    
    document.head.appendChild(style);
}

/**
 * Setup drag from library to workflow
 */
function setupLibraryDragDrop() {
    const blockItems = document.querySelectorAll('.block-item');
    const workflowArea = document.querySelector('.workflow-area');
    
    if (!blockItems.length || !workflowArea) {
        console.error("Block items or workflow area not found");
        return;
    }
    
    // Make library blocks draggable
    blockItems.forEach(item => {
        item.setAttribute('draggable', 'true');
        
        item.addEventListener('dragstart', (e) => {
            const blockType = item.getAttribute('data-block-type');
            e.dataTransfer.setData('application/block-type', blockType);
            e.dataTransfer.effectAllowed = 'copy';
            item.classList.add('dragging');
        });
        
        item.addEventListener('dragend', () => {
            item.classList.remove('dragging');
        });
    });
    
    // Make workflow area a drop target
    workflowArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        workflowArea.classList.add('drag-over');
    });
    
    workflowArea.addEventListener('dragleave', (e) => {
        // Only remove highlight when actually leaving the container
        const rect = workflowArea.getBoundingClientRect();
        if (
            e.clientX <= rect.left ||
            e.clientX >= rect.right ||
            e.clientY <= rect.top ||
            e.clientY >= rect.bottom
        ) {
            workflowArea.classList.remove('drag-over');
        }
    });
    
    workflowArea.addEventListener('drop', (e) => {
        e.preventDefault();
        workflowArea.classList.remove('drag-over');
        
        // Handle drop from library
        const blockType = e.dataTransfer.getData('application/block-type');
        if (blockType && window.blockManager) {
            // Get default properties for this block type
            const properties = getDefaultProperties(blockType);
            
            // Add block to workflow
            window.blockManager.addBlock({
                type: blockType,
                properties: properties
            });
        }
    });
}

/**
 * Setup reordering blocks within the workflow
 */
function setupWorkflowReordering() {
    const workflowArea = document.querySelector('.workflow-area');
    if (!workflowArea) return;
    
    // Use mutation observer to watch for new blocks being added
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type === 'childList' && mutation.addedNodes.length) {
                // For each added node that's a workflow block
                mutation.addedNodes.forEach(node => {
                    if (node.classList && node.classList.contains('workflow-block')) {
                        setupDraggableBlock(node);
                    }
                });
            }
        });
    });
    
    // Start observing
    observer.observe(workflowArea, { childList: true });
    
    // Also setup workflow area to handle dropping
    workflowArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        
        // Get dragging block
        const draggingBlock = workflowArea.querySelector('.dragging');
        if (!draggingBlock) return;
        
        // Find drag position
        const afterElement = getDragAfterElement(workflowArea, e.clientY);
        
        // Remove existing drop indicators
        document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
        
        // Create a drop indicator
        const dropIndicator = document.createElement('div');
        dropIndicator.className = 'block-drop-indicator';
        
        if (afterElement) {
            workflowArea.insertBefore(dropIndicator, afterElement);
        } else {
            workflowArea.appendChild(dropIndicator);
        }
    });
    
    workflowArea.addEventListener('drop', (e) => {
        e.preventDefault();
        
        // Remove drop indicators
        document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
        
        // Get dragging block ID from data transfer
        const blockId = e.dataTransfer.getData('text/plain');
        if (!blockId || !window.blockManager) return;
        
        const draggingBlock = document.getElementById(blockId);
        if (!draggingBlock) return;
        
        // Find drop position
        const afterElement = getDragAfterElement(workflowArea, e.clientY);
        
        // Get indices for reordering
        const currentIndex = parseInt(draggingBlock.getAttribute('data-index') || '0');
        let newIndex;
        
        if (afterElement) {
            newIndex = parseInt(afterElement.getAttribute('data-index') || '0');
            if (currentIndex < newIndex) {
                newIndex--;
            }
        } else {
            newIndex = window.blockManager.blocks.length - 1;
        }
        
        // Skip if same position
        if (newIndex === currentIndex) return;
        
        // Reorder blocks in the block manager
        const [movedBlock] = window.blockManager.blocks.splice(currentIndex, 1);
        window.blockManager.blocks.splice(newIndex, 0, movedBlock);
        
        // Re-render workflow
        window.blockManager.renderWorkflow();
    });
    
    // Setup existing blocks initially
    workflowArea.querySelectorAll('.workflow-block').forEach(block => {
        setupDraggableBlock(block);
    });
}

/**
 * Make a workflow block draggable
 */
function setupDraggableBlock(block) {
    if (!block) return;
    
    // Make sure it's draggable
    block.setAttribute('draggable', 'true');
    
    // Setup drag events if not already set
    if (!block.getAttribute('data-drag-setup')) {
        block.addEventListener('dragstart', function(e) {
            e.dataTransfer.setData('text/plain', block.id);
            block.classList.add('dragging');
        });
        
        block.addEventListener('dragend', function() {
            block.classList.remove('dragging');
            // Remove all drop indicators
            document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
        });
        
        // Mark as setup
        block.setAttribute('data-drag-setup', 'true');
    }
}

/**
 * Helper function to determine where to drop when reordering
 */
function getDragAfterElement(container, y) {
    // Get all non-dragging blocks
    const draggableElements = [...container.querySelectorAll('.workflow-block: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;
}

/**
 * Get default properties for a block type
 */
function getDefaultProperties(blockType) {
    // Get canvas dimensions
    const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
    const [canvasWidth, canvasHeight] = canvasSize.split('x').map(Number);
    
    switch(blockType) {
        case 'drawText':
            return {
                text: 'GLANCE',
                x: 5,
                y: 10,
                color: '#00FF00',
                font: 'bitmap_5x7',
                alignment: 'left'
            };
            
        case 'setPixel':
            return {
                x: Math.floor(canvasWidth / 2),
                y: Math.floor(canvasHeight / 2),
                color: '#FFFFFF'
            };
            
        case 'getData':
            return {
                url: 'https://api.example.com/data',
                apiKey: '',
                variable: 'data'
            };
            
        default:
            return {};
    }
}

/**
 * Update existing blocks to have the right structure
 */
function updateExistingBlocks() {
    // Update existing blocks to have better structure
    setTimeout(() => {
        const workflowBlocks = document.querySelectorAll('.workflow-block');
        
        workflowBlocks.forEach(block => {
            // Make draggable
            setupDraggableBlock(block);
            
            // Check if it already has a title container
            if (!block.querySelector('.block-title-container')) {
                // Get block title and icon elements
                const blockTitle = block.querySelector('.block-title');
                const blockIcon = block.querySelector('.block-icon');
                
                if (blockTitle && blockIcon && blockTitle.parentNode) {
                    // Create title container
                    const titleContainer = document.createElement('div');
                    titleContainer.className = 'block-title-container';
                    
                    // Move icon and text into container
                    const titleText = document.createElement('span');
                    titleText.className = 'block-title-text';
                    titleText.textContent = blockTitle.textContent.replace(blockIcon.textContent, '').trim();
                    
                    // Keep original icon
                    titleContainer.appendChild(blockIcon);
                    titleContainer.appendChild(titleText);
                    
                    // Replace original title with container
                    blockTitle.parentNode.replaceChild(titleContainer, blockTitle);
                }
            }
        });
    }, 500); // Wait for blocks to be rendered
}