/**
 * No-Code Integration Script for LED Panel Developer Platform
 * This script serves as a bridge between the provided JavaScript files
 * and ensures proper functionality of the no-code environment.
 */

// Disable the original setupRightPanelResizing to prevent conflicts
// Put this at the VERY TOP of the file
window.setupRightPanelResizing = function() {
    console.log("Original setupRightPanelResizing disabled by simple-divider");
    return false;
};

// Ensure we only run the initialization once
let initialized = false;

// Global variable to control auto-preview behavior
window.autoPreviewEnabled = false;

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Only proceed if we're in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    // Avoid double initialization
    if (initialized) return;
    initialized = true;
    
    console.log("Initializing No-Code Integration...");
    
    // Define missing functions first
    if (typeof setupBlockLibrary !== 'function') {
        window.setupBlockLibrary = function() {
            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);
            });
        };
    }
    
    // Now initialize
    initIntegration();
    
    // Setup optimized interface after a short delay
    setTimeout(setupOptimizedInterface, 500);
    setTimeout(optimizeBlockLayout, 600);
    
    // Setup resize handlers
    setupResizeHandlers();
    
    // Setup the right panel resizing
    // setupRightPanelResizing();
});

/**
 * Initialize the integration between components
 */
function initIntegration() {
    // Connect to compiler if it exists
    if (window.compiler && window.canvas) {
        window.compiler.setCanvas(window.canvas);
    }
    
    // Setup the submit button for publishing
    setupSubmitButton();
    
    // Fix any missing components
    fixMissingComponents();
    
    // Setup canvas size selector
    setupCanvasSizeSelector();
    
    // Create block manager if it doesn't exist
    if (!window.blockManager) {
        console.log("Creating block manager...");
        window.blockManager = createBlockManager();
    }
}

/**
 * Setup the submit button functionality
 */
function setupSubmitButton() {
    const submitBtn = document.getElementById('submit-btn');
    
    if (submitBtn) {
        submitBtn.addEventListener('click', function() {
            // Show loading animation
            if (typeof toggleLoader === 'function') {
                toggleLoader(true);
            }
            
            // Generate the PHP code
            const phpCode = window.blockManager.generateCode();
            
            // Open submission modal
            openSubmissionModal(phpCode);
        });
    } else {
        console.error("Submit button not found!");
        
        // Create submit button if missing
        createSubmitButton();
    }
}

/**
 * Create a submit button if it's missing
 */
function createSubmitButton() {
    const previewBtn = document.getElementById('preview-btn');
    
    if (previewBtn && previewBtn.parentNode) {
        const submitBtn = document.createElement('button');
        submitBtn.id = 'submit-btn';
        submitBtn.className = 'btn btn-primary';
        submitBtn.textContent = 'Submit for Review';
        
        // Add click handler
        submitBtn.addEventListener('click', function() {
            // Generate the PHP code
            const phpCode = window.blockManager.generateCode();
            
            // Open submission modal
            openSubmissionModal(phpCode);
        });
        
        // Insert after preview button
        previewBtn.parentNode.insertBefore(submitBtn, previewBtn.nextSibling);
    }
}

/**
 * Open the submission modal with form fields
 */
