/**
 * Workflow to PHP Converter
 * This module handles conversion of no-code workflow blocks to executable PHP code
 */

class WorkflowCompiler {
    constructor() {
        this.indentation = 4; // Spaces for code indentation
    }
    
    /**
     * Get descriptive name for block type
     */
    getBlockTypeName(type) {
        switch(type) {
            case 'drawText': return 'Draw Text';
            case 'setPixel': return 'Set Pixel';
            case 'getData': return 'Get API Data';
            default: return type;
        }
    }
    
    /**
     * Escape string for PHP output
     */
    escapeString(str) {
        if (typeof str !== 'string') return str;
        return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
    }
    
    /**
     * Compiles the entire workflow to PHP code
     * @returns {string} Complete PHP code
     */
    compileWorkflow() {
        if (!window.blockManager || !window.blockManager.blocks || !window.blockManager.blocks.length) {
            return this.generateEmptyTemplate();
        }
        
        // Get blocks in order (top to bottom)
        const blocks = window.blockManager.blocks;
        
        // Generate the complete PHP file
        let phpCode = '';
        
        // Add each block as a PHP function call in order
        blocks.forEach((block, index) => {
            phpCode += this.generateBlockComment(block, index);
            phpCode += this.generateBlockCode(block);
        });
        
        return phpCode;
    }
    
    /**
     * Generate a comment for a block
     */
    generateBlockComment(block, index) {
        return `// Block ${index + 1}: ${this.getBlockTypeName(block.type)}\n`;
    }
    
    /**
     * Generate code for a specific block
     */
    generateBlockCode(block) {
        switch(block.type) {
            case 'drawText':
                return this.generateDrawTextCode(block.properties);
            case 'setPixel':
                return this.generateSetPixelCode(block.properties);
            case 'getData':
                return this.generateGetDataCode(block.properties);
            default:
                return `// Unsupported block type: ${block.type}\n\n`;
        }
    }
    
    /**
     * Generate code for drawText block
     */
    generateDrawTextCode(props) {
        const text = props.text || 'Text';
        const x = props.x || 0;
        const y = props.y || 0;
        const color = props.color || '#FFFFFF';
        const font = props.font || 'bitmap_5x7';
        const alignment = props.alignment || 'left';
        
        // Ensure proper color format
        const colorVar = this.getColorVariable(color);
        
        // Ensure font has bitmap_ prefix
        const fontName = font.startsWith('bitmap_') ? font : `bitmap_${font}`;
        
        return `drawText($image, "${this.escapeString(text)}", ${x}, ${y}, "${alignment}", ${colorVar}, $fontFiles . '${fontName}');\n\n`;
    }
    
    /**
     * Generate code for setPixel block
     */
    generateSetPixelCode(props) {
        const x = props.x || 0;
        const y = props.y || 0;
        const color = props.color || '#FFFFFF';
        
        // Get proper color variable
        const colorVar = this.getColorVariable(color);
        
        return `imagesetpixel($image, ${x}, ${y}, ${colorVar});\n\n`;
    }
    
    /**
     * Generate code for getData block
     */
    generateGetDataCode(props) {
        const url = props.url || 'https://api.example.com/data';
        const apiKey = props.apiKey || '';
        const variable = props.variable || 'data';
        
        let code = `// Fetch data from API\n`;
        code += `$${variable} = file_get_contents("${this.escapeString(url)}"`;
        
        if (apiKey) {
            code += `, false, stream_context_create([\n`;
            code += `    "http" => [\n`;
            code += `        "header" => "Authorization: Bearer ${this.escapeString(apiKey)}\\r\\n"\n`;
            code += `    ]\n`;
            code += `])`;
        }
        
        code += `);\n\n`;
        return code;
    }
    
