/**
 * No-Code Interface for GLANCE LED Panel Developer Platform
 * This script enables the drag-and-drop interface, block management,
 * and real-time preview for the no-code environment.
 */

// Only initialize when in no-code mode
document.addEventListener('DOMContentLoaded', function() {
    // Check if we're in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    console.log("Initializing No-Code Interface...");
    
    // Initialize the No-Code Interface
    initNoCodeInterface();
});

/**
 * Initialize the no-code interface
 */
function initNoCodeInterface() {
    // Create the block manager first
    window.blockManager = createBlockManager();
    
    // Setup drag-and-drop from library to workflow
    setupBlockLibrary();
    
    // Setup preview button
    setupPreviewButton();
    
    // Create workflow area if it doesn't exist
    createWorkflowArea();

    // Initialize the properties panel
    initPropertiesPanel();
    
    // Initialize the canvas
    if (window.canvas) {
        console.log("Canvas already initialized");
    } else {
        window.canvas = new CanvasHandler('preview-canvas', {
            enableGrid: true,
            enableTooltips: true,
            enableControls: true,
            initialZoom: 1,
            gridColor: 'rgba(255, 255, 255, 0.1)'
        });
    }
    
    // Initialize compiler
    if (!window.compiler) {
        window.compiler = new Compiler();
        window.compiler.setCanvas(window.canvas);
    }
    
    // Setup the block toolbar
    // setupBlockToolbar();
    
    // Setup submit button for publishing
    setupSubmitButton();
}

// initialize properties panel
function initPropertiesPanel() {
    const properties = document.querySelector('.properties');
    if (!properties) return;
    
    const title = properties.querySelector('.section-title');
    if (!title) return;
    
    title.addEventListener('click', () => {
        properties.classList.toggle('collapsed');
    });
}

// Add this near the beginning of no-code.js
/**
 * Setup the block library drag-and-drop functionality
 */
function setupBlockLibrary() {
    console.log("Setting up block library...");
    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;
    }
    
    blockItems.forEach(blockItem => {
        blockItem.addEventListener('dragstart', (e) => {
            const blockType = blockItem.getAttribute('data-block-type');
            e.dataTransfer.setData('application/blockType', blockType);
            blockItem.classList.add('dragging');
        });
        
        blockItem.addEventListener('dragend', () => {
            blockItem.classList.remove('dragging');
        });
    });
    
    // Setup workflow area as drop target
    workflowArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        workflowArea.classList.add('drag-over');
    });
    
    workflowArea.addEventListener('dragleave', (e) => {
        const rect = workflowArea.getBoundingClientRect();
        const isLeaving = 
            e.clientX <= rect.left ||
            e.clientX >= rect.right ||
            e.clientY <= rect.top ||
            e.clientY >= rect.bottom;
            
        if (isLeaving) {
            workflowArea.classList.remove('drag-over');
        }
    });
    
    workflowArea.addEventListener('drop', (e) => {
        e.preventDefault();
        workflowArea.classList.remove('drag-over');
        
        const blockType = e.dataTransfer.getData('application/blockType');
        if (!blockType) return;
        
        // Create a new block with default properties
        const blockData = {
            type: blockType,
            properties: getDefaultProperties(blockType)
        };
        
        window.blockManager.addBlock(blockData);
    });
}

/**
 * Create the block manager object to handle workflow blocks
 */