function openSubmissionModal(phpCode) {
    // Check if modal already exists
    let modal = document.getElementById('submission-modal');
    
    if (!modal) {
        // Create modal
        modal = document.createElement('div');
        modal.id = 'submission-modal';
        modal.className = 'modal';
        
        // Add modal content
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Submit Application for Review</h2>
                    <span class="close-modal">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="submission-form">
                        <div class="form-group">
                            <label for="app-title">Application Title</label>
                            <input type="text" id="app-title" name="appTitle" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="app-description">Description</label>
                            <textarea id="app-description" name="appDescription" rows="3" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>Update Interval</label>
                            <div class="radio-group">
                                <label>
                                    <input type="radio" name="updateInterval" value="5" checked>
                                    5 minutes
                                </label>
                                <label>
                                    <input type="radio" name="updateInterval" value="15">
                                    15 minutes
                                </label>
                                <label>
                                    <input type="radio" name="updateInterval" value="30">
                                    30 minutes
                                </label>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Visibility</label>
                            <div class="radio-group">
                                <label>
                                    <input type="radio" name="visibility" value="public" checked>
                                    Public
                                </label>
                                <label>
                                    <input type="radio" name="visibility" value="private">
                                    Private
                                </label>
                            </div>
                        </div>
                        
                        <div id="app-inputs">
                            <h3>Application Inputs (Optional)</h3>
                            <p>Define inputs that users will need to provide when using your application.</p>
                            
                            <button type="button" id="add-input-btn" class="btn btn-sm">+ Add Input</button>
                            
                            <div id="inputs-container"></div>
                        </div>
                        
                        <div class="form-group">
                            <label for="php-code-preview">Generated PHP Code</label>
                            <textarea id="php-code-preview" readonly rows="5"></textarea>
                        </div>
                        
                        <input type="hidden" id="php-code" name="phpCode">
                        
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary close-modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">Submit for Review</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // Setup close button
        const closeButtons = modal.querySelectorAll('.close-modal');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                modal.style.display = 'none';
                
                // Hide loading animation
                if (typeof toggleLoader === 'function') {
                    toggleLoader(false);
                }
            });
        });
        
        // Setup add input button
        const addInputBtn = document.getElementById('add-input-btn');
        const inputsContainer = document.getElementById('inputs-container');
        let inputCount = 0;
        
        addInputBtn.addEventListener('click', function() {
            if (inputCount >= 4) {
                if (typeof showToast === 'function') {
                    showToast('Maximum of 4 inputs allowed', 'warning');
                }
                return;
            }
            
            const inputId = 'input-' + Date.now();
            const inputDiv = document.createElement('div');
            inputDiv.className = 'app-input';
            inputDiv.innerHTML = `
                <div class="form-group">
                    <label for="${inputId}-name">Input Name</label>
                    <input type="text" id="${inputId}-name" name="inputNames[]" required>
                </div>
                <div class="form-group">
                    <label for="${inputId}-desc">Description</label>
                    <input type="text" id="${inputId}-desc" name="inputDescs[]" required>
                </div>
                <div class="form-group">
                    <label for="${inputId}-type">Type</label>
                    <select id="${inputId}-type" name="inputTypes[]">
                        <option value="text">Text</option>
                        <option value="number">Number</option>
                        <option value="color">Color</option>
                        <option value="select">Select</option>
                        <option value="apiKey">API Key</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="${inputId}-default">Default Value</label>
                    <input type="text" id="${inputId}-default" name="inputDefaults[]">
                </div>
                <button type="button" class="btn btn-sm btn-danger remove-input">Remove</button>
            `;
            
            inputsContainer.appendChild(inputDiv);
            inputCount++;
            
            // Add remove button handler
            inputDiv.querySelector('.remove-input').addEventListener('click', function() {
                inputsContainer.removeChild(inputDiv);
                inputCount--;
            });
        });
        
        // Setup form submission
        const form = document.getElementById('submission-form');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Validate form fields
            if (!validateSubmissionForm()) {
                return;
            }
            
            // Get form data
            const formData = new FormData(form);
            
            // Add the PHP code
            formData.append('phpCode', phpCode);
            
            // Add canvas size
            formData.append('canvasSize', document.body.getAttribute('data-canvas-size') || '64x32');
            
            // Submit the application
            submitApplication(formData);
        });
    }
    
    // Update PHP code preview
    document.getElementById('php-code-preview').value = phpCode;
    document.getElementById('php-code').value = phpCode;
    
    // Show the modal
    modal.style.display = 'block';
}

/**
 * Validate the submission form
 */
function validateSubmissionForm() {
    const titleInput = document.getElementById('app-title');
    const descriptionInput = document.getElementById('app-description');
    
    if (!titleInput.value.trim()) {
        if (typeof showToast === 'function') {
            showToast('Please enter an application title', 'error');
        }
        titleInput.focus();
        return false;
    }
    
    // Validate title format (alphanumeric, spaces, and some special chars)
    const titleRegex = /^[a-zA-Z0-9_\-\s]+$/;
    if (!titleRegex.test(titleInput.value)) {
        if (typeof showToast === 'function') {
            showToast('Application title can only contain letters, numbers, spaces, underscores, and hyphens', 'error');
        }
        titleInput.focus();
        return false;
    }
    
    if (!descriptionInput.value.trim()) {
        if (typeof showToast === 'function') {
            showToast('Please enter an application description', 'error');
        }
        descriptionInput.focus();
        return false;
    }
    
    return true;
}

