/**
 * No-Code Interface Initialization for GLANCE LED Panel Developer Platform
 * This script properly initializes the no-code interface and ensures all components work together.
 */

// Global initialization state
const NoCodeInit = {
    state: {
        initialized: false,
        canvasReady: false,
        blockManagerReady: false,
        workflowReady: false
    },
    
    // Main initialization sequence
    async init() {
        if (document.body.getAttribute('data-mode') !== 'no-code') return;
        if (this.state.initialized) return;
        
        console.log("🚀 Starting No-Code Interface initialization...");
        
        try {
            // 1. Initialize Canvas (Most important for preview)
            await this.initCanvas();
            
            // 2. Initialize Block Manager (Core functionality)
            await this.initBlockManager();
            
            // 3. Initialize Workflow UI (Depends on Block Manager)
            await this.initWorkflow();
            
            // 4. Initialize Supporting Features
            // this.initSupportingFeatures();
            
            // Initialize workflow publishing
            if (typeof initWorkflowPublishing === 'function') {
                initWorkflowPublishing();
            }
            
            this.state.initialized = true;
            console.log("✅ No-Code Interface initialization complete!");
            
        } catch (error) {
            console.error("❌ Initialization failed:", error);
        }
    },
    
    // Individual initialization steps
    async initCanvas() {
        if (!window.canvas) {
            window.canvas = new CanvasHandler('preview-canvas', {
                enableGrid: true,
                enableTooltips: true,
                enableControls: false,
                initialZoom: 8,
                gridColor: 'rgba(255, 255, 255, 0.1)'
            });
        }
        this.state.canvasReady = true;
        console.log("📊 Canvas initialized");
    },
    
    async initBlockManager() {
        if (!window.blockManager) {
            window.blockManager = createBlockManager();
        }
        
        // Initialize compiler after block manager
        if (!window.compiler) {
            window.compiler = new Compiler();
            window.compiler.setCanvas(window.canvas);
        }
        
        this.state.blockManagerReady = true;
        console.log("🧱 Block Manager initialized");
    },
    
    async initWorkflow() {
        // Ensure DOM elements exist
        ensureWorkflowAreaExists();
        
        // Setup core workflow features
        setupBlockLibrary();
        initPropertiesPanel();
        
        // Add clear workflow button
        addClearWorkflowButton();
        
        this.state.workflowReady = true;
        console.log("🔄 Workflow initialized");
    },
    
    // initSupportingFeatures() {
    //     window.blockPersistenceManager = new BlockPersistenceManager();
    //     // Setup buttons and controls
    //     setupPreviewButton();
    //     setupSubmitButton();
        
    //     // Initialize persistence
    //     BlockPersistenceManager.initialize();
        
    //     console.log("🛠 Supporting features initialized");
    // },

    initPreviewSection() {
        // Check if this is adding duplicate controls
    }
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => NoCodeInit.init());

/**
 * Initialize the no-code interface
 */
