(function ($) {

    function sanitizePreviewHtml(html) {
        const input = String(html || '');
        let sanitized = input;
        if (!input) return '';

        if (typeof window.vmoSanitizeGeneratedHtml === 'function') {
            sanitized = window.vmoSanitizeGeneratedHtml(input);
        } else {
            sanitized = input
                .replace(/<!--[\s\S]*?-->/g, '')
                .replace(/AI\s+Image\s+Generating\.\.\./gi, '')
                .replace(/AI\s+Video\s+Generating\.\.\./gi, '')
                .replace(/A professional (?:image|video) will appear here/gi, '')
                .replace(/\n{3,}/g, '\n\n');
        }

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

        sanitized = sanitized.replace(/<link\b(?=[^>]*\brel\s*=\s*['"]?stylesheet['"]?)[^>]*>/gi, tag => {
            const hrefMatch = tag.match(/\bhref\s*=\s*(['"])(.*?)\1/i) || tag.match(/\bhref\s*=\s*([^\s>]+)/i);
            const href = hrefMatch ? String(hrefMatch[2] || hrefMatch[1] || '').trim() : '';

            if (!href || /^(#|javascript:|about:blank)/i.test(href)) return '';
            if (/^(https?:|data:|blob:|\/)/i.test(href)) return tag;

            return '';
        });

        return sanitized;
    }

    function extractDocumentBodyHtml(html) {
        const input = String(html || '');
        const bodyMatch = input.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);

        if (!input) return '';
        return bodyMatch ? bodyMatch[1] : input;
    }

    /* ---------- RENDER BLOCKS (isolate-styles fix) ---------- */
    window.renderBlocks = (function (orig) {
        return function () {

            // 0️⃣  keep whatever an earlier renderBlocks did
            if (typeof orig === 'function') orig.apply(this, arguments);

            // --- isolate styles so they don't leak into admin UI ---
            const $canvas = $('#builder-canvas');
            if ($canvas.length) {
                const safeHTML = sanitizePreviewHtml($canvas.html())
                    .replace(/<style[\s\S]*?<\/style>/gi, '')
                    .replace(/<script[\s\S]*?<\/script>/gi, '')
                    .replace(/<link[^>]+rel=["']?stylesheet["'][^>]*>/gi, '');
                $canvas.html(safeHTML);
            }

            // 1️⃣  Build two copies of the page
            // – iframeHtml  : full code (styles / scripts intact)
            // – canvasHtml  : stripped for the admin wrapper
            let iframeHtml = '';
            let canvasHtml = '';

            let sourceBlocks = Array.isArray(window.vmoState?.blocks) ? window.vmoState.blocks : [];
            if (window.vmoGrapesAdapter && typeof window.vmoGrapesAdapter.runPipeline === 'function') {
                try {
                    const grapesResult = window.vmoGrapesAdapter.runPipeline(sourceBlocks, { minIntervalMs: 300 });
                    if (grapesResult && Array.isArray(grapesResult.blocks)) {
                        sourceBlocks = grapesResult.blocks;
                    }
                } catch (grapesError) {
                    console.warn('⚠️ GrapesJS adapter error, fallback renderer active:', grapesError);
                }
            }

            const singleFullDocumentBlock = sourceBlocks.length === 1
                && sourceBlocks[0]
                && typeof sourceBlocks[0].html === 'string'
                && typeof window.vmoLooksLikeFullDocument === 'function'
                && window.vmoLooksLikeFullDocument(sourceBlocks[0].html);

            if (singleFullDocumentBlock) {
                const fullDocumentHtml = sanitizePreviewHtml(sourceBlocks[0].html);
                const blockId = sourceBlocks[0].id != null ? sourceBlocks[0].id : 'full-document';
                const bodyHtml = extractDocumentBodyHtml(fullDocumentHtml);

                iframeHtml = fullDocumentHtml;
                canvasHtml = `<div data-block-id="${blockId}">${bodyHtml}</div>\n`;
            } else {
                sourceBlocks.forEach(b => {
                    const blockHtml = sanitizePreviewHtml(b && b.html ? b.html : '');

                    // --- Wrap each block in a container with data-block-id ---
                    const wrapped = `<div data-block-id="${b.id}">${blockHtml}</div>\n`;
                    iframeHtml   += wrapped;

                    // strip <style>, <script>, <link rel="stylesheet">
                    const safe   = wrapped
                        .replace(/<style[\s\S]*?<\/style>/gi, '')
                        .replace(/<script[\s\S]*?<\/script>/gi, '')
                        .replace(/<link[^>]+rel=["']?stylesheet["'][^>]*>/gi, '');
                    canvasHtml  += safe;
                });
            }

            iframeHtml = sanitizePreviewHtml(iframeHtml);
            canvasHtml = sanitizePreviewHtml(canvasHtml);

            // 2️⃣  Paint into code view, canvas, iframe
            window.lastContent = iframeHtml;
            $('#vmo-code-view').text(iframeHtml);
            $('#builder-canvas').html(canvasHtml);              // ✅ admin side
            const ifr = $('#vmo-preview-iframe')[0];
            // Do not clobber live preview with srcdoc if we're showing the published page URL
            if (ifr && !window.vmoPreviewIsLive) {
                try {
                    const hasRenderableContent = typeof window.vmoShouldTreatAsRealContent === 'function'
                        ? window.vmoShouldTreatAsRealContent(iframeHtml, { blocks: sourceBlocks })
                        : !!iframeHtml.trim();

                    // If we have content, clear the placeholder flag and render
                    if (iframeHtml.trim() && hasRenderableContent) {
                        window.vmoHasContent = true;
                        if (ifr.dataset) {
                            delete ifr.dataset.vmoPreviewMode;
                            delete ifr.dataset.vmoShowcaseRecoveryCount;
                            delete ifr.dataset.vmoShowcaseMediaState;
                        }
                        ifr.removeAttribute('data-vmo-preview-mode');
                        // Wrap content in proper HTML document structure with modern libraries
                        const wrappedHtml = window.wrapIframeContent ? window.wrapIframeContent(iframeHtml) : iframeHtml;
                        ifr.srcdoc = wrappedHtml;
                    } else {
                        window.vmoHasContent = false;
                        // No content - show placeholder
                        if (typeof window.showIframePlaceholder === 'function') {
                            window.showIframePlaceholder();
                        }
                    }
                } catch(e){ console.warn('[VMO] Unable to set iframe srcdoc', e); }
            }

            // 🔧 NEW: Make sections clickable and add inspector integration
            $('#builder-canvas').find('[data-block-id]').each(function(index) {
                const $section = $(this);
                
                // Add visual indicators and classes
                $section.addClass('vmo-section')
                        .attr('data-section-index', index)
                        .css({
                            'position': 'relative',
                            'cursor': 'pointer',
                            'transition': 'all 0.2s ease'
                        });
                
                // Add hover effect
                $section.hover(
                    function() {
                        if (!$(this).hasClass('vmo-selected')) {
                            $(this).css({
                                'outline': '2px dashed #667eea',
                                'outline-offset': '2px'
                            });
                        }
                    },
                    function() {
                        if (!$(this).hasClass('vmo-selected')) {
                            $(this).css({
                                'outline': 'none'
                            });
                        }
                    }
                );
                
                // Add section label overlay
                const $label = $('<div class="vmo-section-label">')
                    .text(`Section ${index + 1}`)
                    .css({
                        'position': 'absolute',
                        'top': '4px',
                        'left': '4px',
                        'background': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        'color': 'white',
                        'padding': '2px 8px',
                        'font-size': '10px',
                        'font-weight': 'bold',
                        'border-radius': '12px',
                        'opacity': '0',
                        'transition': 'opacity 0.2s ease',
                        'pointer-events': 'none',
                        'z-index': '10'
                    });
                
                $section.prepend($label);
                
                // Show label on hover
                $section.hover(
                    function() { $label.css('opacity', '1'); },
                    function() { if (!$(this).hasClass('vmo-selected')) $label.css('opacity', '0'); }
                );
            });
            
            // Add selected section styling
            $('head').append(`
                <style id="vmo-section-styles">
                    .vmo-section.vmo-selected {
                        outline: 3px solid #667eea !important;
                        outline-offset: 2px !important;
                        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.2) !important;
                    }
                    .vmo-section.vmo-selected .vmo-section-label {
                        opacity: 1 !important;
                        background: #28a745 !important;
                    }
                </style>
            `);

            // 3️⃣  Inject replace buttons into media elements in iframe (shared helper)
            setTimeout(() => { if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') window.vmoInjectReplaceButtonsInIframe(); }, 200);

            // 4️⃣  Optional “whole page editable”
            setTimeout(() => {
                const ifr = document.getElementById('vmo-preview-iframe');
                if (ifr && typeof window.makeIframeTextEditable === 'function') {
                    window.makeIframeTextEditable(ifr);
                }
            }, 200);

            // 5️⃣  Re-tag new nodes & refresh Inspector / autosave flags
            if (typeof addEditableMarkers     === 'function') addEditableMarkers();
            if (typeof vmoSyncLastContent     === 'function') vmoSyncLastContent();
            if (typeof vmoEnableInlineEditing === 'function') vmoEnableInlineEditing();
        };
    })(window.renderBlocks || function () {});

    const INLINE_EDITABLE_SELECTOR = 'body *';
    const INLINE_EDITABLE_TAGS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'a', 'span', 'blockquote', 'figcaption', 'label', 'button', 'strong', 'em', 'small', 'summary', 'dd', 'dt', 'td', 'th', 'caption', 'code', 'pre']);
    const BLOCKISH_CHILD_TAGS = new Set(['ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'BUTTON', 'DIV', 'DL', 'FIELDSET', 'FIGURE', 'FOOTER', 'FORM', 'HEADER', 'MAIN', 'NAV', 'OL', 'P', 'SECTION', 'TABLE', 'UL']);

    function hasDirectEditableText(el) {
        return Array.from(el.childNodes || []).some(node => node && node.nodeType === Node.TEXT_NODE && node.textContent && node.textContent.trim());
    }

    function hasBlockingChildStructure(el) {
        return Array.from(el.children || []).some(child => child && child.tagName && child.tagName !== 'BR' && BLOCKISH_CHILD_TAGS.has(child.tagName));
    }

    function shouldSkipInlineEditable(el) {
        const childElements = Array.from(el.children || []).filter(child => child.tagName !== 'BR');

        if (!el || !el.textContent || !el.textContent.trim()) return true;
        if (typeof window.vmoIsShowcasePreviewActive === 'function' && window.vmoIsShowcasePreviewActive()) return true;
        if (typeof el.matches === 'function' && el.matches('input, textarea, select, option')) return true;
        if (el.closest('.vmo-replace-overlay,[data-noneditable="1"],script,style,noscript,svg,canvas,video,audio')) return true;
        if (el.classList.contains('vmo-replace-overlay')) return true;
        if (el.getAttribute('data-noneditable') === '1') return true;
        if (el.hasAttribute('data-vmo-consultation-trigger')) return true;
        if ((el.tagName === 'SPAN' || el.tagName === 'A' || el.tagName === 'BUTTON') && childElements.length > 2) return true;

        return false;
    }

    function markEditableTextNodes(doc) {
        if (!doc) return;

        doc.querySelectorAll(INLINE_EDITABLE_SELECTOR).forEach(el => {
            const tagName = String(el.tagName || '').toLowerCase();
            const directText = hasDirectEditableText(el);
            const knownTextTag = INLINE_EDITABLE_TAGS.has(tagName);

            if (shouldSkipInlineEditable(el)) return;
            if (el.dataset.vmoEditable === '1') return;
            if (!knownTextTag && !directText) return;
            if (!knownTextTag && hasBlockingChildStructure(el)) return;

            el.dataset.vmoEditable = '1';
            el.setAttribute('data-editable', 'true');
            el.setAttribute('data-vmo-editable', '1');
            el.setAttribute('spellcheck', 'true');
            el.contentEditable = 'true';
            el.style.cursor = 'text';
            el.style.userSelect = 'text';
            el.style.webkitUserSelect = 'text';
            el.addEventListener('mouseenter', () => { el.style.outline = '1px dashed #00f8ff'; });
            el.addEventListener('mouseleave', () => { el.style.outline = 'none'; });
        });
    }

    function findEditableTextTarget(startNode, doc) {
        let el = startNode && startNode.nodeType === 3 ? startNode.parentElement : startNode;
        const body = doc && doc.body;

        while (el && el !== body) {
            if (el.nodeType !== 1) {
                el = el.parentElement;
                continue;
            }

            if (shouldSkipInlineEditable(el)) return null;
            if (el.dataset && el.dataset.vmoEditable === '1') return el;

            const tagName = String(el.tagName || '').toLowerCase();
            const directText = hasDirectEditableText(el);
            const knownTextTag = INLINE_EDITABLE_TAGS.has(tagName);

            if ((knownTextTag || directText) && (!hasBlockingChildStructure(el) || knownTextTag)) {
                markEditableTextNodes(doc);
                return el.dataset && el.dataset.vmoEditable === '1' ? el : null;
            }

            el = el.parentElement;
        }

        return null;
    }

    function focusEditableElement(el) {
        if (!el || typeof el.focus !== 'function') return;

        el.focus({ preventScroll: true });
        if ((el.matches && el.matches('a, button, [role="button"]')) && el.ownerDocument && el.ownerDocument.defaultView) {
            const selection = el.ownerDocument.defaultView.getSelection();
            const range = el.ownerDocument.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }

    function vmoEnableInlineEditing () {
        const iframe = document.getElementById('vmo-preview-iframe');
        if (!iframe || window.vmoPreviewIsLive || !iframe.contentDocument) return;
        if (typeof window.vmoIsShowcasePreviewActive === 'function' && window.vmoIsShowcasePreviewActive()) return;

        const doc = iframe.contentDocument;
        markEditableTextNodes(doc);

        if (!doc.__vmoEditableObserver && doc.body && typeof MutationObserver !== 'undefined') {
            let observerTimer = null;
            const observer = new MutationObserver(() => {
                clearTimeout(observerTimer);
                observerTimer = setTimeout(() => markEditableTextNodes(doc), 120);
            });

            observer.observe(doc.body, {
                childList: true,
                subtree: true,
                characterData: true
            });

            doc.__vmoEditableObserver = observer;
        }

        if (!doc.__vmoEditHook) {
            doc.addEventListener('input', e => {
                const editedEl = e.target && typeof e.target.closest === 'function'
                    ? e.target.closest('[data-editable="true"]')
                    : null;
                const blockEl = editedEl && typeof editedEl.closest === 'function'
                    ? editedEl.closest('[data-block-id]')
                    : null;

                if (!editedEl) return;

                if (typeof window.vmoSyncPreviewStateFromIframe === 'function') {
                    window.vmoSyncPreviewStateFromIframe({
                        blockId: blockEl ? blockEl.dataset.blockId : '',
                        markUnsaved: true
                    });
                } else if (blockEl) {
                    const block = window.vmoState?.blocks?.find(b => String(b.id) === String(blockEl.dataset.blockId));
                    if (block) {
                        block.html = blockEl.innerHTML;
                        if (typeof vmoSyncLastContent === 'function') vmoSyncLastContent();
                    }
                    window.isUnsaved = true;
                }

                if (typeof autoSaveCheckpoint === 'function') {
                    autoSaveCheckpoint();
                }
            });
            doc.__vmoEditHook = true;
        }

        if (!doc.__vmoEditClickHook) {
            doc.addEventListener('click', e => {
                const target = e.target;
                if (!target || (target.closest && target.closest('.vmo-replace-overlay,[data-vmo-editor-only="media-replace-overlay"],input,textarea,select,option'))) return;

                const editable = findEditableTextTarget(target, doc);
                if (!editable) return;

                if (target.closest && target.closest('a,button,[role="button"]')) {
                    e.preventDefault();
                }
                e.stopPropagation();
                focusEditableElement(editable);
            }, true);
            doc.__vmoEditClickHook = true;
        }

        if (doc.body) {
            doc.body.style.pointerEvents = 'auto';
            doc.body.style.userSelect = 'text';
        }
    }

    window.vmoEnableInlineEditing = vmoEnableInlineEditing;

    // Also hook iframe load to re-inject overlays
    document.getElementById('vmo-preview-iframe')?.addEventListener('load', function(){
        const iframe = this;
        setTimeout(() => {
            if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') window.vmoInjectReplaceButtonsInIframe();
            if (!window.vmoPreviewIsLive && typeof window.makeIframeTextEditable === 'function') window.makeIframeTextEditable(iframe);
        }, 100);
    });

    // Re-inject on successful content generation AJAX
    $(document).ajaxSuccess((_, __, settings) => {
        if (typeof settings?.data === 'string' && settings.data.indexOf('vmo_generate_content') !== -1) {
            setTimeout(() => { if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') window.vmoInjectReplaceButtonsInIframe(); }, 150);
        }
    });

    /* ---------------------------------------------------------------
       (OPTIONAL) Full-page editable body – handy for copy/paste
    ---------------------------------------------------------------- */
    window.makeIframeTextEditable = function (iframe) {
        try {
            const doc = iframe.contentDocument || iframe.contentWindow.document;
            if (doc && doc.body) {
                doc.body.style.userSelect = 'text';
                doc.body.style.pointerEvents = 'auto';
                if (typeof window.vmoEnableInlineEditing === 'function') {
                    window.vmoEnableInlineEditing();
                }
            }
        } catch (_) {}
    };

    /* ---------- LIVE CODE-VIEW SYNC (unchanged) ---------- */
    $(document).on('input', '#vmo-code-view', function () {
    const code = $(this).val();
        lastContent = code;
        vmoState.blocks = [{ id: getUniqueBlockId(), html: code, type: 'manual' }];
    if (!window.vmoPreviewIsLive) $('#vmo-preview-iframe')[0].srcdoc = code;
        isUnsaved = true;
    });

    // Replace overlay injection handled by vmo-theme-fixed.js (single source of truth)

    /* mark all headings / paragraphs inside the *iframe* as editable */
    function addEditableMarkers () {
        const ifr = document.getElementById('vmo-preview-iframe');
        if (!ifr || !ifr.contentDocument) return;

        markEditableTextNodes(ifr.contentDocument);
    }

})(jQuery);

/* ================================================================
   DEVICE TOGGLE – resize iframe for mobile / tablet / desktop preview
================================================================ */
(function($) {
    'use strict';

    const DEVICE_SIZES = {
        desktop: { width: '100%', maxWidth: 'none',  label: '🖥 Desktop' },
        tablet:  { width: '768px', maxWidth: '768px', label: '📱 Tablet'  },
        mobile:  { width: '375px', maxWidth: '375px', label: '📲 Mobile'  }
    };

    window.vmoCurrentDevice = 'desktop';

    $(document).on('click', '.vmo-device-btn', function() {
        const device = $(this).data('device');
        if (!device || !DEVICE_SIZES[device]) return;
        window.vmoCurrentDevice = device;

        // Update button active states
        $('.vmo-device-btn').css({ background: 'transparent', border: '1px solid rgba(255,255,255,0.15)', color: '#8899aa' }).removeClass('vmo-device-active');
        $(this).css({ background: 'rgba(102,126,234,0.2)', border: '1px solid #667eea', color: '#667eea' }).addClass('vmo-device-active');

        // Resize iframe
        const ifr = $('#vmo-preview-iframe');
        if (!ifr.length) return;
        const cfg = DEVICE_SIZES[device];
        ifr.css({
            width: cfg.width,
            maxWidth: cfg.maxWidth,
            margin: device === 'desktop' ? '0' : '0 auto',
            transition: 'width 0.35s cubic-bezier(0.4,0,0.2,1), max-width 0.35s cubic-bezier(0.4,0,0.2,1)',
            borderRadius: device === 'desktop' ? '0' : '12px',
            border: device === 'desktop' ? 'none' : '2px solid rgba(102,126,234,0.3)',
            boxShadow: device === 'desktop' ? 'none' : '0 8px 32px rgba(0,0,0,0.3)',
            display: 'block'
        });

        // Also resize code view similarly
        $('#vmo-code-view').css({ width: cfg.width, maxWidth: cfg.maxWidth, margin: device === 'desktop' ? '0' : '0 auto' });

        console.log('[VMO Device] Switched to', device, cfg.width);
    });
})(jQuery);