/**
 * Submit the application to the server
 */
function submitApplication(formData) {
    // Show loading animation
    if (typeof toggleLoader === 'function') {
        toggleLoader(true);
    }
    
    // Send to server
    fetch('api/submit-application.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading animation
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        // Hide the modal
        document.getElementById('submission-modal').style.display = 'none';
        
        if (data.success) {
            if (typeof showToast === 'function') {
                showToast('Application submitted successfully! It will be reviewed by admins.', 'success');
            }
        } else {
            if (typeof showToast === 'function') {
                showToast('Error: ' + data.error, 'error');
            } else {
                console.error('Submission error:', data.error);
            }
        }
    })
    .catch(error => {
        // Hide loading animation
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        console.error('Submission error:', error);
        if (typeof showToast === 'function') {
            showToast('Connection error: ' + error.message, 'error');
        }
    });
}

/**
 * Setup Preview button functionality
 */
function setupPreviewButton() {
    const previewBtn = document.getElementById('preview-btn');
    
    if (previewBtn) {
        previewBtn.addEventListener('click', updatePreview);
    } else {
        console.error("Preview button not found!");
    }
}

/**
 * Modified updatePreview function with auto-preview handling
 */
function setupOptimizedInterface() {
    console.log("Setting up optimized no-code interface...");
    
    // 1. Remove unnecessary workflow blocks
    hideWorkflowBlocks();
    
    // 2. Hide the Add Block button
    hideAddBlockButton();
    
    // 3. Add auto-preview toggle
    // addAutoPreviewToggle();
    
    // 4. Patch the updatePreview function
    patchUpdatePreview();
}

/**
 * Hide the workflow blocks at the top
 */
function hideWorkflowBlocks() {
    // Add CSS to hide these elements
    const style = document.createElement('style');
    style.textContent = `
        /* Hide the top workflow blocks */
        .workflow > .block-container {
            display: none;
        }
        
        /* Hide the Add Block button */
        .workflow .add-block,
        button.add-block-btn {
            display: none;
        }
    `;
    document.head.appendChild(style);
}

/**
 * Hide the Add Block button
 */
function hideAddBlockButton() {
    const addBlockBtn = document.querySelector('.add-block-btn');
    if (addBlockBtn) {
        addBlockBtn.style.display = 'none';
    }
}

/**
 * Add auto-preview toggle
 */
function addAutoPreviewToggle() {
    const previewArea = document.querySelector('.preview-panel');
    if (!previewArea) return;
    
    // Create toggle container
    const toggleContainer = document.createElement('div');
    toggleContainer.className = 'preview-controls';
    
    // Create the toggle switch
    toggleContainer.innerHTML = `
        <label class="toggle-switch">
            <input type="checkbox" id="auto-preview-toggle">
            <span class="toggle-slider"></span>
        </label>
        <span class="toggle-label">Auto-Preview</span>
    `;
    
    // Insert before the preview canvas
    const canvasContainer = previewArea.querySelector('.canvas-container') || previewArea.firstChild;
    if (canvasContainer) {
        previewArea.insertBefore(toggleContainer, canvasContainer);
    } else {
        previewArea.appendChild(toggleContainer);
    }
    
    // Add event listener
    const toggleSwitch = document.getElementById('auto-preview-toggle');
    if (toggleSwitch) {
        toggleSwitch.addEventListener('change', function() {
            window.autoPreviewEnabled = this.checked;
            console.log(`Auto-preview ${this.checked ? 'enabled' : 'disabled'}`);
        });
    }
    
    // Add styles for the toggle switch
    const style = document.createElement('style');
    style.textContent = `
        // .preview-controls {
        //     display: flex;
        //     align-items: center;
        //     gap: 10px;
        //     margin-bottom: 10px;
        // }

        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 20px;
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .toggle-slider {
            background-color: var(--primary);
        }

        input:checked + .toggle-slider:before {
            transform: translateX(20px);
        }

        .toggle-label {
            font-size: 0.9rem;
            user-select: none;
        }
    `;
    document.head.appendChild(style);
}

/**
 * Patch the updatePreview function to respect auto-preview setting
 */
