/**
 * No-Code Integration Updates
 * This file handles workflow container improvements in the no-code interface
 */

function enhanceBlockManager() {
    if (!window.blockManager) return;
    
    const originalCreateBlockElement = window.blockManager.createBlockElement;
    
    window.blockManager.createBlockElement = function(block, index) {
        const blockEl = document.createElement('div');
        blockEl.className = 'workflow-block';
        blockEl.id = block.id;
        blockEl.setAttribute('draggable', 'true');
        
        // Create main container
        const mainContainer = document.createElement('div');
        mainContainer.className = 'workflow-block-container';
        
        // Left section: Handle + Icon + Type
        const leftSection = document.createElement('div');
        leftSection.className = 'workflow-block-left';
        
        const dragHandle = document.createElement('div');
        dragHandle.className = 'block-drag-handle';
        dragHandle.innerHTML = '⋮⋮';
        
        const blockIcon = document.createElement('div');
        blockIcon.className = 'block-icon';
        switch(block.type) {
            case 'drawText':
                blockIcon.style.backgroundColor = '#0A1F5C';
                blockIcon.style.color = '#93C5FD';
                blockIcon.innerHTML = 'T';
                break;
            case 'setPixel':
                blockIcon.style.backgroundColor = '#022018';
                blockIcon.style.color = '#6EE7B7';
                blockIcon.innerHTML = '•';
                break;
            case 'getData':
                blockIcon.style.backgroundColor = '#3A1407';
                blockIcon.style.color = '#FDBA74';
                blockIcon.innerHTML = '{}';
                break;
        }
        
        const blockType = document.createElement('div');
        blockType.className = 'block-type';
        blockType.textContent = block.type === 'drawText' ? 'Text' : 
                              block.type === 'setPixel' ? 'Pixel' : 'Data';
        
        leftSection.appendChild(dragHandle);
        leftSection.appendChild(blockIcon);
        leftSection.appendChild(blockType);
        
        // Middle section: Block properties
        const middleSection = document.createElement('div');
        middleSection.className = 'workflow-block-middle';
        
        const blockSummary = document.createElement('div');
        blockSummary.className = 'block-summary';
        
        switch(block.type) {
            case 'drawText':
                blockSummary.innerHTML = `Text: "${block.properties.text || ''}" at (${block.properties.x || 0}, ${block.properties.y || 0})`;
                if (block.properties.color) {
                    const colorSwatch = document.createElement('div');
                    colorSwatch.className = 'color-swatch';
                    colorSwatch.style.backgroundColor = block.properties.color;
                    blockSummary.appendChild(colorSwatch);
                }
                break;
            case 'setPixel':
                blockSummary.innerHTML = `Position: (${block.properties.x || 0}, ${block.properties.y || 0})`;
                if (block.properties.color) {
                    const colorSwatch = document.createElement('div');
                    colorSwatch.className = 'color-swatch';
                    colorSwatch.style.backgroundColor = block.properties.color;
                    blockSummary.appendChild(colorSwatch);
                }
                break;
            case 'getData':
                blockSummary.innerHTML = `URL: ${block.properties.url || 'api.example.com'}`;
                break;
        }
        
        middleSection.appendChild(blockSummary);
        
        // Right section: Layer + Actions
        const rightSection = document.createElement('div');
        rightSection.className = 'workflow-block-right';
        
        const layerIndicator = document.createElement('div');
        layerIndicator.className = 'layer-indicator';
        
        // Get total number of blocks
        const totalBlocks = window.blockManager.blocks.length;
        
        // Set layer text based on position
        if (index === 0) {
            layerIndicator.textContent = 'Bottom Layer';
        } else if (index === totalBlocks - 1) {
            layerIndicator.textContent = 'Top Layer';
        } else {
            layerIndicator.textContent = `Layer ${index + 1}`;
        }
        
        const actionsContainer = document.createElement('div');
        actionsContainer.className = 'block-actions';
        
        const editButton = document.createElement('button');
        editButton.className = 'block-edit';
        editButton.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M11 4H4C3.44772 4 3 4.44772 3 5V19C3 19.5523 3.44772 20 4 20H18C18.5523 20 19 19.5523 19 19V12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M17.5 2.5C18.3284 1.67157 19.6716 1.67157 20.5 2.5C21.3284 3.32843 21.3284 4.67157 20.5 5.5L12 14L8 15L9 11L17.5 2.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        `;
        editButton.title = 'Edit';
        editButton.onclick = (e) => {
            e.stopPropagation();
            window.blockManager.selectBlock(block.id);
        };
        
        const deleteButton = document.createElement('button');
        deleteButton.className = 'block-delete';
        deleteButton.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M3 6H5H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        `;
        deleteButton.title = 'Delete';
        deleteButton.onclick = (e) => {
            e.stopPropagation();
            window.blockManager.removeBlock(block.id);
        };
        
        actionsContainer.appendChild(editButton);
        actionsContainer.appendChild(deleteButton);
        
        rightSection.appendChild(layerIndicator);
        rightSection.appendChild(actionsContainer);
        
        // Assemble all sections
        mainContainer.appendChild(leftSection);
        mainContainer.appendChild(middleSection);
        mainContainer.appendChild(rightSection);
        blockEl.appendChild(mainContainer);
        
        // Add click handler for block selection
        blockEl.addEventListener('click', () => {
            window.blockManager.selectBlock(block.id);
        });
        
        return blockEl;
    };

    // Keep existing drag and drop enhancement code
    const originalSetupDragReordering = window.blockManager.setupDragReordering;
    window.blockManager.setupDragReordering = function() {
        originalSetupDragReordering.call(this);
        
        const workflowArea = document.querySelector('.workflow-area');
        if (!workflowArea) return;
        
        workflowArea.addEventListener('dragover', e => {
            e.preventDefault();
            workflowArea.classList.add('active-drag-over');
        });
        
        workflowArea.addEventListener('dragleave', () => {
            workflowArea.classList.remove('active-drag-over');
        });
        
        workflowArea.addEventListener('drop', () => {
            workflowArea.classList.remove('active-drag-over');
        });
    };

    // Add debounce function at the top
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Create debounced preview update
    const debouncedPreviewUpdate = debounce(() => {
        window.updatePreview();
        
        // Handle notification
        const existingNotification = document.querySelector('.preview-notification');
        if (existingNotification) {
            existingNotification.remove();
        }
        
        const notification = document.createElement('div');
        notification.className = 'preview-notification';
        notification.textContent = 'Preview Updated';
        document.querySelector('.preview-section').appendChild(notification);
        
        // Remove notification after 2 seconds
        setTimeout(() => {
            notification.remove();
        }, 2000);
    }, 500);

    // Add this to your color change handler
    document.addEventListener('input', function(e) {
        if (e.target.matches('.block-properties input[type="color"], .block-properties input[data-property="color"]')) {
            const blockId = window.blockManager.selectedBlockId;
            if (!blockId) return;

            const block = window.blockManager.blocks.find(b => b.id === blockId);
            if (!block) return;

            // Update the block properties
            block.properties.color = e.target.value;

            // Update the UI
            const blockEl = document.getElementById(blockId);
            if (blockEl) {
                const colorSwatch = blockEl.querySelector('.color-swatch');
                if (colorSwatch) {
                    colorSwatch.style.backgroundColor = e.target.value;
                } else {
                    const summary = blockEl.querySelector('.block-summary');
                    if (summary) {
                        const newSwatch = document.createElement('div');
                        newSwatch.className = 'color-swatch';
                        newSwatch.style.backgroundColor = e.target.value;
                        summary.appendChild(newSwatch);
                    }
                }
            }

            // Use debounced preview update
            if (window.autoPreviewEnabled) {
                debouncedPreviewUpdate();
            }
        }
    });
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    enhanceBlockManager();
});

