// State management for VMO
window.vmoState = { blocks: [] }; // Each block: { id, html, type, images }
window.nextBlockId = 1;
window.undoStack = [];
window.lastContent = '';
window.isGenerating = false;
window.isUnsaved = false;
window.currentProjectId = null;
window.currentProjectTitle = null; // <-- Added for save/update logic
window.lastPublishedUrl = null;

window.vmoLegacyDemoIndicators = [
    'welcome to virtual media office',
    'revolutionizing e-commerce solutions',
    'feature one',
    'feature two',
    'image generating...',
    'video generating...',
    'enhance your business with our innovative solutions'
];

window.vmoNormalizeBuilderHtml = function(html) {
    var value = String(html || '');
    if (!value) return '';

    return value
        .replace(/<!--[\s\S]*?-->/g, '')
        .replace(/AI\s+Image\s+Generating\.\.\.?/gi, '')
        .replace(/AI\s+Video\s+Generating\.\.\.?/gi, '')
        .replace(/\bImage\s+generating\.\.\.?/gi, '')
        .replace(/\bVideo\s+generating\.\.\.?/gi, '')
        .replace(/A professional (?:image|video) will appear here\.?/gi, '')
        .replace(/(^|[\n\r>])\s*['"]?;>\s*(?=<|[\n\r]|$)/g, '$1')
        .replace(/\n{3,}/g, '\n\n')
        .trim();
};

window.vmoLooksLikeStrippedShellText = function(html) {
    var value = String(html || '').trim();
    var markers = 0;

    if (!value || /<script\b|<style\b/i.test(value)) return false;
    ['tailwind.config', ':root{--vmo-primary', '[data-vmo-animate]', '.vmo-overlay-container', '.vmo-fallback-page{', 'window.Lenis', 'window.gsap', 'document.querySelectorAll'].forEach(function(marker) {
        if (value.toLowerCase().indexOf(marker.toLowerCase()) !== -1) markers += 1;
    });

    return markers >= 2 && /<(?:div|header|main|section|article|footer)\b/i.test(value);
};

window.vmoRepairStrippedShellText = function(html) {
    var value = String(html || '');
    var parser;
    var doc;
    var root;
    var walker;
    var textNodes = [];
    var repairWithRegex = function(input) {
        return String(input || '')
            .replace(/^\s*tailwind\.config\s*=\s*\{[\s\S]*?(?=<(?:div|header|main|section|article|footer)\b)/i, '')
            .replace(/^\s*:root\{--vmo-primary:[\s\S]*?(?=<(?:div|header|main|section|article|footer)\b)/i, '')
            .replace(/\s*\.vmo-fallback-page\{[\s\S]*$/i, '')
            .replace(/\s*\(function\(\)\{\s*["']use strict["'];[\s\S]*?\}\)\(\);\s*$/i, '')
            .trim();
    };

    if (!window.vmoLooksLikeStrippedShellText(value)) {
        return value;
    }

    if (typeof window.DOMParser !== 'function') {
        return repairWithRegex(value);
    }

    try {
        parser = new DOMParser();
        doc = parser.parseFromString('<div id="vmo-repair-root">' + value + '</div>', 'text/html');
        root = doc.getElementById('vmo-repair-root');
        if (!root) return value;

        walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
        while (walker.nextNode()) {
            textNodes.push(walker.currentNode);
        }

        textNodes.forEach(function(node) {
            var text = String(node.nodeValue || '');
            if (/tailwind\.config\s*=|:root\{--vmo-primary|\[data-vmo-animate\]|\.vmo-overlay-container|\.vmo-fallback-page\{|window\.Lenis|window\.gsap|document\.querySelectorAll|\(function\(\)\{\s*["']use strict["'];/i.test(text)) {
                node.parentNode.removeChild(node);
            }
        });

        return root.innerHTML.trim();
    } catch (error) {
        return repairWithRegex(value);
    }
};

window.vmoNormalizeBuilderHtml = (function(originalNormalize) {
    return function(html) {
        var normalized = originalNormalize(html);
        return window.vmoRepairStrippedShellText(normalized);
    };
})(window.vmoNormalizeBuilderHtml);

window.vmoLooksLikeFullDocument = function(html) {
    return /^\s*(<!doctype|<html[\s>])/i.test(String(html || ''));
};

window.vmoSerializePreviewBodyHtml = function(iframeElement) {
    var iframe = iframeElement || document.getElementById('vmo-preview-iframe');
    var doc = null;
    var body = null;

    if (!iframe) return '';

    try {
        doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document) || null;
    } catch (_) {
        doc = null;
    }

    if (!doc || !doc.body) return '';

    body = doc.body.cloneNode(true);
    body.querySelectorAll('.vmo-replace-overlay, .vmo-replace-btn, .vmo-replace-media-btn, .replace-image-btn, .replace-video-btn, [data-replace-media], [data-vmo-editor-only="media-replace-overlay"]').forEach(function(node) {
        node.remove();
    });
    body.querySelectorAll('[data-vmo-has-button]').forEach(function(node) {
        node.removeAttribute('data-vmo-has-button');
    });
    body.querySelectorAll('[contenteditable], [data-editable], [data-vmo-editable], [data-noneditable], [spellcheck]').forEach(function(node) {
        node.removeAttribute('contenteditable');
        node.removeAttribute('data-editable');
        node.removeAttribute('data-vmo-editable');
        node.removeAttribute('data-noneditable');
        node.removeAttribute('spellcheck');
    });

    return String(body.innerHTML || '');
};

window.vmoSyncPreviewStateFromIframe = function(options) {
    var settings = options && typeof options === 'object' ? options : {};
    var iframe = settings.iframe || document.getElementById('vmo-preview-iframe');
    var blocks = window.vmoState && Array.isArray(window.vmoState.blocks) ? window.vmoState.blocks : [];
    var blockId = settings.blockId != null && settings.blockId !== '' ? String(settings.blockId) : '';
    var doc = null;
    var serializedDocument = '';
    var serializedBody = '';
    var blockHtml = '';
    var wrapper = null;
    var joinedHtml = '';

    if (!iframe) {
        return '';
    }

    if (window.vmoPreviewIsLive && settings.allowLive !== true) {
        return window.lastContent || '';
    }

    try {
        doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document) || null;
    } catch (_) {
        doc = null;
    }

    if (typeof window.vmoSerializePreviewDocument === 'function') {
        try {
            serializedDocument = window.vmoSerializePreviewDocument(iframe);
        } catch (_) {
            serializedDocument = '';
        }
    }

    if (!serializedDocument) {
        serializedDocument = String(iframe.getAttribute('srcdoc') || iframe.srcdoc || '');
    }

    if (typeof window.vmoSerializePreviewBodyHtml === 'function') {
        serializedBody = window.vmoSerializePreviewBodyHtml(iframe);
    }

    if (blockId && doc) {
        Array.from(doc.querySelectorAll('[data-block-id]')).some(function(node) {
            if (String(node.getAttribute('data-block-id') || '') !== blockId) {
                return false;
            }

            wrapper = node;
            return true;
        });
    }

    if (wrapper) {
        blockHtml = String(wrapper.innerHTML || '');
    } else if (blocks.length === 1) {
        blockHtml = window.vmoLooksLikeFullDocument(blocks[0] && blocks[0].html)
            ? (serializedDocument || String((blocks[0] && blocks[0].html) || ''))
            : (serializedBody || serializedDocument || String((blocks[0] && blocks[0].html) || ''));
    } else if (!blocks.length) {
        blockHtml = serializedBody || serializedDocument || '';
    }

    if (blockHtml && typeof window.vmoNormalizeBuilderHtml === 'function') {
        blockHtml = window.vmoNormalizeBuilderHtml(blockHtml);
    }

    if (blockId && blockHtml && blocks.length) {
        blocks.forEach(function(block) {
            if (String(block && block.id) === blockId) {
                block.html = blockHtml;
            }
        });
    } else if (blocks.length === 1 && blockHtml) {
        blocks[0].html = blockHtml;
    }

    if (blocks.length) {
        joinedHtml = blocks.map(function(block) {
            return block && block.html ? String(block.html) : '';
        }).join('\n');

        if (typeof window.vmoNormalizeBuilderHtml === 'function') {
            joinedHtml = window.vmoNormalizeBuilderHtml(joinedHtml);
        }

        if (
            settings.allowPlaceholder === true ||
            typeof window.vmoShouldTreatAsRealContent !== 'function' ||
            window.vmoShouldTreatAsRealContent(joinedHtml, window.vmoState)
        ) {
            window.lastContent = joinedHtml;
        } else if (blocks.length === 1 && blockHtml) {
            window.lastContent = blockHtml;
        }
    } else if (blockHtml) {
        window.lastContent = blockHtml;
    } else if (serializedDocument) {
        window.lastContent = serializedDocument;
    }

    if (settings.markUnsaved === true) {
        window.isUnsaved = true;
    }

    if (settings.autoSave === true && typeof window.autoSaveCheckpoint === 'function') {
        window.autoSaveCheckpoint();
    }

    return blockHtml || window.lastContent || serializedDocument || serializedBody || '';
};

window.vmoIsOfficialShowcaseHtml = function(html) {
    var value = String(html || '');
    if (!value) return false;

    return /id=["']vmo-demo-showcase["']|demo-hero-backdrop|data-vmo-preview-mode=["']showcase-placeholder["']/i.test(value);
};

window.vmoIsLegacyDemoHtml = function(html, state) {
    var value = String(html || '').trim();
    var indicators = window.vmoLegacyDemoIndicators || [];
    var normalized;
    var score = 0;
    var looksBroken;
    var hasModernShell;
    var combinedStateHtml = '';

    if (!value) return false;
    if (window.vmoIsOfficialShowcaseHtml(value)) return false;

    normalized = window.vmoNormalizeBuilderHtml(value).toLowerCase();
    if (!normalized) return false;

    indicators.forEach(function(marker) {
        if (normalized.indexOf(marker) !== -1) {
            score += 1;
        }
    });

    looksBroken = normalized.indexOf('image generating') !== -1
        || normalized.indexOf('video generating') !== -1
        || /(^|[\s>])['"]?;>/.test(value);
    hasModernShell = /vmo-premium-page|vmo-gjs-page|data-vmo-generated|id=["']vmo-demo-showcase["']|demo-hero-backdrop/i.test(value);

    if (state && Array.isArray(state.blocks) && state.blocks.length) {
        combinedStateHtml = state.blocks.map(function(block) {
            return block && block.html ? String(block.html) : '';
        }).join('\n');
    }

    if (!combinedStateHtml) {
        return !hasModernShell && (score >= 2 || (looksBroken && score >= 1));
    }

    return !hasModernShell
        && (score >= 2
            || (looksBroken && score >= 1)
            || (/feature one|image generating|video generating/i.test(combinedStateHtml)
                && !/vmo-premium-page|vmo-gjs-page|data-vmo-generated|id=["']vmo-demo-showcase["']/i.test(combinedStateHtml)));
};

window.vmoShouldTreatAsRealContent = function(html, state) {
    var normalized = window.vmoNormalizeBuilderHtml(html);
    if (!normalized) return false;
    if (window.vmoLooksLikeFullDocument(normalized)
        && typeof window.vmoHasMeaningfulPreviewHtml === 'function'
        && !window.vmoHasMeaningfulPreviewHtml(normalized)) {
        return false;
    }
    if (window.vmoIsOfficialShowcaseHtml(normalized)) return false;
    return !window.vmoIsLegacyDemoHtml(normalized, state);
};

window.vmoStateHasRenderableContent = function(state) {
    var blocks = state && Array.isArray(state.blocks) ? state.blocks : [];
    var combinedHtml;

    if (!blocks.length) return false;

    combinedHtml = blocks.map(function(block) {
        return block && block.html ? String(block.html) : '';
    }).join('\n');

    return window.vmoShouldTreatAsRealContent(combinedHtml, state);
};

window.vmoClearStoredCheckpoint = function() {
    try {
        localStorage.removeItem('vmo_checkpoint_state');
        localStorage.removeItem('vmo_checkpoint_html');
        localStorage.removeItem('vmo_checkpoint_ts');
        localStorage.removeItem('vmo_checkpoint_title');
        return true;
    } catch (error) {
        console.warn('[VMO] Could not clear local checkpoint state:', error);
        return false;
    }
};

window.vmoExtractProjectId = function(response) {
    var data = response && response.data ? response.data : response;
    var rawValue = data && (data.project_id || data.id || data.post_id || data.projectId || 0);
    var normalized = parseInt(rawValue, 10);

    return Number.isFinite(normalized) && normalized > 0 ? normalized : null;
};

window.vmoBuildProjectSnapshot = function(options) {
    var settings = options && typeof options === 'object' ? options : {};
    var state = settings.state || window.vmoState || { blocks: [] };
    var html = typeof settings.html === 'string'
        ? settings.html
        : (state && Array.isArray(state.blocks)
            ? state.blocks.map(function(block) {
                return block && block.html ? String(block.html) : '';
            }).join('\n')
            : '');

    if (typeof window.vmoNormalizeBuilderHtml === 'function') {
        html = window.vmoNormalizeBuilderHtml(html);
    }

    if (!html || !html.trim()) {
        return null;
    }

    return {
        title: settings.title || window.currentProjectTitle || 'Auto-saved Website',
        html: html,
        state: JSON.stringify(state || { blocks: [] }),
        chat: JSON.stringify(settings.chat || window.vmoChatHistory || []),
        images: JSON.stringify(settings.images || window.vmoImages || [])
    };
};

window.vmoSaveProjectSnapshot = function(options) {
    return new Promise(function(resolve, reject) {
        if (typeof jQuery === 'undefined' || typeof vmo_ajax === 'undefined') {
            reject(new Error('Project save transport is unavailable.'));
            return;
        }

        var snapshot = window.vmoBuildProjectSnapshot(options);
        if (!snapshot) {
            reject(new Error('Project snapshot is empty.'));
            return;
        }

        jQuery.post(vmo_ajax.ajaxurl, {
            action: 'vmo_save_project',
            security: vmo_ajax.nonce,
            title: snapshot.title,
            html: snapshot.html,
            state: snapshot.state,
            chat: snapshot.chat,
            images: snapshot.images
        }).done(function(res) {
            if (!res || !res.success) {
                reject(new Error(res && res.data && res.data.message ? res.data.message : 'Project save failed.'));
                return;
            }

            var projectId = typeof window.vmoExtractProjectId === 'function'
                ? window.vmoExtractProjectId(res)
                : null;

            if (projectId) {
                window.currentProjectId = projectId;
            }

            window.currentProjectTitle = snapshot.title;
            if (!options || options.markSaved !== false) {
                window.isUnsaved = false;
            }

            resolve({
                response: res,
                projectId: projectId,
                title: snapshot.title,
                html: snapshot.html
            });
        }).fail(function(xhr) {
            reject(new Error(xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                ? xhr.responseJSON.data.message
                : 'Project save request failed.'));
        });
    });
};

window.getUniqueBlockId = function() {
    return `block_${window.nextBlockId++}_${Date.now()}`;
};

window.vmoGenerateMediaId = function() {
    return 'media_' + Math.random().toString(36).substr(2, 8);
};

// Essential helper functions
window.vmoWrapWithCDNs = function(html) {
    // Simple CDN wrapper - can be enhanced later
    return html;
};

window.pushUndo = function() {
    if (window.vmoState && window.vmoState.blocks) {
        window.undoStack.push(JSON.parse(JSON.stringify(window.vmoState.blocks)));
        // Keep only last 10 undo states
        if (window.undoStack.length > 10) {
            window.undoStack.shift();
        }
    }
};

window.autoSaveCheckpoint = function() {
    window.isUnsaved = true;

    // ── 1. Persist to localStorage for instant reload ──
    try {
        if (window.vmoState && window.vmoState.blocks && window.vmoState.blocks.length) {
            const html = window.vmoState.blocks.map(function(b){ return b.html; }).join('\n');
            const normalizedHtml = typeof window.vmoNormalizeBuilderHtml === 'function'
                ? window.vmoNormalizeBuilderHtml(html)
                : html;
            const shouldPersist = typeof window.vmoShouldTreatAsRealContent === 'function'
                ? window.vmoShouldTreatAsRealContent(normalizedHtml, window.vmoState)
                : !!normalizedHtml.trim();

            if (!shouldPersist) {
                if (typeof window.vmoClearStoredCheckpoint === 'function') {
                    window.vmoClearStoredCheckpoint();
                }
                return;
            }

            localStorage.setItem('vmo_checkpoint_state', JSON.stringify(window.vmoState));
            localStorage.setItem('vmo_checkpoint_html', normalizedHtml);
            localStorage.setItem('vmo_checkpoint_ts', Date.now().toString());
            if (window.currentProjectTitle) {
                localStorage.setItem('vmo_checkpoint_title', window.currentProjectTitle);
            }
        }
    } catch (e) {
        console.warn('[VMO] localStorage checkpoint failed:', e);
    }

    // ── 2. Debounced server save (every 8 s max) ──
    if (window._vmoAutoSaveTimer) clearTimeout(window._vmoAutoSaveTimer);
    window._vmoAutoSaveTimer = setTimeout(function() {
        if (typeof jQuery === 'undefined' || typeof vmo_ajax === 'undefined') return;
        if (!window.vmoState || !window.vmoState.blocks || !window.vmoState.blocks.length) return;

        var html = window.vmoState.blocks.map(function(b){ return b.html; }).join('\n');
        if (typeof window.vmoNormalizeBuilderHtml === 'function') {
            html = window.vmoNormalizeBuilderHtml(html);
        }
        if (typeof window.vmoShouldTreatAsRealContent === 'function' && !window.vmoShouldTreatAsRealContent(html, window.vmoState)) {
            return;
        }
        if (!html.trim()) return;

        var title = window.currentProjectTitle || 'Auto-saved Website';
        window.vmoSaveProjectSnapshot({
            title: title,
            html: html,
            state: window.vmoState,
            markSaved: true
        }).then(function() {
                if (!window.currentProjectTitle) {
                    window.currentProjectTitle = title;
                }
                window.isUnsaved = false;
                console.log('[VMO] Auto-saved checkpoint to server');
        }).catch(function() {
            console.warn('[VMO] Server auto-save failed; localStorage backup preserved');
        });
    }, 8000);
};

// Media replacement function for blocks
window.vmoReplaceMediaInBlocks = function(mediaId, mediaUrl, mediaType) {
    if (!window.vmoState || !window.vmoState.blocks) return;
    let changed = false;
    
    window.vmoState.blocks.forEach(block => {
        if (block.html && block.html.includes(`data-media-id="${mediaId}"`)) {
            changed = true;
            // Update block HTML to reflect the new media
            if (mediaType === 'video') {
                block.html = block.html.replace(
                    new RegExp(`<div[^>]*data-media-id="${mediaId}"[^>]*>.*?</div>`, 'gs'),
                    `<div class="vmo-media-placeholder" data-type="video" data-media-id="${mediaId}">
                        <video src="${mediaUrl}" autoplay muted loop style="width:100%;height:100%;object-fit:cover;display:block;" data-media-id="${mediaId}" data-type="video"></video>
                    </div>`
                );
            } else if (mediaType === 'audio') {
                block.html = block.html.replace(
                    new RegExp(`<div[^>]*data-media-id="${mediaId}"[^>]*>.*?</div>`, 'gs'),
                    `<div class="vmo-media-placeholder" data-type="audio" data-media-id="${mediaId}">
                        <audio src="${mediaUrl}" controls style="width:100%;display:block;" data-media-id="${mediaId}" data-type="audio"></audio>
                    </div>`
                );
            } else {
                block.html = block.html.replace(
                    new RegExp(`<div[^>]*data-media-id="${mediaId}"[^>]*>.*?</div>`, 'gs'),
                    `<div class="vmo-media-placeholder" data-type="image" data-media-id="${mediaId}">
                        <img src="${mediaUrl}" alt="User Image" style="width:100%;height:100%;object-fit:cover;display:block;" data-media-id="${mediaId}" data-type="image" />
                    </div>`
                );
            }
        }
    });

    if (!changed) {
        if (typeof window.vmoSyncPreviewStateFromIframe === 'function') {
            window.vmoSyncPreviewStateFromIframe({ markUnsaved: true, autoSave: true });
        }
        return;
    }
    
    // Trigger re-render
    if (typeof window.renderBlocks === 'function') {
        window.renderBlocks();
    }
    window.isUnsaved = true;
    if (typeof window.autoSaveCheckpoint === 'function') {
        window.autoSaveCheckpoint();
    }
};