function patchUpdatePreview() {
    // Store the original updatePreview function
    if (typeof window.originalUpdatePreview !== 'function') {
        window.originalUpdatePreview = window.updatePreview;
    }
    
    // Override the updatePreview function
    window.updatePreview = function(force = false) {
        // Only run preview if auto-preview is enabled or if forced
        if (window.autoPreviewEnabled || force) {
            window.originalUpdatePreview();
        }
    };
    
    // Update the preview button click handler
    const previewBtn = document.getElementById('preview-btn');
    if (previewBtn) {
        // Remove existing event listeners
        const newBtn = previewBtn.cloneNode(true);
        previewBtn.parentNode.replaceChild(newBtn, previewBtn);
        
        // Add new event listener
        newBtn.addEventListener('click', function() {
            window.updatePreview(true);  // Force update
        });
    }
    
    // Patch the blockManager if it exists
    if (window.blockManager) {
        // Store the original renderWorkflow function
        const originalRenderWorkflow = window.blockManager.renderWorkflow;
        
        // Override the renderWorkflow function
        window.blockManager.renderWorkflow = function() {
            // Call the original function
            originalRenderWorkflow.call(window.blockManager);
            
            // Don't automatically update preview
            // We removed the updatePreview() call that was here
        };
        
        // Store the original updateBlock function
        const originalUpdateBlock = window.blockManager.updateBlock;
        
        // Override the updateBlock function
        window.blockManager.updateBlock = function(blockId, properties) {
            // Call the original function
            originalUpdateBlock.call(window.blockManager, blockId, properties);
            
            // Trigger preview only if auto-preview is enabled
            if (window.autoPreviewEnabled) {
                window.updatePreview();
            }
        };
    }
    
    console.log("Preview functionality patched to respect auto-preview setting");
}

/**
 * Make the workflow blocks more compact
 */
function optimizeBlockLayout() {
    // Add stylesheet with optimized styles
    const style = document.createElement('style');
    style.textContent = `
        
    `;
    document.head.appendChild(style);
}

/**
 * Update the preview by generating and executing code
 */
function updatePreview() {
    // Check if we have a blockManager
    if (!window.blockManager) {
        console.error("Block manager not found!");
        return;
    }
    
    // Generate PHP code from blocks
    const phpCode = window.blockManager.generateCode();
    
    // Call the API preview endpoint
    const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
    
    // Show loading animation
    if (typeof toggleLoader === 'function') {
        toggleLoader(true);
    }
    
    // Send to server for preview
    fetch('api/preview.php?size=' + canvasSize, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
        },
        body: JSON.stringify({ code: phpCode })
    })
    .then(response => response.json())
    .then(data => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        if (data.success) {
            // Update canvas
            if (window.canvas) {
                window.canvas.updateFromData(data.pixelData);
            }
            if (typeof showToast === 'function') {
                showToast('Preview updated!', 'success');
            }
        } else {
            if (typeof showToast === 'function') {
                showToast('Error: ' + data.error, 'error');
            } else {
                console.error('Preview error:', data.error);
            }
        }
    })
    .catch(error => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        console.error('Preview error:', error);
        if (typeof showToast === 'function') {
            showToast('Connection error: ' + error.message, 'error');
        }
    });
}

/**
 * Setup the canvas size selector
 */
function setupCanvasSizeSelector() {
    const sizeSelector = document.querySelector('.canvas-size-selector');
    
    if (!sizeSelector) {
        console.log("Canvas size selector not found, creating one...");
        createCanvasSizeSelector();
        return;
    }
    
    const sizeOptions = sizeSelector.querySelectorAll('button');
    
    sizeOptions.forEach(option => {
        option.addEventListener('click', function() {
            const size = this.getAttribute('data-size');
            
            // Update active state
            sizeOptions.forEach(opt => opt.classList.remove('active'));
            this.classList.add('active');
            
            // Update data attribute
            document.body.setAttribute('data-canvas-size', size);
            
            // Update canvas dimensions
            updateCanvasDimensions(size);
            
            // Update preview
            updatePreview();
        });
    });
}

/**
 * Create a canvas size selector if it doesn't exist
 */