function initNoCodeInterface() {
    // Create the block manager if it doesn't exist
    if (!window.blockManager) {
        window.blockManager = createBlockManager();
    }
    
    // Create workflow area if it doesn't exist
    ensureWorkflowAreaExists();
    
    // Initialize canvas handler with same settings as low-code
    if (!window.canvas) {
        window.canvas = new CanvasHandler('preview-canvas', {
            enableGrid: true,
            enableTooltips: true,
            enableControls: true,
            initialZoom: 8,  // Match low-code zoom level
            gridColor: 'rgba(255, 255, 255, 0.1)'
        });
    }
    
    // Initialize compiler
    if (!window.compiler) {
        window.compiler = new Compiler();
        window.compiler.setCanvas(window.canvas);
    }
    
    // Setup submission handling
    setupSubmissionHandling();
    
    // Ensure we have a proper updatePreview function
    if (typeof window.updatePreview !== 'function') {
        window.updatePreview = function(force = false) {
            // Generate PHP code from blocks
            if (!window.blockManager) return;
            
            const phpCode = window.blockManager.generateCode();
            
            // Get current canvas size
            const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
            
            // Show loading animation (if available)
            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' && force) {
                        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 preview button handler
    const previewBtn = document.getElementById('preview-btn');
    if (previewBtn) {
        // Remove existing event listeners by cloning
        const newBtn = previewBtn.cloneNode(true);
        previewBtn.parentNode.replaceChild(newBtn, previewBtn);
        
        // Add new event listener
        newBtn.addEventListener('click', function() {
            window.updatePreview(true); // Force update with notification
        });
    }
}

/**
 * Ensure workflow area exists and is properly initialized
 */
function ensureWorkflowAreaExists() {
    // Check if workflow area already exists
    let workflowArea = document.querySelector('.workflow-area');
    if (!workflowArea) {
        console.log("Creating workflow area");
        
        // Find the editor container
        const editorContainer = document.querySelector('.editor-container');
        if (!editorContainer) {
            console.error("Editor container not found");
            return;
        }
        
        // Create workflow area
        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
        const propertiesContainer = document.createElement('div');
        propertiesContainer.className = 'properties-container';
        propertiesContainer.innerHTML = `
            <div class="no-block-selected-message">
                <p>Select a block to edit its properties</p>
            </div>
        `;
        
        // Add to editor container
        editorContainer.innerHTML = ''; // Clear existing content
        editorContainer.appendChild(workflowArea);
        editorContainer.appendChild(propertiesContainer);
    }
}

/**
 * Create block manager if it doesn't exist
 */
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);
            });
            
            // Enhance blocks with drag functionality
            const enhancedDragDrop = document.getElementById('enhanced-drag-drop-styles');
            if (enhancedDragDrop) {
                document.querySelectorAll('.workflow-block').forEach(block => {
                    block.setAttribute('draggable', 'true');
                });
            }
        },
        
        // 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';
            
            // Add 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>
            `;
            blockEl.appendChild(dragHandle);
            
            // Set block title based on type
            const blockTitle = document.createElement('div');
            blockTitle.className = 'block-title';
            
            let title = '';
            let iconHtml = '';
            
            switch(block.type) {
                case 'drawText':
                    title = 'Text';
                    iconHtml = '<span class="block-icon">T</span>';
                    break;
                case 'setPixel':
                    title = 'Pixel';
                    iconHtml = '<span class="block-icon">•</span>';
                    break;
                case 'getData':
                    title = 'Data';
                    iconHtml = '<span class="block-icon">{}</span>';
                    break;
                default:
                    title = block.type;
                    iconHtml = '<span class="block-icon">⚙️</span>';
            }
            
            blockTitle.innerHTML = iconHtml + ' ' + 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', (e) => {
                e.stopPropagation();
                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', (e) => {
                e.stopPropagation();
                if (confirm('Are you sure you want to delete this block?')) {
                    this.removeBlock(block.id);
                }
            });
            
            blockActions.appendChild(editBtn);
            blockActions.appendChild(deleteBtn);
            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);
                }
            });
            
            return blockEl;
        },
        
        // 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 = createColorGroup('color', 'Color', block.properties.color || '#00FF00');
                    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_4x5', 'bitmap_5x7', 'bitmap_6x8', 'bitmap_7x16'];
                    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);
                    
                    // Alignment
                    const alignmentGroup = createFormGroup('alignment', 'Alignment', 'select', block.properties.alignment || 'left');
                    const alignmentSelect = alignmentGroup.querySelector('select');
                    
                    // Add alignment options
                    ['left', 'center', 'right'].forEach(alignment => {
                        const option = document.createElement('option');
                        option.value = alignment;
                        option.textContent = alignment.charAt(0).toUpperCase() + alignment.slice(1);
                        if (alignment === (block.properties.alignment || 'left')) {
                            option.selected = true;
                        }
                        alignmentSelect.appendChild(option);
                    });
                    
                    propertiesForm.appendChild(alignmentGroup);
                    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 = createColorGroup('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;
                    }
                    
                    // For color inputs, handle both text and color pickers
                    if (input.id === 'prop-color-picker') {
                        const textInput = propertiesForm.querySelector('#prop-color');
                        if (textInput) {
                            textInput.value = propValue;
                        }
                    } else if (input.id === 'prop-color') {
                        const colorPicker = propertiesForm.querySelector('#prop-color-picker');
                        if (colorPicker) {
                            colorPicker.value = propValue;
                        }
                    }
                    
                    // Update block properties
                    const updateData = {};
                    updateData[propName] = propValue;
                    this.updateBlock(this.selectedBlockId, updateData);
                    
                    // Update the preview if auto-preview is enabled
                    if (window.autoPreviewEnabled && typeof window.updatePreview === 'function') {
                        window.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 a 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;
        
        // Add min/max for numeric inputs based on canvas size
        if (type === 'number') {
            const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
            const [canvasWidth, canvasHeight] = canvasSize.split('x').map(Number);
            
            if (name === 'x') {
                input.min = 0;
                input.max = canvasWidth - 1;
            } else if (name === 'y') {
                input.min = 0;
                input.max = canvasHeight - 1;
            }
        }
        
        group.appendChild(input);
    }
    
    return group;
}

/**
 * Helper function to create a color form group with picker and text input
 */
function createColorGroup(name, label, 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);
    
    // Create color picker container
    const container = document.createElement('div');
    container.className = 'color-picker-container';
    container.style.display = 'flex';
    
    // Text input for hex value
    const textInput = document.createElement('input');
    textInput.type = 'text';
    textInput.id = 'prop-' + name;
    textInput.name = name;
    textInput.value = value;
    textInput.style.flex = '1';
    
    // Color picker input
    const colorPicker = document.createElement('input');
    colorPicker.type = 'color';
    colorPicker.id = 'prop-' + name + '-picker';
    colorPicker.value = value;
    colorPicker.style.width = '40px';
    colorPicker.style.height = '40px';
    colorPicker.style.padding = '0';
    colorPicker.style.border = 'none';
    
    // Sync inputs
    textInput.addEventListener('input', () => {
        if (/^#[0-9A-F]{6}$/i.test(textInput.value)) {
            colorPicker.value = textInput.value;
        }
    });
    
    colorPicker.addEventListener('input', () => {
        textInput.value = colorPicker.value;
    });
    
    container.appendChild(textInput);
    container.appendChild(colorPicker);
    group.appendChild(container);
    
    return group;
}

/**
 * Helper function to generate drawText PHP code
 */
function generateDrawTextCode(props) {
    // Use default values if properties are missing
    const text = props.text || 'GLANCE';
    const x = props.x !== undefined ? props.x : 5;
    const y = props.y !== undefined ? props.y : 10;
    const color = props.color || '#00FF00';
    const font = props.font || 'bitmap_5x7';
    const alignment = props.alignment || 'left';
    
    return `drawText(${x}, ${y}, '${text}', '${color}', '${font}', '${alignment}');\n`;
}

/**
 * Helper function to generate setPixel PHP code
 */
function generateSetPixelCode(props) {
    // Use default values if properties are missing
    const x = props.x !== undefined ? props.x : 0;
    const y = props.y !== undefined ? props.y : 0;
    const color = props.color || '#FFFFFF';
    
    return `setPixel(${x}, ${y}, '${color}');\n`;
}

/**
 * Helper function to generate getData PHP code
 */
function generateGetDataCode(props) {
    // Use default values if properties are missing
    const url = props.url || 'https://api.example.com/data';
    const variable = props.variable || 'data';
    
    let code = `${variable} = getData('${url}'`;
    
    // Add API key if provided
    if (props.apiKey) {
        code += `, '${props.apiKey}'`;
    }
    
    code += `);\n`;
    return code;
}

/**
 * Setup submission handling for the no-code interface
 */
function setupSubmissionHandling() {
    const submitBtn = document.getElementById('submit-btn');
    if (!submitBtn) return;
    
    // Remove existing event listeners by cloning
    const newBtn = submitBtn.cloneNode(true);
    submitBtn.parentNode.replaceChild(newBtn, submitBtn);
    
    // Add new event listener
    newBtn.addEventListener('click', function() {
        handleSubmission();
    });
}

/**
 * Handle application submission
 */
function handleSubmission() {
    // Get application title
    const appTitle = document.getElementById('app-title');
    if (!appTitle || !appTitle.value.trim()) {
        if (typeof showToast === 'function') {
            showToast('Please enter an application title', 'error');
        } else {
            alert('Please enter an application title');
        }
        appTitle.focus();
        return;
    }
    
    // Validate title (alphanumeric, spaces, underscores, hyphens)
    const titleRegex = /^[a-zA-Z0-9_\-\s]+$/;
    if (!titleRegex.test(appTitle.value)) {
        if (typeof showToast === 'function') {
            showToast('Application title can only contain letters, numbers, spaces, underscores, and hyphens', 'error');
        } else {
            alert('Application title can only contain letters, numbers, spaces, underscores, and hyphens');
        }
        appTitle.focus();
        return;
    }
    
    // Show loading animation
    if (typeof toggleLoader === 'function') {
        toggleLoader(true);
    }
    
    // Disable submit button
    const submitBtn = document.getElementById('submit-btn');
    if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<svg class="spinner" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="4"></circle></svg> Publishing...';
    }
    
    // Get application data
    const data = {
        title: appTitle.value,
        mode: 'no-code',
        executionTime: document.getElementById('execution-time')?.value || '5',
        visibility: document.getElementById('visibility')?.value || 'public',
        canvasSize: document.body.getAttribute('data-canvas-size') || '64x32',
        code: generateCode()
    };
    
    // Send to server
    fetch('api/save.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        // Reset submit button
        if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Publish Application';
        }
        
        if (data.success) {
            if (typeof showToast === 'function') {
                showToast('Application published successfully!', 'success');
            } else {
                alert('Application published successfully!');
            }
            
            // Show success confirmation
            if (typeof showPublishSuccess === 'function') {
                showPublishSuccess(data.fileName);
            }
        } else {
            if (typeof showToast === 'function') {
                showToast('Error: ' + data.error, 'error');
            } else {
                alert('Error: ' + data.error);
            }
        }
    })
    .catch(error => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        // Reset submit button
        if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Publish Application';
        }
        
        console.error('Error:', error);
        if (typeof showToast === 'function') {
            showToast('Connection error: ' + error.message, 'error');
        } else {
            alert('Connection error: ' + error.message);
        }
    });
}

/**
 * Generate PHP code from blocks
 */
function generateCode() {
    if (!window.blockManager) return '';
    
    let code = '';
    
    // Add each block as a PHP function call
    window.blockManager.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;
}

// Apply minor visual improvements
function applyVisualImprovements() {
    // Ensure proper styling for workflow blocks
    const style = document.createElement('style');
    style.textContent = `
        .clear-workflow-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: var(--bg-medium);
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            padding: 0.5rem 0.75rem;
            border-radius: var(--radius-sm);
            font-size: 0.75rem;
            cursor: pointer;
            transition: all 0.2s ease;
            z-index: 10;
        }
        .clear-workflow-btn:hover {
            background: var(--bg-light);
            color: var(--text-light);
        }
        .clear-workflow-btn.confirm {
            background: #10B981;
            color: white;
            border-color: #047857;
        }
    `;
    
    document.head.appendChild(style);
    
    // Add clear workflow button
    addClearWorkflowButton();
}

/**
 * Add a button to clear the entire workflow
 */
function addClearWorkflowButton() {
    // Look for the preview header instead of workflow area
    const previewHeader = document.querySelector('.preview-header');
    if (!previewHeader) return;
    
    // Create button if it doesn't exist
    let clearBtn = document.querySelector('.clear-workflow-btn');
    if (clearBtn) return;
    
    // Create clear button with trash icon
    clearBtn = document.createElement('button');
    clearBtn.className = 'clear-workflow-btn btn-icon';
    clearBtn.title = 'Clear all blocks from the workflow';
    clearBtn.innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
            <line x1="10" y1="11" x2="10" y2="17"></line>
            <line x1="14" y1="11" x2="14" y2="17"></line>
        </svg>
        <span>Clear</span>
    `;
    
    // Track confirmation state
    let confirmState = false;
    let confirmTimeout;
    
    clearBtn.addEventListener('click', () => {
        if (!confirmState) {
            // First click - show confirmation
            confirmState = true;
            clearBtn.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="3 6 5 6 21 6"></polyline>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                    <line x1="10" y1="11" x2="10" y2="17"></line>
                    <line x1="14" y1="11" x2="14" y2="17"></line>
                </svg>
                <span>Confirm</span>
            `;
            clearBtn.classList.add('confirm');
            
            // Reset after 3 seconds if not confirmed
            confirmTimeout = setTimeout(() => {
                confirmState = false;
                clearBtn.innerHTML = `
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="3 6 5 6 21 6"></polyline>
                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                        <line x1="10" y1="11" x2="10" y2="17"></line>
                        <line x1="14" y1="11" x2="14" y2="17"></line>
                    </svg>
                    <span>Clear</span>
                `;
                clearBtn.classList.remove('confirm');
            }, 3000);
        } else {
            // Confirmed - clear the workflow
            clearWorkflow();
            
            // Reset button
            clearTimeout(confirmTimeout);
            confirmState = false;
            clearBtn.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="3 6 5 6 21 6"></polyline>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                    <line x1="10" y1="11" x2="10" y2="17"></line>
                    <line x1="14" y1="11" x2="14" y2="17"></line>
                </svg>
                <span>Clear</span>
            `;
            clearBtn.classList.remove('confirm');
        }
    });
    
    // Add CSS styles for button
    const style = document.createElement('style');
    style.textContent = `
        .clear-workflow-btn {
            background: var(--bg-dark);
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            padding: 0.5rem 0.75rem;
            border-radius: var(--radius-sm);
            font-size: 0.75rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
            margin-left: 6px;
        }
        .clear-workflow-btn:hover {
            background: var(--bg-light);
            color: var(--text-light);
        }
        .clear-workflow-btn.confirm {
            background:rgb(225, 66, 17);
            color: white;
            border-color:rgb(173, 37, 0);
        }
        .clear-workflow-btn svg {
            stroke-width: 2;
        }
    `;
    document.head.appendChild(style);
    
    // Add to preview header next to the preview button
    previewHeader.appendChild(clearBtn);
}

