// Global workflow persistence manager (canvas size independent)
class CanvasSizeStateManager {
    static WORKFLOW_KEY = 'shared_workflow';
    static LOADING_KEY = 'canvas_size_changing';
    static isLoading = false;

    static initialize() {
        console.log('🔄 Initializing Global Workflow Persistence Manager...');

        // Only run in no-code mode
        if (document.body.getAttribute('data-mode') !== 'no-code') {
            console.log('Not in no-code mode, skipping initialization');
            return;
        }

        // IMMEDIATELY show loading screen if we're coming from another canvas size
        if (this.isPageLoad()) {
            this.showInitialLoadingScreen();
        }

        // Set up canvas size link interception for future clicks
        this.setupCanvasSizeLinks();
        
        // Add transition styles
        this.addTransitionStyles();

        // Set a safety timeout to hide loading screen even if something fails
        const safetyTimeout = setTimeout(() => {
            console.warn('Safety timeout reached, forcing loading screen to hide');
            this.hideLoadingScreen();
        }, 8000);

        // Wait for blockManager and essential UI components
        this.waitForCompleteUIReady().then(() => {
            console.log('UI ready, completing initialization');
            
            // Clear safety timeout since we got here normally
            clearTimeout(safetyTimeout);
            
            // Hook block manager methods
            this.hookBlockManagerMethods();
            
            // Restore workflow with a delay to ensure DOM is completely ready
            setTimeout(() => {
                this.restoreWorkflow();
                
                // Hide loading screen after everything is ready
                setTimeout(() => {
                    this.hideLoadingScreen();
                }, 300);
            }, 500);
        });
        
        console.log('Workflow persistence initialized - blocks will be shared across all canvas sizes');
    }
    
    static isPageLoad() {
        return sessionStorage.getItem(this.LOADING_KEY) === 'true';
    }
    
    static waitForCompleteUIReady() {
        return new Promise(resolve => {
            // Add a maximum wait time to prevent infinite loops
            const MAX_WAIT_TIME = 5000; // 5 seconds max
            const startTime = Date.now();
            
            const checkComponents = () => {
                const hasBlockManager = !!window.blockManager;
                const hasPreviewContainer = !!document.querySelector('.preview-container');
                const hasWorkflowArea = !!document.querySelector('.workflow-area');
                const hasPropertiesContainer = !!document.querySelector('.properties-container');
                const hasCanvas = !!window.canvas;
                
                // Log which components are missing for debugging
                if (Date.now() - startTime > 1000 && Date.now() % 1000 < 100) {
                    console.log('UI component status:', {
                        blockManager: hasBlockManager,
                        previewContainer: hasPreviewContainer,
                        workflowArea: hasWorkflowArea,
                        propertiesContainer: hasPropertiesContainer,
                        canvas: hasCanvas
                    });
                }
                
                // Check if all required components are ready OR we've waited too long
                if ((hasBlockManager && 
                     hasWorkflowArea && 
                     hasPropertiesContainer) || 
                    (Date.now() - startTime > MAX_WAIT_TIME)) {
                    
                    if (Date.now() - startTime > MAX_WAIT_TIME) {
                        console.warn('Timeout waiting for UI components, proceeding anyway');
                    } else {
                        console.log('Essential UI components ready');
                    }
                    
                    resolve();
                } else {
                    setTimeout(checkComponents, 100);
                }
            };
            
            checkComponents();
        });
    }

    static showInitialLoadingScreen() {
        // Create a full-page overlay that blocks EVERYTHING
        const overlay = document.createElement('div');
        overlay.id = 'fullpage-loading-overlay';
        overlay.innerHTML = `
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <p>Preparing canvas...</p>
            </div>
        `;
        
        // Add styles inline for immediate effect
        const style = document.createElement('style');
        style.textContent = `
            #fullpage-loading-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: #1a1a1a;
                z-index: 99999;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .loading-content {
                text-align: center;
            }
            
            .loading-spinner {
                border: 5px solid rgba(255, 255, 255, 0.2);
                border-radius: 50%;
                border-top: 5px solid white;
                width: 50px;
                height: 50px;
                margin: 0 auto 20px auto;
                animation: spin 1s linear infinite;
            }
            
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            
            /* Hide ALL content until ready */
            body.loading .app-container {
                opacity: 0;
            }
        `;
        
        // Add to body immediately
        document.head.appendChild(style);
        document.body.appendChild(overlay);
        document.body.classList.add('loading');
        
        // Remove flag that triggered this
        sessionStorage.removeItem(this.LOADING_KEY);
    }

    static hideLoadingScreen() {
        const overlay = document.getElementById('fullpage-loading-overlay');
        if (overlay) {
            // Fade out overlay
            overlay.style.opacity = '0';
            overlay.style.transition = 'opacity 0.5s ease';
            
            // Remove overlay after transition
            setTimeout(() => {
                if (overlay.parentNode) {
                    overlay.parentNode.removeChild(overlay);
                }
                document.body.classList.remove('loading');
                console.log('Loading complete, UI now visible');
            }, 500);
        }
    }