function createCanvasSizeSelector() {
    const previewPanel = document.querySelector('.preview-panel');
    
    if (!previewPanel) return;
    
    // Create selector container
    const sizeSelector = document.createElement('div');
    sizeSelector.className = 'canvas-size-selector';
    
    // Add size options
    const sizes = [
        { value: '64x32', label: '64×32' },
        { value: '128x32', label: '128×32' },
        { value: '192x32', label: '192×32' }
    ];
    
    sizes.forEach(size => {
        const button = document.createElement('button');
        button.setAttribute('data-size', size.value);
        button.textContent = size.label;
        
        // Set active state for current size
        const currentSize = document.body.getAttribute('data-canvas-size') || '64x32';
        if (size.value === currentSize) {
            button.classList.add('active');
        }
        
        // Add click handler
        button.addEventListener('click', function() {
            const newSize = this.getAttribute('data-size');
            
            // Update active state
            sizeSelector.querySelectorAll('button').forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // Update data attribute
            document.body.setAttribute('data-canvas-size', newSize);
            
            // Update canvas dimensions
            updateCanvasDimensions(newSize);
            
            // Update preview
            updatePreview();
        });
        
        sizeSelector.appendChild(button);
    });
    
    // Add to preview panel
    const canvasContainer = previewPanel.querySelector('.canvas-container');
    if (canvasContainer) {
        previewPanel.insertBefore(sizeSelector, canvasContainer);
    } else {
        previewPanel.appendChild(sizeSelector);
    }
    
    // Add styles
    const style = document.createElement('style');
    style.textContent = `
        .canvas-size-selector {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .canvas-size-selector button {
            padding: 0.25rem 0.5rem;
            background: var(--bg-medium);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-sm);
            cursor: pointer;
        }
        
        .canvas-size-selector button.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }
    `;
    
    document.head.appendChild(style);
}

/**
 * Update canvas dimensions based on selected size
 */
function updateCanvasDimensions(sizeString) {
    const [width, height] = sizeString.split('x').map(Number);
    
    // Update the preview canvas size
    const previewCanvas = document.getElementById('preview-canvas');
    if (previewCanvas) {
        previewCanvas.width = width;
        previewCanvas.height = height;
        
        // Update canvas handler if it exists
        if (window.canvas) {
            window.canvas.resize(width, height);
        }
        
        // Update dimensions display if it exists
        const dimensionsDisplay = document.querySelector('.preview-dimensions');
        if (dimensionsDisplay) {
            dimensionsDisplay.textContent = `${width} × ${height}`;
        }
    }
}

/**
 * Setup the block toolbar
 */
// function setupBlockToolbar() {
//     // Check if toolbar already exists
//     if (document.querySelector('.block-toolbar')) return;
    
//     // Check if we have a workflow area
//     const workflowArea = document.querySelector('.workflow-area');
//     if (!workflowArea) return;
    
//     // Create toolbar
//     const toolbar = document.createElement('div');
//     toolbar.className = 'block-toolbar';
    
//     // Add block types
//     const blockTypes = [
//         { type: 'drawText', label: 'Text', icon: 'T' },
//         { type: 'setPixel', label: 'Pixel', icon: '⬛' },
//         { type: 'getData', label: 'Data', icon: '🔄' }
//     ];
    
//     blockTypes.forEach(block => {
//         const item = document.createElement('div');
//         item.className = 'block-toolbar-item';
//         item.setAttribute('data-block-type', block.type);
//         item.innerHTML = `<span class="block-icon">${block.icon}</span> ${block.label}`;
        
//         // Add click handler
//         item.addEventListener('click', function() {
//             // Add new block
//             window.blockManager.addBlock({
//                 type: block.type,
//                 properties: getDefaultProperties(block.type)
//             });
//         });
        
//         toolbar.appendChild(item);
//     });
    
//     // Insert before workflow area
//     workflowArea.parentNode.insertBefore(toolbar, workflowArea);
// }