/**
 * Clear all blocks from the workflow
 */
function clearWorkflow() {
    // Clear block manager if it exists
    if (window.blockManager) {
        window.blockManager.blocks = [];
        window.blockManager.selectedBlockId = null;
        window.blockManager.renderWorkflow();
        window.blockManager.updatePropertiesPanel();
    } else {
        // If blockManager isn't available, manually clear the workflow area
        const workflowArea = document.querySelector('.workflow-area');
        if (workflowArea) {
            workflowArea.innerHTML = `
                <div class="empty-workflow-message">
                    <p>Drag blocks from the library to start building your application</p>
                </div>
            `;
        }
    }
    
    // Clear persistence if available
    if (typeof CanvasSizeStateManager !== 'undefined' && 
        typeof CanvasSizeStateManager.saveWorkflow === 'function') {
        // Remove from localStorage
        localStorage.removeItem(CanvasSizeStateManager.WORKFLOW_KEY);
    }
    
    // Clear persistence manager
    if (window.blockPersistenceManager) {
        window.blockPersistenceManager.clearBlocks();
    }
    
    // Ensure empty message is displayed if not already handled by blockManager
    const workflowArea = document.querySelector('.workflow-area');
    if (workflowArea && !workflowArea.querySelector('.empty-workflow-message')) {
        workflowArea.innerHTML = `
            <div class="empty-workflow-message">
                <p>Drag blocks from the library to start building your application</p>
            </div>
        `;
    }
    
    // Update preview
    if (window.autoPreviewEnabled && typeof window.updatePreview === 'function') {
        window.updatePreview();
    }
    
    // Show success message
    if (typeof showToast === 'function') {
        showToast('Workflow cleared successfully', 'success');
    }
}

