/**
 * VMO shipped preview state.
 *
 * The generated website renderer still owns the iframe when real content exists.
 * Until then, the preview stays inside a standalone srcdoc document so WordPress
 * chrome, themes, and editor UI never become the builder iframe fallback.
 */
(function() {
    'use strict';

    const SHIPPED_PREVIEW_HTML = '<!doctype html><html data-vmo-preview-mode="showcase-placeholder"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>VMO Builder Preview</title><style>html,body{margin:0;width:100%;min-height:100%;background:#f8fafc;color:#0f172a;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;}body{display:grid;place-items:center;padding:32px;box-sizing:border-box;}.demo-shell{width:min(960px,100%);min-height:min(620px,calc(100vh - 64px));display:grid;place-items:center;border:1px solid rgba(15,23,42,.08);border-radius:18px;background:linear-gradient(135deg,#ffffff 0%,#f1f5f9 48%,#e0f2fe 100%);box-shadow:0 24px 80px rgba(15,23,42,.12);}.vmo-reset-card{width:min(560px,calc(100% - 40px));padding:34px;border-radius:16px;background:rgba(255,255,255,.82);border:1px solid rgba(15,23,42,.08);box-shadow:0 18px 50px rgba(15,23,42,.1);}.vmo-reset-mark{width:54px;height:54px;border-radius:16px;display:grid;place-items:center;background:#0f172a;color:#67e8f9;font-weight:900;letter-spacing:.04em;margin-bottom:20px;}.vmo-reset-title{margin:0 0 10px;font-size:28px;line-height:1.15;}.vmo-reset-copy{margin:0;color:#475569;font-size:15px;line-height:1.7;}.vmo-reset-steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:24px;}.vmo-reset-step{height:8px;border-radius:999px;background:#cbd5e1;}.vmo-reset-step:first-child{background:#22d3ee;}@media(max-width:640px){body{padding:16px}.demo-shell{min-height:calc(100vh - 32px);border-radius:14px}.vmo-reset-card{padding:24px}.vmo-reset-title{font-size:24px}}</style></head><body><main id="vmo-demo-showcase" class="demo-shell" data-vmo-preview-mode="showcase-placeholder"><section id="vmo-showcase-stage" class="vmo-reset-card"><div class="vmo-reset-mark">VMO</div><h1 class="vmo-reset-title">Builder ready</h1><p class="vmo-reset-copy">Your current website instance has been cleared from the builder preview. Start a new consultation or restore one of the protected backups to continue.</p><div class="vmo-reset-steps" aria-hidden="true"><span class="vmo-reset-step"></span><span class="vmo-reset-step"></span><span class="vmo-reset-step"></span></div></section></main></body></html>';

    function escapeHtmlAttribute(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function getVmoIconUrl() {
        const source = window.vmoAjax || window.vmo_ajax || {};
        const pluginBase = String(source.pluginUrl || source.plugin_url || '').replace(/\/+$/, '');
        return pluginBase ? pluginBase + '/assets/vmo-icon.svg' : 'assets/vmo-icon.svg';
    }

    function buildShippedPreviewHtml() {
        return SHIPPED_PREVIEW_HTML
            .replace('</style>', '.vmo-reset-mark{background:#fff;overflow:hidden;padding:6px}.vmo-reset-mark img{width:100%;height:100%;display:block;object-fit:contain}</style>')
            .replace('<div class="vmo-reset-mark">VMO</div>', '<div class="vmo-reset-mark"><img src="' + escapeHtmlAttribute(getVmoIconUrl()) + '" alt="VMO logo"></div>');
    }

    function hasRenderablePreview() {
        if (window.vmoPreviewIsLive) return true;

        if (typeof window.vmoShouldTreatAsRealContent === 'function') {
            const state = window.vmoState && typeof window.vmoState === 'object'
                ? window.vmoState
                : { blocks: [] };
            const combinedStateHtml = Array.isArray(state.blocks)
                ? state.blocks.map(function(block) {
                    return block && block.html ? String(block.html) : '';
                }).join('\n')
                : '';

            if (window.vmoShouldTreatAsRealContent(window.lastContent || '', state)) return true;
            if (window.vmoShouldTreatAsRealContent(combinedStateHtml, state)) return true;
            return false;
        }

        if (window.vmoHasContent) return true;
        if (typeof window.lastContent === 'string' && window.lastContent.trim()) return true;
        if (Array.isArray(window.vmoState?.blocks) && window.vmoState.blocks.length > 0) return true;
        return false;
    }

    function clearPreviewDatasets(iframe) {
        if (!iframe || !iframe.dataset) return;
        delete iframe.dataset.vmoPreviewMode;
        delete iframe.dataset.vmoShowcaseRecoveryCount;
        delete iframe.dataset.vmoShowcaseMediaState;
    }

    function setShippedPreviewFrame(options) {
        const settings = options && typeof options === 'object' ? options : {};
        const iframe = document.getElementById('vmo-preview-iframe');

        if (!iframe) {
            return false;
        }

        if (!settings.force && hasRenderablePreview()) {
            return false;
        }

        iframe.style.display = '';
        iframe.style.visibility = 'visible';
        iframe.removeAttribute('src');
        clearPreviewDatasets(iframe);
        iframe.dataset.vmoPreviewMode = 'showcase-placeholder';
        iframe.dataset.vmoShowcaseMediaState = 'shipped';
        const previewHtml = buildShippedPreviewHtml();
        iframe.srcdoc = previewHtml;
        window.vmoShowcasePreviewHtml = previewHtml;

        if (settings.skipPersist !== true && typeof window.vmoPersistPreviewFrameState === 'function') {
            window.vmoPersistPreviewFrameState('blank-preview-set');
        }

        return true;
    }

    function noopStatus() {
        return false;
    }

    window.vmoGetDemoPreviewUrl = function() {
        return '';
    };

    window.vmoLoadDemoPreviewFrame = function(options) {
        return setShippedPreviewFrame(options || { force: true });
    };

    window.vmoPostDemoPreviewStatus = noopStatus;

    window.vmoGenerateDemoPreviewMedia = function() {
        return Promise.resolve({ disabled: true, message: 'Preview media generation is disabled.' });
    };

    window.vmoIsShowcasePreviewActive = function() {
        return false;
    };

    window.vmoBuildShowcasePreviewHtml = function() {
        return buildShippedPreviewHtml();
    };

    window.vmoBlankPreviewFrame = setShippedPreviewFrame;

    window.showIframePlaceholder = function(options) {
        const settings = options && typeof options === 'object' ? options : {};
        return setShippedPreviewFrame(settings);
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            if (!hasRenderablePreview()) {
                setShippedPreviewFrame({ force: true, skipPersist: true });
            }
        });
    } else if (!hasRenderablePreview()) {
        setShippedPreviewFrame({ force: true, skipPersist: true });
    }
})();