/**
 * 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 {};
        }
    }
    
    /**
     * Fix any missing components in the UI
     */
    function fixMissingComponents() {
        // Check for preview-dimensions element
        const previewCanvas = document.getElementById('preview-canvas');
        if (previewCanvas && !document.querySelector('.preview-dimensions')) {
            const dimensionsDisplay = document.createElement('div');
            dimensionsDisplay.className = 'preview-dimensions';
            
            const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
            const [width, height] = canvasSize.split('x').map(Number);
            dimensionsDisplay.textContent = `${width} × ${height}`;
            
            // Add near the canvas
            const canvasContainer = previewCanvas.parentNode;
            if (canvasContainer) {
                canvasContainer.appendChild(dimensionsDisplay);
            }
        }
    }
    
    /**
     * Helper function to generate drawText PHP code
     */
    function generateDrawTextCode(props) {
        return `drawText(${props.x}, ${props.y}, '${props.text}', '${props.color}', '${props.font}', '${props.alignment}');\n`;
    }
    
    /**
     * Helper function to generate setPixel PHP code
     */
    function generateSetPixelCode(props) {
        return `setPixel(${props.x}, ${props.y}, '${props.color}');\n`;
    }
    
    /**
     * Helper function to generate getData PHP code
     */
    function generateGetDataCode(props) {
        let code = `$${props.variable} = getData('${props.url}'`;
        
        // Add API key if provided
        if (props.apiKey) {
            code += `, '${props.apiKey}'`;
        }
        
        code += `);\n`;
        return code;
    }
    
    // Use existing Compiler class if available, don't define a new one
    if (!window.compiler && typeof Compiler === 'function') {
        window.compiler = new Compiler();
    }

/**
 * Setup resize handlers for the block library and properties panels
 */
