/**
 * Auto-Preview Feature for GLANCE LED Panel Developer Platform
 * This script adds an auto-preview toggle to automatically update the preview when changes are made.
 */

document.addEventListener('DOMContentLoaded', function() {
    // Only initialize in no-code mode
    if (document.body.getAttribute('data-mode') !== 'no-code') return;
    
    console.log("Initializing Auto-Preview Feature...");
    setupAutoPreview();
});

/**
 * Setup auto-preview toggle
 */
function setupAutoPreview() {
    // Find the preview controls area
    const previewControls = document.querySelector('.preview-controls');
    if (!previewControls) {
        console.error("Preview controls not found");
        return;
    }
    
    // Create auto-preview toggle
    const toggleContainer = document.createElement('div');
    toggleContainer.className = 'auto-preview-toggle';
    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 preview button
    const previewBtn = document.getElementById('preview-btn');
    if (previewBtn) {
        previewControls.insertBefore(toggleContainer, previewBtn);
    } else {
        previewControls.appendChild(toggleContainer);
    }
    
    // Add styles
    addAutoPreviewStyles();
    
    // Initialize auto-preview state
    window.autoPreviewEnabled = false;
    
    // Setup toggle event
    const toggle = document.getElementById('auto-preview-toggle');
    if (toggle) {
        toggle.addEventListener('change', function() {
            window.autoPreviewEnabled = this.checked;
            console.log(`Auto-preview ${this.checked ? 'enabled' : 'disabled'}`);
            
            // If enabled, update preview immediately
            if (this.checked && typeof window.updatePreview === 'function') {
                window.updatePreview();
            }
        });
    }
    
    // Patch the blockManager to respect auto-preview setting
    patchBlockManager();
}

/**
 * Add styles for auto-preview toggle
 */
function addAutoPreviewStyles() {
    const styleId = 'auto-preview-styles';
    
    // Don't add styles if they already exist
    if (document.getElementById(styleId)) return;
    
    const style = document.createElement('style');
    style.id = styleId;
    style.textContent = `
        /* Auto-preview toggle container */
        .auto-preview-toggle {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 12px;
        }
        
        /* Toggle switch */
        .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: var(--bg-light);
            border-radius: 34px;
            transition: .4s;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 14px;
            width: 14px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            border-radius: 50%;
            transition: .4s;
        }
        
        input:checked + .toggle-slider {
            background-color: var(--primary);
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(20px);
        }
        
        .toggle-label {
            font-size: 0.875rem;
            color: var(--text-light);
            user-select: none;
        }
    `;
    
    document.head.appendChild(style);
}

/**
 * Patch the blockManager to respect auto-preview setting
 */
function patchBlockManager() {
    // Wait until blockManager is available
    const checkInterval = setInterval(() => {
        if (!window.blockManager) return;
        
        clearInterval(checkInterval);
        
        // Store original methods
        const originalAddBlock = window.blockManager.addBlock;
        const originalRemoveBlock = window.blockManager.removeBlock;
        const originalUpdateBlock = window.blockManager.updateBlock;
        
        // Override addBlock method
        window.blockManager.addBlock = function(blockData) {
            // Call original method
            const blockId = originalAddBlock.call(this, blockData);
            
            // Update preview if auto-preview is enabled
            if (window.autoPreviewEnabled && typeof window.updatePreview === 'function') {
                window.updatePreview();
            }
            
            return blockId;
        };
        
        // Override removeBlock method
        window.blockManager.removeBlock = function(blockId) {
            // Call original method
            originalRemoveBlock.call(this, blockId);
            
            // Update preview if auto-preview is enabled
            if (window.autoPreviewEnabled && typeof window.updatePreview === 'function') {
                window.updatePreview();
            }
        };
        
        // Override updateBlock method
        window.blockManager.updateBlock = function(blockId, properties) {
            // Call original method
            originalUpdateBlock.call(this, blockId, properties);
            
            // Update preview if auto-preview is enabled
            if (window.autoPreviewEnabled && typeof window.updatePreview === 'function') {
                window.updatePreview();
            }
        };
        
        console.log("Successfully patched blockManager for auto-preview");
    }, 100);
    
    // Stop checking after 5 seconds to avoid infinite loop
    setTimeout(() => {
        clearInterval(checkInterval);
    }, 5000);
}