    /**
     * Convert hex color to PHP color variable
     */
    getColorVariable(color) {
        // Check if it's already a variable reference
        if (color.startsWith('$')) {
            return color;
        }
        
        // Handle standard color names
        const colorMap = {
            '#FFFFFF': '$white',
            '#000000': '$black',
            '#FF0000': '$red',
            '#00FF00': '$green',
            '#0000FF': '$blue',
            '#00FFFF': '$cyan',
            '#FFFF00': '$yellow',
            '#FF00FF': '$magenta'
        };
        
        // Normalize hex color
        const normalizedColor = color.toUpperCase();
        
        // Return mapped color if available
        if (colorMap[normalizedColor]) {
            return colorMap[normalizedColor];
        }
        
        // Convert hex to RGB for imagecolorallocate
        if (normalizedColor.startsWith('#') && normalizedColor.length === 7) {
            const r = parseInt(normalizedColor.slice(1, 3), 16);
            const g = parseInt(normalizedColor.slice(3, 5), 16);
            const b = parseInt(normalizedColor.slice(5, 7), 16);
            return `imagecolorallocate($image, ${r}, ${g}, ${b})`;
        }
        
        // Default to white if invalid color
        return '$white';
    }
    
    /**
     * Generate an empty template when no blocks exist
     */
    generateEmptyTemplate() {
        return `// No blocks found in workflow\n// Add blocks to create your application\n\n` +
               `// Example: Display a welcome message\n` +
               `drawText($image, "Add blocks to start", $width/2, $height/2, "center", $white, $fontFiles . 'bitmap_5x7');\n`;
    }
}

/**
 * Shows a code preview modal for generated PHP code
 */
function showCodePreviewModal(phpCode, confirmCallback) {
    // Create modal if it doesn't exist
    let modal = document.getElementById('code-preview-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'code-preview-modal';
        modal.className = 'modal';
        
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Review Generated Code</h2>
                    <span class="close">&times;</span>
                </div>
                <div class="modal-body">
                    <p>The following PHP code will be saved:</p>
                    <pre id="preview-code"></pre>
                </div>
                <div class="modal-footer">
                    <button id="confirm-publish" class="btn btn-primary">Publish Application</button>
                    <button id="cancel-publish" class="btn btn-secondary">Cancel</button>
                </div>
            </div>
        `;
        
        // Add modal styles
        const style = document.createElement('style');
        style.textContent = `
            .modal {
                display: none;
                position: fixed;
                z-index: 10000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.7);
            }
            .modal-content {
                background-color: #1e2130;
                margin: 5% auto;
                padding: 20px;
                border: 1px solid #343957;
                width: 80%;
                max-width: 900px;
                max-height: 80vh;
                display: flex;
                flex-direction: column;
                border-radius: 5px;
            }
            .modal-header {
                padding: 10px 0;
                border-bottom: 1px solid #343957;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .modal-header h2 {
                margin: 0;
                color: white;
            }
            .close {
                color: #aaa;
                float: right;
                font-size: 28px;
                font-weight: bold;
                cursor: pointer;
            }
            .close:hover {
                color: white;
            }
            .modal-body {
                padding: 20px 0;
                flex: 1;
                overflow-y: auto;
            }
            .modal-body p {
                color: #ccc;
            }
            #preview-code {
                background-color: #1a1a2e;
                color: #00ff00;
                padding: 15px;
                border-radius: 5px;
                overflow: auto;
                max-height: 50vh;
                white-space: pre-wrap;
                font-family: monospace;
            }
            .modal-footer {
                padding: 10px 0;
                border-top: 1px solid #343957;
                display: flex;
                justify-content: flex-end;
                gap: 10px;
            }
            .btn {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }
            .btn-primary {
                background-color: #4CAF50;
                color: white;
            }
            .btn-secondary {
                background-color: #555;
                color: white;
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(modal);
    }
    
    // Set the preview code
    const previewCodeElement = document.getElementById('preview-code');
    previewCodeElement.textContent = phpCode;
    
    // Show the modal
    modal.style.display = 'block';
    
    // Add event listeners
    const closeButton = modal.querySelector('.close');
    const confirmButton = document.getElementById('confirm-publish');
    const cancelButton = document.getElementById('cancel-publish');
    
    // Close on X click
    closeButton.onclick = function() {
        modal.style.display = 'none';
    };
    
    // Close on cancel
    cancelButton.onclick = function() {
        modal.style.display = 'none';
    };
    
    // Confirm action
    confirmButton.onclick = function() {
        modal.style.display = 'none';
        if (typeof confirmCallback === 'function') {
            confirmCallback();
        }
    };
    
    // Close on outside click
    window.onclick = function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    };
}