class BlockPersistenceManager {
    constructor() {
        this.blocks = new Map();
    }
    
    saveBlock(id, data) {
        this.blocks.set(id, data);
    }
    
    loadBlock(id) {
        return this.blocks.get(id);
    }
    
    clearBlocks() {
        this.blocks.clear();
    }
}

/**
 * Initialize workflow-to-PHP code generation for the publish button
 */
function initWorkflowPublishing() {
    console.log('Initializing workflow-to-PHP publishing system');
    
    // Check if we're in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    // Find the publish button (submit-btn)
    const submitBtn = document.getElementById('submit-btn');
    if (!submitBtn) {
        console.warn('Submit button not found, skipping workflow publishing setup');
        return;
    }
    
    // Replace the existing click handler with our workflow publishing handler
    submitBtn.removeEventListener('click', window.originalSubmitHandler);
    
    // Save reference to original handler if needed for other modes
    if (!window.originalSubmitHandler && submitBtn.onclick) {
        window.originalSubmitHandler = submitBtn.onclick;
        submitBtn.onclick = null;
    }
    
    // Add our custom click handler
    submitBtn.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Validate app title 
        const appTitle = document.getElementById('app-title');
        if (!appTitle || !appTitle.value.trim()) {
            if (typeof showToast === 'function') {
                showToast('Please enter an application title', 'error');
            } else {
                alert('Please enter an application title');
            }
            return;
        }
        
        // Generate PHP code from the workflow
        const compiler = new WorkflowCompiler();
        const phpCode = compiler.compileWorkflow();
        
        // Show preview and confirm
        showCodePreviewModal(phpCode, function() {
            // On confirmation, submit code to server
            submitToServer(phpCode);
        });
    });
    
    console.log('Workflow publishing system initialized');
}