function setupResizeHandlers() {
    // Block Library resize
    const blockLibraryContainer = document.querySelector('.block-library-container');
    const workflowContainer = document.querySelector('.workflow-container');
    
    if (!blockLibraryContainer || !workflowContainer) return;
    
    // Create resize handle for block library if it doesn't exist
    let blockLibraryResize = document.querySelector('.block-library-resize');
    if (!blockLibraryResize) {
        blockLibraryResize = document.createElement('div');
        blockLibraryResize.className = 'resize-handle block-library-resize';
        blockLibraryContainer.appendChild(blockLibraryResize);
    }
    
    // Properties container resize
    const propertiesContainer = document.querySelector('.properties-container');
    if (!propertiesContainer) return;
    
    // Create resize handle for properties if it doesn't exist
    let propertiesResize = document.querySelector('.properties-resize');
    if (!propertiesResize) {
        propertiesResize = document.createElement('div');
        propertiesResize.className = 'resize-handle properties-resize';
        propertiesContainer.insertBefore(propertiesResize, propertiesContainer.firstChild);
    }
    
    // Setup block library resize functionality
    blockLibraryResize.addEventListener('mousedown', function(e) {
        e.preventDefault();
        
        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 - 300) {
                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);
    });
    
    // Setup properties resize functionality
    propertiesResize.addEventListener('mousedown', function(e) {
        e.preventDefault();
        
        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 - 300) {
                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 heights if they exist
    const savedBlockLibraryHeight = localStorage.getItem('blockLibraryHeight');
    if (savedBlockLibraryHeight) {
        blockLibraryContainer.style.flex = `0 0 ${savedBlockLibraryHeight}px`;
    }
    
    const savedPropertiesHeight = localStorage.getItem('propertiesHeight');
    if (savedPropertiesHeight) {
        propertiesContainer.style.flex = `0 0 ${savedPropertiesHeight}px`;
    }
}

/**
 * Setup the right panel with resizable sections
 */
// function setupRightPanelResizing() {
//     // Clean up any previous event listeners first
//     const existingHandle = document.querySelector('.right-panel-resize-handle');
//     if (existingHandle) {
//         // Clone and replace to remove all event listeners
//         const newHandle = existingHandle.cloneNode(true);
//         existingHandle.parentNode.replaceChild(newHandle, existingHandle);
//     }
    
//     const rightPanel = document.querySelector('.right-panel');
//     const blockLibrarySection = document.querySelector('.panel-section.block-library-section');
//     const propertiesSection = document.querySelector('.panel-section.properties-section');
//     const resizeHandle = document.querySelector('.right-panel-resize-handle');
    
//     if (!rightPanel || !blockLibrarySection || !propertiesSection || !resizeHandle) {
//         console.error("Right panel elements not found!");
//         console.log({rightPanel, blockLibrarySection, propertiesSection, resizeHandle});
//         return;
//     }
    
//     console.log("Setting up right panel resizing...");
    
//     // IMPORTANT FIX: Remove any transitions to prevent animation effects
//     rightPanel.style.transition = 'none';
//     blockLibrarySection.style.transition = 'none';
//     propertiesSection.style.transition = 'none';
    
//     // Override any flex values that might be causing animation
//     blockLibrarySection.style.flex = 'none';
//     propertiesSection.style.flex = 'none';
    
//     // Make sure right panel has the correct layout properties
//     rightPanel.style.display = 'flex';
//     rightPanel.style.flexDirection = 'column';
//     rightPanel.style.height = '100%';
//     rightPanel.style.overflow = 'hidden';
    
//     // Set initial sizes with fixed heights instead of flex
//     function applyHeights(libraryPercent) {
//         // Constrain to 20%-80% range
//         libraryPercent = Math.max(20, Math.min(80, libraryPercent));
//         const propertiesPercent = 100 - libraryPercent;
        
//         // Calculate pixel heights (subtract handle height)
//         const totalHeight = rightPanel.offsetHeight;
//         const handleHeight = resizeHandle.offsetHeight || 5;
//         const availableHeight = totalHeight - handleHeight;
        
//         const libraryHeight = Math.floor((libraryPercent / 100) * availableHeight);
//         const propertiesHeight = availableHeight - libraryHeight;
        
//         // Apply fixed heights directly
//         blockLibrarySection.style.height = `${libraryHeight}px`;
//         blockLibrarySection.style.minHeight = '100px';
//         blockLibrarySection.style.maxHeight = `${availableHeight * 0.8}px`;
//         blockLibrarySection.style.overflow = 'auto';
        
//         propertiesSection.style.height = `${propertiesHeight}px`;
//         propertiesSection.style.minHeight = '100px';
//         propertiesSection.style.maxHeight = `${availableHeight * 0.8}px`;
//         propertiesSection.style.overflow = 'auto';
        
//         // Save to localStorage
//         localStorage.setItem('rightPanelLibraryPercent', libraryPercent);
        
//         console.log(`Applied heights: ${libraryHeight}px / ${propertiesHeight}px (${libraryPercent}%)`);
//     }
    
//     // FORCE EXACTLY 50/50 on first load
//     // We're overriding the saved value to ensure a consistent starting point
//     applyHeights(50);
    
//     // Re-enable transitions after layout is done
//     setTimeout(function() {
//         blockLibrarySection.style.transition = '';
//         propertiesSection.style.transition = '';
//     }, 50);
    
//     // Resize event handler with mouse events
//     resizeHandle.addEventListener('mousedown', function(e) {
//         e.preventDefault();
//         console.log("Resize handle mousedown");
        
//         // Mark as actively resizing - add visual feedback
//         resizeHandle.style.backgroundColor = 'var(--primary)';
//         document.body.style.cursor = 'ns-resize';
        
//         // Get starting positions
//         const startY = e.clientY;
//         const initialLibraryHeight = blockLibrarySection.offsetHeight;
//         const totalHeight = rightPanel.offsetHeight - resizeHandle.offsetHeight;
        
//         function onMouseMove(moveEvent) {
//             moveEvent.preventDefault();
            
//             // Calculate new position
//             const currentY = moveEvent.clientY;
//             const deltaY = currentY - startY;
//             const newLibraryHeight = initialLibraryHeight + deltaY;
            
//             // Convert to percentage
//             const newLibraryPercent = (newLibraryHeight / totalHeight) * 100;
//             console.log(`Moving: deltaY=${deltaY}, newPercent=${newLibraryPercent.toFixed(1)}%`);
            
//             // Apply with constraints
//             applyHeights(newLibraryPercent);
//         }
        
//         function onMouseUp() {
//             console.log("Resize handle mouseup");
//             document.removeEventListener('mousemove', onMouseMove);
//             document.removeEventListener('mouseup', onMouseUp);
            
//             // Remove visual feedback
//             resizeHandle.style.backgroundColor = '';
//             document.body.style.cursor = '';
//         }
        
//         // Add temporary event listeners
//         document.addEventListener('mousemove', onMouseMove);
//         document.addEventListener('mouseup', onMouseUp);
//     });
    
//     // Handle window resize
//     window.addEventListener('resize', function() {
//         // Re-apply with the same percentages
//         const savedPercent = localStorage.getItem('rightPanelLibraryPercent');
//         applyHeights(savedPercent ? parseFloat(savedPercent) : 50);
//     });
    
//     console.log("Right panel resize setup complete");
// }

// Remove any previous setupResizeHandlers function to avoid conflicts
if (window.setupResizeHandlers) {
    window.setupResizeHandlers = null;
}

// Initialize when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Only in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    console.log("DOM loaded, setting up right panel resizing");
    // setupRightPanelResizing();
});