/**
 * Set up the publish button to generate and submit PHP code
 */
function setupPublishWorkflow() {
    const submitBtn = document.getElementById('submit-btn');
    if (!submitBtn) return;
    
    submitBtn.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Validate app title
        const appTitle = document.getElementById('app-title');
        if (!appTitle || !appTitle.value.trim()) {
            alert('Please enter an application title');
            return;
        }
        
        // Compile the workflow to PHP
        const compiler = new WorkflowCompiler();
        const phpCode = compiler.compileWorkflow();
        
        // Display the generated code in a modal for review
        showCodePreviewModal(phpCode, function() {
            // On confirmation, submit to server
            submitCodeToServer(phpCode);
        });
    });
}

/**
 * Submit the generated code to the server
 */
function submitCodeToServer(code) {
    // Get form data
    const appTitle = document.getElementById('app-title').value;
    const executionTime = document.getElementById('execution-time').value;
    const visibility = document.getElementById('visibility').value;
    
    // Create form data
    const formData = new FormData();
    formData.append('title', appTitle);
    formData.append('execution_time', executionTime);
    formData.append('visibility', visibility);
    formData.append('code', code);
    formData.append('mode', 'no-code');
    
    // Get canvas size
    const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
    formData.append('canvas_size', canvasSize);
    
    // Show loading indicator
    showSavingIndicator();
    
    // Submit to server
    fetch('save.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideSavingIndicator();
        
        if (data.success) {
            showToast('Application published successfully!', 'success');
            
            // Optional: Redirect to application page if URL is provided
            if (data.url) {
                setTimeout(() => {
                    window.location.href = data.url;
                }, 1500);
            }
        } else {
            showToast('Error: ' + (data.message || 'Failed to publish application'), 'error');
        }
    })
    .catch(error => {
        hideSavingIndicator();
        showToast('Error: ' + error.message, 'error');
    });
}

/**
 * Show saving indicator
 */
function showSavingIndicator() {
    let indicator = document.getElementById('saving-indicator');
    if (!indicator) {
        indicator = document.createElement('div');
        indicator.id = 'saving-indicator';
        indicator.innerHTML = `
            <div class="saving-spinner"></div>
            <p>Publishing application...</p>
        `;
        
        // Add styles
        const style = document.createElement('style');
        style.textContent = `
            #saving-indicator {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.85);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: white;
                z-index: 10001;
            }
            .saving-spinner {
                width: 50px;
                height: 50px;
                border: 5px solid rgba(255, 255, 255, 0.3);
                border-radius: 50%;
                border-top-color: #fff;
                animation: spin 1s ease-in-out infinite;
                margin-bottom: 20px;
            }
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(indicator);
    } else {
        indicator.style.display = 'flex';
    }
}

/**
 * Hide saving indicator
 */
function hideSavingIndicator() {
    const indicator = document.getElementById('saving-indicator');
    if (indicator) {
        indicator.style.display = 'none';
    }
}

/**
 * Show toast notification
 */
function showToast(message, type = 'info') {
    // Remove any existing toasts
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }

    // Create new toast
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    
    // Add styles if not already added
    if (!document.getElementById('toast-styles')) {
        const style = document.createElement('style');
        style.id = 'toast-styles';
        style.textContent = `
            .toast {
                position: fixed;
                bottom: 20px;
                right: 20px;
                padding: 10px 20px;
                border-radius: 4px;
                color: white;
                z-index: 10000;
                opacity: 0;
                transform: translateY(20px);
                transition: opacity 0.3s, transform 0.3s;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            .toast.show {
                opacity: 1;
                transform: translateY(0);
            }
            .toast-success {
                background-color: #4CAF50;
            }
            .toast-error {
                background-color: #F44336;
            }
            .toast-info {
                background-color: #2196F3;
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(toast);

    // Trigger animation
    requestAnimationFrame(() => {
        toast.classList.add('show');
    });

    // Remove after 3 seconds
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (document.body.contains(toast)) {
                document.body.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Only in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    // Set up publish workflow functionality
    setupPublishWorkflow();
}); 