/**
 * Submit generated PHP code to the server
 */
function submitToServer(phpCode) {
    // Get application metadata
    const appTitle = document.getElementById('app-title').value || 'LED Panel Application';
    const executionTime = document.getElementById('execution-time')?.value || '15';
    const visibility = document.getElementById('visibility')?.value || 'public';
    
    // Get canvas size
    const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
    
    // Create form data for API request
    const formData = new FormData();
    formData.append('title', appTitle);
    formData.append('code', phpCode);
    formData.append('execution_time', executionTime);
    formData.append('visibility', visibility);
    formData.append('canvas_size', canvasSize);
    formData.append('mode', 'no-code');
    
    // Show loading animation
    if (typeof toggleLoader === 'function') {
        toggleLoader(true);
    }
    
    // Send to server (using fetch with FormData instead of JSON)
    fetch('api/save.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        if (data.success) {
            if (typeof showToast === 'function') {
                showToast('Application published successfully!', 'success');
            }
            
            // Show success confirmation
            if (typeof showPublishSuccess === 'function') {
                showPublishSuccess(data.fileName);
            }
        } else {
            if (typeof showToast === 'function') {
                showToast('Error: ' + (data.error || 'Failed to publish application'), 'error');
            } else {
                console.error('Publish error:', data.error);
            }
        }
    })
    .catch(error => {
        // Hide loader
        if (typeof toggleLoader === 'function') {
            toggleLoader(false);
        }
        
        console.error('Publish error:', error);
        if (typeof showToast === 'function') {
            showToast('Connection error: ' + error.message, 'error');
        }
    });
}