    static addTransitionStyles() {
        // Only add styles once
        if (document.getElementById('canvas-transition-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'canvas-transition-styles';
        style.textContent = `
            /* Ensure loading overlay transitions smoothly */
            #fullpage-loading-overlay {
                transition: opacity 0.5s ease;
            }
            
            /* Override any other loaders */
            #loader, .workflow-loading-screen, .workflow-loading-indicator {
                display: none !important;
            }
        `;
        document.head.appendChild(style);
    }

    static setupCanvasSizeLinks() {
        // Intercept all canvas size links
        document.querySelectorAll('a[href*="size="]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                
                console.log('Canvas size link clicked:', link.href);
                
                // Save current workflow state
                this.saveWorkflow();
                
                // Set loading flag for next page
                sessionStorage.setItem(this.LOADING_KEY, 'true');
                
                // Navigate to the new page
                window.location.href = link.href;
            });
        });
    }

    static waitForBlockManager() {
        return new Promise(resolve => {
            const checkBlockManager = () => {
                if (window.blockManager) {
                    console.log('BlockManager is available');
                    resolve(window.blockManager);
                } else {
                    setTimeout(checkBlockManager, 100);
                }
            };
            
            checkBlockManager();
        });
    }

    static saveWorkflow() {
        if (!window.blockManager) return;
        
        try {
            // Get current blocks from block manager
            const blocks = window.blockManager.blocks.map(block => ({
                type: block.type,
                properties: block.properties
            }));
            
            // Save to localStorage
            localStorage.setItem(this.WORKFLOW_KEY, JSON.stringify({
                blocks: blocks,
                timestamp: Date.now()
            }));
            
            console.log(`✅ Saved ${blocks.length} blocks to shared workflow`);
        } catch (e) {
            console.error('Failed to save workflow state:', e);
        }
    }

    static restoreWorkflow() {
        const savedData = localStorage.getItem(this.WORKFLOW_KEY);
        
        try {
            if (!savedData) {
                console.log('No saved workflow found');
                this.ensureEmptyMessageExists();
                return;
            }
            
            const data = JSON.parse(savedData);
            if (data.blocks && Array.isArray(data.blocks) && window.blockManager) {
                console.log(`Found ${data.blocks.length} saved blocks in shared workflow`);
                
                // Clear existing blocks
                window.blockManager.blocks = [];
                
                // Find the workflow area
                const workflowArea = document.querySelector('.workflow-area');
                if (workflowArea) {
                    // Remove existing block elements
                    const blockElements = workflowArea.querySelectorAll('.workflow-block');
                    blockElements.forEach(el => el.remove());
                    
                    // Remove empty message if present
                    const emptyMessage = workflowArea.querySelector('.empty-workflow-message');
                    if (emptyMessage && data.blocks.length > 0) {
                        emptyMessage.remove();
                    }
                    
                    // If no blocks to restore, add empty message
                    if (data.blocks.length === 0) {
                        this.ensureEmptyMessageExists();
                    } else {
                        // Restore blocks
                        data.blocks.forEach(block => {
                            try {
                                window.blockManager.addBlock({
                                    type: block.type,
                                    properties: block.properties
                                });
                            } catch (e) {
                                console.error('Failed to restore block:', e);
                            }
                        });
                        
                        console.log(`✅ Restored ${data.blocks.length} blocks from shared workflow`);
                    }
                    
                    // Update preview
                    if (typeof window.updatePreview === 'function') {
                        window.updatePreview();
                    }
                }
            } else {
                this.ensureEmptyMessageExists();
            }
        } catch (e) {
            console.error('Failed to restore workflow state:', e);
            // Ensure empty message exists on error
            this.ensureEmptyMessageExists();
        }
    }

    static ensureEmptyMessageExists() {
        const workflowArea = document.querySelector('.workflow-area');
        if (!workflowArea) return;
        
        // Only add if there are no blocks and no empty message
        if (!workflowArea.querySelector('.workflow-block') && 
            !workflowArea.querySelector('.empty-workflow-message')) {
            const emptyMessage = document.createElement('div');
            emptyMessage.className = 'empty-workflow-message';
            emptyMessage.innerHTML = '<p>Drag blocks from the library to start building your application</p>';
            workflowArea.appendChild(emptyMessage);
        }
    }

    static hookBlockManagerMethods() {
        if (!window.blockManager) return;
        
        console.log('Hooking into blockManager methods');
        
        // Methods to hook
        const methods = ['addBlock', 'removeBlock', 'updateBlock'];
        
        methods.forEach(method => {
            if (typeof window.blockManager[method] === 'function') {
                const original = window.blockManager[method];
                window.blockManager[method] = function(...args) {
                    const result = original.apply(this, args);
                    CanvasSizeStateManager.saveWorkflow();
                    return result;
                };
            }
        });
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    console.log('Starting CanvasSizeStateManager initialization');
    CanvasSizeStateManager.initialize();
});