function createBlockManager() {
    return {
        blocks: [],
        selectedBlockId: null,
        
        // Add a new block to the workflow
        addBlock: function(blockData) {
            const blockId = 'block-' + Date.now();
            const newBlock = {
                id: blockId,
                type: blockData.type,
                properties: blockData.properties || {}
            };
            
            this.blocks.push(newBlock);
            this.renderWorkflow();
            this.selectBlock(blockId);
            return blockId;
        },
        
        // Remove a block from the workflow
        removeBlock: function(blockId) {
            this.blocks = this.blocks.filter(block => block.id !== blockId);
            if (this.selectedBlockId === blockId) {
                this.selectedBlockId = null;
                this.updatePropertiesPanel();
            }
            this.renderWorkflow();
        },
        
        // Update a block's properties
        updateBlock: function(blockId, properties) {
            const blockIndex = this.blocks.findIndex(block => block.id === blockId);
            if (blockIndex !== -1) {
                this.blocks[blockIndex].properties = { 
                    ...this.blocks[blockIndex].properties,
                    ...properties
                };
                this.renderWorkflow();
                this.updateBlockSummary(blockId);
            }
        },
        
        // Select a block to edit its properties
        selectBlock: function(blockId) {
            this.selectedBlockId = blockId;
            
            // Highlight the selected block
            document.querySelectorAll('.workflow-block').forEach(blockEl => {
                blockEl.classList.remove('selected');
            });
            
            const blockEl = document.getElementById(blockId);
            if (blockEl) {
                blockEl.classList.add('selected');
            }
            
            this.updatePropertiesPanel();
        },
        
        // Render all blocks in the workflow
        renderWorkflow: function() {
            const workflowArea = document.querySelector('.workflow-area');
            if (!workflowArea) return;
            
            // Clear existing blocks
            workflowArea.innerHTML = '';
            
            if (this.blocks.length === 0) {
                workflowArea.innerHTML = `
                    <div class="empty-workflow-message">
                        <p>Drag blocks from the library to start building your application</p>
                    </div>
                `;
                return;
            }
            
            // Render each block
            this.blocks.forEach((block, index) => {
                const blockEl = this.createBlockElement(block, index);
                workflowArea.appendChild(blockEl);
            });
            
            // Setup drag-and-drop reordering
            this.setupDragReordering();
            
            // Update preview
            updatePreview();
        },
        
        // Create a DOM element for a block
        createBlockElement: function(block, index) {
            const blockEl = document.createElement('div');
            blockEl.className = 'workflow-block';
            blockEl.id = block.id;
            blockEl.setAttribute('data-index', index);
            blockEl.setAttribute('data-type', block.type);
            
            // Create block content
            const blockContent = document.createElement('div');
            blockContent.className = 'block-content';
            
            // Set block title based on type
            const blockTitle = document.createElement('div');
            blockTitle.className = 'block-title';
            
            let title = '';
            switch(block.type) {
                case 'drawText':
                    title = 'Text';
                    break;
                case 'setPixel':
                    title = 'Pixel';
                    break;
                case 'getData':
                    title = 'Data';
                    break;
                default:
                    title = block.type;
            }
            
            blockTitle.textContent = title;
            blockContent.appendChild(blockTitle);
            
            // Set layer indicator
            const layerIndicator = document.createElement('div');
            layerIndicator.className = 'layer-indicator';
            layerIndicator.textContent = `Layer ${index + 1}`;
            blockContent.appendChild(layerIndicator);
            
            // Create block summary
            const blockSummary = document.createElement('div');
            blockSummary.className = 'block-summary';
            
            // Populate summary based on block type
            switch(block.type) {
                case 'drawText':
                    blockSummary.innerHTML = `
                        <div>Text: <span class="text-value">${block.properties.text || 'Text'}</span></div>
                        <div>Position: (<span class="x-value">${block.properties.x || '0'}</span>, <span class="y-value">${block.properties.y || '0'}</span>)</div>
                    `;
                    break;
                    
                case 'setPixel':
                    blockSummary.innerHTML = `
                        <div>Position: (<span class="x-value">${block.properties.x || '0'}</span>, <span class="y-value">${block.properties.y || '0'}</span>)</div>
                    `;
                    break;
                    
                case 'getData':
                    const url = block.properties.url || 'api.example.com';
                    blockSummary.innerHTML = `
                        <div>URL: <span class="url-value">${url.replace(/^https?:\/\//, '')}</span></div>
                    `;
                    break;
            }
            
            blockContent.appendChild(blockSummary);
            blockEl.appendChild(blockContent);
            
            // Add block actions
            const blockActions = document.createElement('div');
            blockActions.className = 'block-actions';
            
            // Edit button
            const editBtn = document.createElement('button');
            editBtn.className = 'block-edit';
            editBtn.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>
            `;
            editBtn.addEventListener('click', () => {
                this.selectBlock(block.id);
            });
            
            // Delete button
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'block-delete';
            deleteBtn.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>
            `;
            deleteBtn.addEventListener('click', () => {
                if (confirm('Are you sure you want to delete this block?')) {
                    this.removeBlock(block.id);
                }
            });
            
            // Drag handle
            const dragHandle = document.createElement('div');
            dragHandle.className = 'block-drag-handle';
            dragHandle.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M4 8H20M4 16H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            `;
            
            blockActions.appendChild(editBtn);
            blockActions.appendChild(deleteBtn);
            blockActions.appendChild(dragHandle);
            blockEl.appendChild(blockActions);
            
            // Add click event to select block
            blockEl.addEventListener('click', (e) => {
                // Don't trigger when clicking action buttons
                if (!e.target.closest('.block-actions')) {
                    this.selectBlock(block.id);
                }
            });
            
            // Setup drag handle
            dragHandle.addEventListener('mousedown', (e) => {
                e.preventDefault();
                blockEl.setAttribute('draggable', 'true');
                
                // Clean up after drag
                const dragEndHandler = () => {
                    blockEl.removeAttribute('draggable');
                    document.removeEventListener('mouseup', dragEndHandler);
                };
                
                document.addEventListener('mouseup', dragEndHandler);
            });
            
            return blockEl;
        },
        
        // Setup drag reordering functionality
        setupDragReordering: function() {
            const workflowArea = document.querySelector('.workflow-area');
            if (!workflowArea) return;
            
            const blocks = workflowArea.querySelectorAll('.workflow-block');
            
            blocks.forEach(block => {
                block.addEventListener('dragstart', (e) => {
                    e.dataTransfer.setData('text/plain', block.id);
                    block.classList.add('dragging');
                    
                    // Delay adding opacity to make drag image normal
                    setTimeout(() => {
                        block.style.opacity = '0.4';
                    }, 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);
                }
            });
            
            // Handle drop
            workflowArea.addEventListener('drop', (e) => {
                e.preventDefault();
                workflowArea.classList.remove('drag-over');
                
                // Remove drop indicators
                document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
                
                const blockId = e.dataTransfer.getData('text/plain');
                const draggingBlock = document.getElementById(blockId);
                if (!draggingBlock) return;
                
                const afterElement = this.getDragAfterElement(workflowArea, e.clientY);
                
                // Determine new index
                let newIndex;
                if (afterElement) {
                    newIndex = parseInt(afterElement.getAttribute('data-index'));
                } else {
                    newIndex = this.blocks.length;
                }
                
                // Get current index
                const currentIndex = parseInt(draggingBlock.getAttribute('data-index'));
                
                // Adjust index if moving down
                if (currentIndex < newIndex) {
                    newIndex--;
                }
                
                // Reorder blocks
                const [movedBlock] = this.blocks.splice(currentIndex, 1);
                this.blocks.splice(newIndex, 0, movedBlock);
                
                // Re-render
                this.renderWorkflow();
            });
            
            // Handle drag leave
            workflowArea.addEventListener('dragleave', (e) => {
                // Only trigger if actually leaving the container
                // Not when leaving child elements
                const rect = workflowArea.getBoundingClientRect();
                const isLeaving = 
                    e.clientX <= rect.left ||
                    e.clientX >= rect.right ||
                    e.clientY <= rect.top ||
                    e.clientY >= rect.bottom;
                    
                if (isLeaving) {
                    workflowArea.classList.remove('drag-over');
                    document.querySelectorAll('.block-drop-indicator').forEach(el => el.remove());
                }
            });
        },
        
        // Helper function to find the element to drop after
        getDragAfterElement: function(container, y) {
            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;
        },
        
        // Update a block's summary
        updateBlockSummary: function(blockId) {
            const blockEl = document.getElementById(blockId);
            if (!blockEl) return;
            
            const block = this.blocks.find(b => b.id === blockId);
            if (!block) return;
            
            const summary = blockEl.querySelector('.block-summary');
            if (!summary) return;
            
            switch(block.type) {
                case 'drawText':
                    const textValue = summary.querySelector('.text-value');
                    if (textValue) textValue.textContent = block.properties.text || 'Text';
                    
                    const xValue = summary.querySelector('.x-value');
                    if (xValue) xValue.textContent = block.properties.x || '0';
                    
                    const yValue = summary.querySelector('.y-value');
                    if (yValue) yValue.textContent = block.properties.y || '0';
                    break;
                    
                case 'setPixel':
                    const pixelX = summary.querySelector('.x-value');
                    if (pixelX) pixelX.textContent = block.properties.x || '0';
                    
                    const pixelY = summary.querySelector('.y-value');
                    if (pixelY) pixelY.textContent = block.properties.y || '0';
                    break;
                    
                case 'getData':
                    const urlValue = summary.querySelector('.url-value');
                    if (urlValue) {
                        const url = block.properties.url || 'api.example.com';
                        urlValue.textContent = url.replace(/^https?:\/\//, '');
                    }
                    break;
            }
        },
        
        // Show properties for the selected block
        updatePropertiesPanel: function() {
            const propertiesContainer = document.querySelector('.properties-container');
            if (!propertiesContainer) return;
            
            // Clear existing content
            propertiesContainer.innerHTML = '';
            
            // If no block is selected, show default message
            if (!this.selectedBlockId) {
                propertiesContainer.innerHTML = `
                    <div class="no-block-selected-message">
                        <p>Select a block to edit its properties</p>
                    </div>
                `;
                return;
            }
            
            // Find the selected block
            const block = this.blocks.find(b => b.id === this.selectedBlockId);
            if (!block) return;
            
            // Create properties form
            const propertiesForm = document.createElement('div');
            propertiesForm.className = 'block-properties';
            
            // Create form title
            const formTitle = document.createElement('h3');
            formTitle.className = 'properties-title';
            formTitle.textContent = getBlockTypeName(block.type) + ' Properties';
            propertiesForm.appendChild(formTitle);
            
            // Create form fields based on block type
            switch(block.type) {
                case 'drawText':
                    // Text field
                    const textGroup = createFormGroup('text', 'Text', 'text', block.properties.text || 'Text');
                    propertiesForm.appendChild(textGroup);
                    
                    // X coordinate
                    const xGroup = createFormGroup('x', 'X Position', 'number', block.properties.x || '0');
                    propertiesForm.appendChild(xGroup);
                    
                    // Y coordinate
                    const yGroup = createFormGroup('y', 'Y Position', 'number', block.properties.y || '0');
                    propertiesForm.appendChild(yGroup);
                    
                    // Color picker
                    const colorGroup = createFormGroup('color', 'Color', 'color', block.properties.color || '#FFFFFF');
                    propertiesForm.appendChild(colorGroup);
                    
                    // Font selector
                    const fontGroup = createFormGroup('font', 'Font', 'select', block.properties.font || 'bitmap_5x7');
                    const fontSelect = fontGroup.querySelector('select');
                    
                    // Add font options
                    const fonts = ['bitmap_3x4', 'bitmap_3x7', 'bitmap_4x5', 'bitmap_5x7', 'bitmap_6x8', 'bitmap_7x16', 'bitmap_10x16'];
                    fonts.forEach(font => {
                        const option = document.createElement('option');
                        option.value = font;
                        option.textContent = font.replace('bitmap_', '');
                        if (font === (block.properties.font || 'bitmap_5x7')) {
                            option.selected = true;
                        }
                        fontSelect.appendChild(option);
                    });
                    
                    propertiesForm.appendChild(fontGroup);
                    
                    // Justification
                    const justGroup = createFormGroup('alignment', 'Alignment', 'select', block.properties.alignment || 'left');
                    const justSelect = justGroup.querySelector('select');
                    
                    // Add justification options
                    ['left', 'center', 'right'].forEach(just => {
                        const option = document.createElement('option');
                        option.value = just;
                        option.textContent = just.charAt(0).toUpperCase() + just.slice(1);
                        if (just === (block.properties.alignment || 'left')) {
                            option.selected = true;
                        }
                        justSelect.appendChild(option);
                    });
                    
                    propertiesForm.appendChild(justGroup);
                    break;
                    
                case 'setPixel':
                    // X coordinate
                    const pixelXGroup = createFormGroup('x', 'X Position', 'number', block.properties.x || '0');
                    propertiesForm.appendChild(pixelXGroup);
                    
                    // Y coordinate
                    const pixelYGroup = createFormGroup('y', 'Y Position', 'number', block.properties.y || '0');
                    propertiesForm.appendChild(pixelYGroup);
                    
                    // Color picker
                    const pixelColorGroup = createFormGroup('color', 'Color', 'color', block.properties.color || '#FFFFFF');
                    propertiesForm.appendChild(pixelColorGroup);
                    break;
                    
                case 'getData':
                    // URL field
                    const urlGroup = createFormGroup('url', 'API URL', 'url', block.properties.url || 'https://api.example.com/data');
                    propertiesForm.appendChild(urlGroup);
                    
                    // API Key field
                    const apiKeyGroup = createFormGroup('apiKey', 'API Key', 'text', block.properties.apiKey || '');
                    propertiesForm.appendChild(apiKeyGroup);
                    
                    // Variable name
                    const varNameGroup = createFormGroup('variable', 'Variable Name', 'text', block.properties.variable || 'data');
                    propertiesForm.appendChild(varNameGroup);
                    break;
            }
            
            // Add event listeners to inputs
            propertiesForm.querySelectorAll('input, select').forEach(input => {
                input.addEventListener('change', () => {
                    const propName = input.name;
                    let propValue = input.value;
                    
                    // For number inputs, ensure the value is an integer
                    if (input.type === 'number') {
                        propValue = parseInt(propValue);
                        if (isNaN(propValue)) propValue = 0;
                    }
                    
                    // Update block properties
                    const updateData = {};
                    updateData[propName] = propValue;
                    this.updateBlock(this.selectedBlockId, updateData);
                    
                    // Update the preview
                    updatePreview();
                });
            });
            
            propertiesContainer.appendChild(propertiesForm);
        },
        
        // Generate PHP code from blocks
        generateCode: function() {
            let code = '';
            
            // Add each block as a PHP function call
            this.blocks.forEach(block => {
                switch(block.type) {
                    case 'drawText':
                        code += generateDrawTextCode(block.properties);
                        break;
                        
                    case 'setPixel':
                        code += generateSetPixelCode(block.properties);
                        break;
                        
                    case 'getData':
                        code += generateGetDataCode(block.properties);
                        break;
                }
            });
            
            return code;
        }
    };
}

/**
 * Helper function to get block type name
 */
function getBlockTypeName(type) {
    switch(type) {
        case 'drawText': return 'Text';
        case 'setPixel': return 'Pixel';
        case 'getData': return 'Data';
        default: return type;
    }
}

/**
 * Helper function to create form group
 */
function createFormGroup(name, label, type, value) {
    const group = document.createElement('div');
    group.className = 'form-group';
    
    const labelEl = document.createElement('label');
    labelEl.setAttribute('for', 'prop-' + name);
    labelEl.textContent = label;
    group.appendChild(labelEl);
    
    if (type === 'select') {
        const select = document.createElement('select');
        select.id = 'prop-' + name;
        select.name = name;
        group.appendChild(select);
    } else {
        const input = document.createElement('input');
        input.type = type;
        input.id = 'prop-' + name;
        input.name = name;
        input.value = value;
        group.appendChild(input);
        
        // Special handling for color inputs
        if (type === 'color') {
            // Add text input for hex value
            const textInput = document.createElement('input');
            textInput.type = 'text';
            textInput.id = 'prop-' + name + '-text';
            textInput.value = value;
            textInput.addEventListener('change', () => {
                // Update color picker when text changes
                input.value = textInput.value;
                // Trigger change event on the color picker
                const event = new Event('change');
                input.dispatchEvent(event);
            });
            group.appendChild(textInput);
            
            // Update text when color changes
            input.addEventListener('input', () => {
                textInput.value = input.value;
            });
        }
    }
    
    return group;
}

/**
 * Create the workflow area if it doesn't exist
 */
function createWorkflowArea() {
    const blocksCanvas = document.querySelector('.blocks-canvas');
    if (!blocksCanvas) return;
    
    // Check if workflow area already exists
    if (document.querySelector('.workflow-area')) return;
    
    // Create container for block library with resize handle
    const blockLibraryContainer = document.createElement('div');
    blockLibraryContainer.className = 'block-library-container';
    
    // Get or create block library
    const blockLibrary = document.querySelector('.block-library') || document.createElement('div');
    if (!document.querySelector('.block-library')) {
        blockLibrary.className = 'block-library';
    }
    
    // Add resize handle for block library
    const blockLibraryResizeHandle = document.createElement('div');
    blockLibraryResizeHandle.className = 'resize-handle block-library-resize';
    
    // Create workflow area
    const workflowArea = document.createElement('div');
    workflowArea.className = 'workflow-area';
    workflowArea.innerHTML = `
        <div class="empty-workflow-message">
            <p>Drag blocks from the library to start building your application</p>
        </div>
    `;
    
    // Create properties container with resize handle
    const propertiesContainer = document.createElement('div');
    propertiesContainer.className = 'properties-container';
    
    const propertiesResizeHandle = document.createElement('div');
    propertiesResizeHandle.className = 'resize-handle properties-resize';
    
    const propertiesContent = document.createElement('div');
    propertiesContent.className = 'properties';
    propertiesContent.innerHTML = `
        <div class="no-block-selected-message">
            <p>Select a block to edit its properties</p>
        </div>
    `;
    
    // Assemble structure
    blockLibraryContainer.appendChild(blockLibrary);
    blockLibraryContainer.appendChild(blockLibraryResizeHandle);
    
    propertiesContainer.appendChild(propertiesResizeHandle);
    propertiesContainer.appendChild(propertiesContent);
    
    // Create workflow container
    const workflowContainer = document.createElement('div');
    workflowContainer.className = 'workflow-container';
    workflowContainer.appendChild(workflowArea);
    workflowContainer.appendChild(propertiesContainer);
    
    // Add to blocks canvas
    blocksCanvas.appendChild(blockLibraryContainer);
    blocksCanvas.appendChild(workflowContainer);
    
    // Add styles for resizable sections
    addResizeStyles();
    
    // Setup resize functionality
    setupResizeHandlers();
}

function addResizeStyles() {
    const style = document.createElement('style');
    style.textContent = `
        .blocks-canvas {
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
        }
        
        .block-library-container {
            position: relative;
            flex: 0 0 250px; /* Initial height */
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .block-library {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            background: var(--bg-medium);
        }
        
        .workflow-container {
            display: flex;
            flex-direction: column;
            flex: 1;
            min-height: 0;
            position: relative;
            overflow: hidden;
        }
        
        .workflow-area {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            background: var(--editor-bg);
        }
        
        .properties-container {
            position: relative;
            flex: 0 0 200px; /* Initial height */
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .properties {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            background: var(--bg-darker);
        }
        
        .resize-handle {
            position: absolute;
            left: 0;
            right: 0;
            height: 5px;
            background-color: var(--bg-light);
            cursor: ns-resize;
            z-index: 10;
            transition: background-color 0.2s ease;
        }
        
        .resize-handle:hover {
            background-color: var(--primary);
        }
        
        .block-library-resize {
            bottom: 0;
        }
        
        .properties-resize {
            top: 0;
        }
    `;
    
    document.head.appendChild(style);
}

function setupResizeHandlers() {
    // Block Library resize
    const blockLibraryResize = document.querySelector('.block-library-resize');
    if (blockLibraryResize) {
        blockLibraryResize.addEventListener('mousedown', function(e) {
            e.preventDefault();
            
            const blockLibraryContainer = document.querySelector('.block-library-container');
            const initialHeight = blockLibraryContainer.offsetHeight;
            const initialY = e.clientY;
            
            function onMouseMove(e) {
                const deltaY = e.clientY - initialY;
                const newHeight = initialHeight + deltaY;
                
                // Set minimum and maximum height
                if (newHeight > 100 && newHeight < window.innerHeight - 200) {
                    blockLibraryContainer.style.flex = `0 0 ${newHeight}px`;
                    
                    // Save the height preference
                    localStorage.setItem('blockLibraryHeight', newHeight);
                }
            }
            
            function onMouseUp() {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }
            
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });
        
        // Restore saved height if it exists
        const savedHeight = localStorage.getItem('blockLibraryHeight');
        if (savedHeight) {
            const blockLibraryContainer = document.querySelector('.block-library-container');
            blockLibraryContainer.style.flex = `0 0 ${savedHeight}px`;
        }
    }
    
    // Properties resize
    const propertiesResize = document.querySelector('.properties-resize');
    if (propertiesResize) {
        propertiesResize.addEventListener('mousedown', function(e) {
            e.preventDefault();
            
            const propertiesContainer = document.querySelector('.properties-container');
            const initialHeight = propertiesContainer.offsetHeight;
            const initialY = e.clientY;
            
            function onMouseMove(e) {
                const deltaY = initialY - e.clientY;
                const newHeight = initialHeight + deltaY;
                
                // Set minimum and maximum height
                if (newHeight > 100 && newHeight < window.innerHeight - 200) {
                    propertiesContainer.style.flex = `0 0 ${newHeight}px`;
                    
                    // Save the height preference
                    localStorage.setItem('propertiesHeight', newHeight);
                }
            }
            
            function onMouseUp() {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }
            
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });
        
        // Restore saved height if it exists
        const savedHeight = localStorage.getItem('propertiesHeight');
        if (savedHeight) {
            const propertiesContainer = document.querySelector('.properties-container');
            propertiesContainer.style.flex = `0 0 ${savedHeight}px`;
        }
    }
}
function setupResizeHandlers() {
    // Block Library resize
    const blockLibraryResize = document.querySelector('.block-library-resize');
    if (blockLibraryResize) {
        blockLibraryResize.addEventListener('mousedown', function(e) {
            e.preventDefault();
            
            const blockLibraryContainer = document.querySelector('.block-library-container');
            const initialHeight = blockLibraryContainer.offsetHeight;
            const initialY = e.clientY;
            
            function onMouseMove(e) {
                const deltaY = e.clientY - initialY;
                const newHeight = initialHeight + deltaY;
                
                // Set minimum and maximum height
                if (newHeight > 100 && newHeight < window.innerHeight - 200) {
                    blockLibraryContainer.style.flex = `0 0 ${newHeight}px`;
                    
                    // Save the height preference
                    localStorage.setItem('blockLibraryHeight', newHeight);
                }
            }
            
            function onMouseUp() {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }
            
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });
        
        // Restore saved height if it exists
        const savedHeight = localStorage.getItem('blockLibraryHeight');
        if (savedHeight) {
            const blockLibraryContainer = document.querySelector('.block-library-container');
            blockLibraryContainer.style.flex = `0 0 ${savedHeight}px`;
        }
    }
    
    // Properties resize
    const propertiesResize = document.querySelector('.properties-resize');
    if (propertiesResize) {
        propertiesResize.addEventListener('mousedown', function(e) {
            e.preventDefault();
            
            const propertiesContainer = document.querySelector('.properties-container');
            const initialHeight = propertiesContainer.offsetHeight;
            const initialY = e.clientY;
            
            function onMouseMove(e) {
                const deltaY = initialY - e.clientY;
                const newHeight = initialHeight + deltaY;
                
                // Set minimum and maximum height
                if (newHeight > 100 && newHeight < window.innerHeight - 200) {
                    propertiesContainer.style.flex = `0 0 ${newHeight}px`;
                    
                    // Save the height preference
                    localStorage.setItem('propertiesHeight', newHeight);
                }
            }
            
            function onMouseUp() {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }
            
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });
        
        // Restore saved height if it exists
        const savedHeight = localStorage.getItem('propertiesHeight');
        if (savedHeight) {
            const propertiesContainer = document.querySelector('.properties-container');
            propertiesContainer.style.flex = `0 0 ${savedHeight}px`;
        }
    }
}