/**
 * Setup the block library as the single source for blocks
 * This removes any duplicate blocks in the workflow and enhances 
 * the library interaction
 */
function setupBlockLibraryAsSource() {
    // Find the block items from the library
    const blockItems = document.querySelectorAll('.block-item');
    
    // Find the workflow area
    const workflowArea = document.querySelector('.workflow-area');
    
    if (!blockItems.length || !workflowArea) return;
    
    // Enhance library appearance
    blockItems.forEach(item => {
        
        // Make library items clearly draggable
        item.setAttribute('draggable', 'true');
        item.style.cursor = 'grab';
        
        // Add visual indicator for dragging
        item.addEventListener('dragstart', () => {
            item.classList.add('dragging');
        });
        
        item.addEventListener('dragend', () => {
            item.classList.remove('dragging');
        });
    });
    
    // Remove block toolbar from the workflow container (the duplicative elements)
    const blockToolbar = document.querySelector('.block-toolbar');
    if (blockToolbar) {
        blockToolbar.remove();
    }
    
    // Clear any existing blocks in the workflow area by default
    // No need to add blocks directly to workflow - they should come from library
    const existingBlocks = workflowArea.querySelectorAll('.workflow-block:not(.empty-workflow-message)');
    existingBlocks.forEach(block => {
        workflowArea.removeChild(block);
    });
    
    // Add empty state message if needed
    if (workflowArea.children.length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'empty-workflow-message';
        emptyMessage.innerHTML = '<p>Drag blocks from the library to start building your application</p>';
        workflowArea.appendChild(emptyMessage);
    }
    
    // Make sure the workflow area has the right styles for drag operations
    workflowArea.style.minHeight = '150px';
    
    // Add custom style for enhanced drag and drop
    const style = document.createElement('style');
    style.textContent = `
      
    `;
    document.head.appendChild(style);
}

/**
 * Initialize the enhancements when the DOM is ready
 */
function initEnhancements() {
    // Wait for the block manager to be initialized
    const checkBlockManager = setInterval(() => {
        if (window.blockManager) {
            clearInterval(checkBlockManager);
            enhanceBlockManager();
            setupBlockLibraryAsSource();
            console.log("✅ No-Code workflow enhancements applied!");
        }
    }, 100);
    
    // Only check for 5 seconds, then give up to avoid infinite loop
    setTimeout(() => {
        clearInterval(checkBlockManager);
        console.log("⚠️ Could not enhance workflow - blockManager not found");
    }, 5000);
    
    // Also ensure to remove block toolbar from the DOM even if blockManager not ready
    setTimeout(() => {
        const blockToolbar = document.querySelector('.block-toolbar');
        if (blockToolbar) {
            blockToolbar.remove();
            console.log("✅ Removed duplicative block toolbar");
        }
    }, 300);
}

// Initialize when the page is loaded
if (document.readyState === "complete" || document.readyState === "interactive") {
    initEnhancements();
} else {
    document.addEventListener("DOMContentLoaded", initEnhancements);
}

// Apply custom styles for workflow blocks to make them smaller vertically
function applyCompactStyles() {
    const style = document.createElement('style');
    style.textContent = `
      
    `;
    document.head.appendChild(style);
}

// Enhanced drag-and-drop support for reordering workflow items
function enhanceDragAndDrop() {
    const workflowArea = document.querySelector('.workflow-area');
    if (!workflowArea) return;
    
    // Make sure blockManager exists
    if (!window.blockManager) {
        console.warn("BlockManager not found - drag-and-drop may not work properly");
        return;
    }
    
    // Override the setupDragReordering method to improve it
    const originalSetupDragReordering = window.blockManager.setupDragReordering;
    
    window.blockManager.setupDragReordering = function() {
        // Call original method first if it exists
        if (typeof originalSetupDragReordering === 'function') {
            originalSetupDragReordering.call(this);
        }
        
        const workflowArea = document.querySelector('.workflow-area');
        if (!workflowArea) return;
        
        const blocks = workflowArea.querySelectorAll('.workflow-block');
        
        // Make all blocks draggable
        blocks.forEach(block => {
            block.setAttribute('draggable', 'true');
            
            block.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', block.id);
                block.classList.add('dragging');
                
                // Delay adding opacity for the drag image
                setTimeout(() => {
                    block.style.opacity = '0.6';
                }, 0);
            });
            
            block.addEventListener('dragend', () => {
                block.classList.remove('dragging');
                block.style.opacity = '1';
                
                // Remove all drop indicators
                document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
                workflowArea.classList.remove('drag-over');
            });
        });
        
        // Allow dropping
        workflowArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            workflowArea.classList.add('drag-over');
            
            // Find closest block
            const draggingBlock = document.querySelector('.dragging');
            if (!draggingBlock) return;
            
            const afterElement = this.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);
            }
        });
    };
    
    // Force re-run the setup
    if (typeof window.blockManager.setupDragReordering === 'function') {
        window.blockManager.setupDragReordering();
    }
}

// Initialize enhancements
function initWorkflowEnhancements() {

    
    // Setup resizable workflow/preview
    setupResizableWorkflowPreview();
    
    // Rest of initialization...
}

function setupResizableWorkflowPreview() {
    const workflowContainer = document.querySelector('.workflow-container');
    const previewSection = document.querySelector('.preview-section');
    
    if (!workflowContainer || !previewSection) return;
    
    // Create resize handle
    const resizeHandle = document.createElement('div');
    resizeHandle.className = 'resize-handle';
    workflowContainer.appendChild(resizeHandle);
    
    let isResizing = false;
    let startY = 0;
    let startHeight = 0;
    
    resizeHandle.addEventListener('mousedown', (e) => {
        isResizing = true;
        startY = e.clientY;
        startHeight = workflowContainer.offsetHeight;
        document.body.style.cursor = 'ns-resize';
    });
    
    document.addEventListener('mousemove', (e) => {
        if (!isResizing) return;
        
        const delta = e.clientY - startY;
        const newHeight = startHeight + delta;
        const containerHeight = workflowContainer.parentElement.offsetHeight;
        
        // Enforce min/max constraints
        if (newHeight > 100 && newHeight < (containerHeight - 100)) {
            workflowContainer.style.height = newHeight + 'px';
            previewSection.style.height = (containerHeight - newHeight - 1) + 'px';
        }
    });
    
    document.addEventListener('mouseup', () => {
        isResizing = false;
        document.body.style.cursor = '';
    });
}

// Run when DOM is ready
document.addEventListener('DOMContentLoaded', initWorkflowEnhancements);

// If DOM is already loaded, run immediately
if (document.readyState === 'interactive' || document.readyState === 'complete') {
    initWorkflowEnhancements();
}

function enhanceWorkflow() {
    // Check if blockManager exists in window scope
    if (!window.blockManager) {
        console.warn('⚠️ Could not enhance workflow - blockManager not found');
        // Create a new block manager if it doesn't exist
        window.blockManager = new BlockManager();
    }
    
    // Continue with enhancements
    // ... rest of enhancement code ...
}
  