/**
 * VMO Iframe Wrapper - High-Quality Modern Website Support
 * Ensures iframe is ready for GSAP animations, modern frameworks, and professional websites
 * Version: 1.0.0
 */

(function() {
    'use strict';

    function hasShowcasePreviewStructure(content) {
        const input = String(content || '');

        if (!/id=["']vmo-demo-showcase["']|data-vmo-preview-mode=["']showcase-placeholder["']/i.test(input)) {
            return false;
        }

        return /id=["']vmo-showcase-stage["']|class=["'][^"']*(?:vmo-showcase-slide|demo-hero|demo-shell)[^"']*["']/i.test(input);
    }

    function hasMeaningfulPreviewHtml(content) {
        const input = String(content || '').trim();
        let body = input;
        let previous = '';
        let guard = 0;

        if (!input) return false;
        if (/id=["']vmo-demo-showcase["']|data-vmo-preview-mode=["']showcase-placeholder["']/i.test(input)
            && !hasShowcasePreviewStructure(input)) {
            return false;
        }

        const bodyMatch = input.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);
        if (bodyMatch) {
            body = bodyMatch[1];
        }

        body = body
            .replace(/<!--[\s\S]*?-->/g, '')
            .replace(/<script[\s\S]*?<\/script>/gi, '')
            .replace(/<style[\s\S]*?<\/style>/gi, '')
            .replace(/<link\b[^>]*>/gi, '')
            .replace(/<meta\b[^>]*>/gi, '')
            .replace(/<title[\s\S]*?<\/title>/gi, '')
            .replace(/&nbsp;/gi, ' ');

        while (previous !== body && guard < 8) {
            previous = body;
            body = body.replace(/<([a-z0-9:-]+)\b[^>]*>\s*<\/\1>/gi, '');
            guard += 1;
        }

        return /\S/.test(body);
    }

    function stripEditorOnlyMediaOverlaysFromMarkup(content) {
        let html = String(content || '');
        if (!html) return '';

        if (typeof window.DOMParser === 'function') {
            try {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                doc.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();
                });
                doc.querySelectorAll('[data-vmo-has-button]').forEach(function(node) {
                    node.removeAttribute('data-vmo-has-button');
                });

                if (/^\s*(<!doctype|<html[\s>])/i.test(html)) {
                    return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
                }
                return doc.body ? doc.body.innerHTML : html;
            } catch (_) {}
        }

        return html
            .replace(/<button\b[^>]*(?:data-replace-media|data-vmo-editor-only=["']media-replace-overlay["']|class=["'][^"']*(?:vmo-replace-overlay|vmo-replace-btn|vmo-replace-media-btn|replace-image-btn|replace-video-btn)[^"']*["'])[^>]*>[\s\S]*?<\/button>/gi, '')
            .replace(/\sdata-vmo-has-button=("[^"]*"|'[^']*'|[^\s>]+)/gi, '');
    }

    function sanitizeGeneratedHtml(content) {
        const input = String(content || '');
        if (!input) return '';

        return stripEditorOnlyMediaOverlaysFromMarkup(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');
    }

    function getPluginAssetBaseUrl() {
        const value = (typeof window.vmo_ajax !== 'undefined' && (window.vmo_ajax.plugin_url || window.vmo_ajax.pluginUrl)) || '';
        const trimmed = String(value || '').replace(/\/+$/, '');
        return trimmed ? trimmed + '/' : '';
    }

    function injectMarkupIntoHead(documentHtml, markup) {
        if (!markup) return documentHtml;

        if (/<\/head>/i.test(documentHtml)) {
            return documentHtml.replace(/<\/head>/i, markup + '\n</head>');
        }

        if (/<html\b[^>]*>/i.test(documentHtml)) {
            return documentHtml.replace(/<html\b([^>]*)>/i, '<html$1><head>' + markup + '</head>');
        }

        return markup + documentHtml;
    }

    function enhanceExistingPreviewDocument(documentHtml) {
        let html = String(documentHtml || '');
        if (!html) return html;

        const pluginAssetBaseUrl = getPluginAssetBaseUrl();
        const needsGsap = !/gsap(?:\.min)?\.js|cdn\.jsdelivr\.net\/npm\/gsap(?:@[^"']+)?\/dist\/gsap|unpkg\.com\/gsap(?:@[^"']+)?\/dist\/gsap|cdnjs\.cloudflare\.com\/ajax\/libs\/gsap/i.test(html);
        const needsScrollTrigger = !/ScrollTrigger(?:\.min)?\.js|cdn\.jsdelivr\.net\/npm\/gsap(?:@[^"']+)?\/dist\/ScrollTrigger|unpkg\.com\/gsap(?:@[^"']+)?\/dist\/ScrollTrigger|cdnjs\.cloudflare\.com\/ajax\/libs\/gsap\/[0-9.]+\/ScrollTrigger/i.test(html);
        const needsMotionRuntime = pluginAssetBaseUrl && !/vmo-motion-runtime\.js/i.test(html);
        const headMarkup = [];

        if (needsGsap) {
            headMarkup.push('<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>');
        }

        if (needsScrollTrigger) {
            headMarkup.push('<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollTrigger.min.js"></script>');
        }

        if (needsMotionRuntime) {
            headMarkup.push('<script src="' + pluginAssetBaseUrl + 'assets/vmo-motion-runtime.js"></script>');
        }

        if (!headMarkup.length) {
            return html;
        }

        return injectMarkupIntoHead(html, '\n    ' + headMarkup.join('\n    ') + '\n');
    }

    function stripPreviewArtifacts(doc) {
        if (!doc || !doc.documentElement) return '';

        const root = doc.documentElement.cloneNode(true);
        root.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();
        });

        root.querySelectorAll('[data-vmo-has-button]').forEach(function(node) {
            node.removeAttribute('data-vmo-has-button');
        });

        root.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 '<!DOCTYPE html>\n' + root.outerHTML;
    }

    window.vmoSanitizeGeneratedHtml = sanitizeGeneratedHtml;
    window.vmoStripEditorOnlyMediaOverlays = stripEditorOnlyMediaOverlaysFromMarkup;
    window.vmoHasMeaningfulPreviewHtml = hasMeaningfulPreviewHtml;

    window.vmoSerializePreviewDocument = function(iframeElement) {
        const iframe = iframeElement || document.getElementById('vmo-preview-iframe');
        if (!iframe) return '';

        try {
            const doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document) || null;
            if (doc && doc.documentElement) {
                const serialized = stripPreviewArtifacts(doc);
                return hasMeaningfulPreviewHtml(serialized) ? serialized : '';
            }
        } catch (_) {}

        const fallback = String(iframe.getAttribute('srcdoc') || iframe.srcdoc || '');
        return hasMeaningfulPreviewHtml(fallback) ? fallback : '';
    };

    /**
     * Wrap iframe content with proper HTML structure and modern libraries
     * @param {string} content - The HTML content to wrap
     * @returns {string} - Complete HTML document with all modern libraries
     */
    window.wrapIframeContent = function(content) {
        const sanitizedContent = sanitizeGeneratedHtml(content);
        const pluginAssetBaseUrl = getPluginAssetBaseUrl();
        const motionRuntimeTag = pluginAssetBaseUrl
            ? '<script src="' + pluginAssetBaseUrl + 'assets/vmo-motion-runtime.js"></script>'
            : '';

        // If content already has <!DOCTYPE>, return as-is
        if (sanitizedContent.trim().toLowerCase().startsWith('<!doctype') || 
            sanitizedContent.trim().toLowerCase().startsWith('<html')) {
            return enhanceExistingPreviewDocument(sanitizedContent);
        }

        // Build complete HTML document with modern libraries
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VMO Preview</title>
    
    <!-- Performance & Quality Optimizations -->
    <meta name="theme-color" content="#ffffff">
    <meta name="color-scheme" content="light dark">
    
    <!-- Modern CSS Reset & Base Styles -->
    <style>
        /* Modern CSS Reset */
        *, *::before, *::after {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        html {
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
            scroll-behavior: smooth;
            height: 100%;
        }
        
        body {
            min-height: 100%;
            line-height: 1.6;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            overflow-x: hidden;
            position: relative;
        }
        
        img, picture, video, canvas, svg {
            display: block;
            max-width: 100%;
            height: auto;
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
        }
        
        /* Smooth animations */
        @media (prefers-reduced-motion: no-preference) {
            * {
                transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
            }
        }
        
        /* Hardware acceleration helpers */
        .vmo-accelerated {
            transform: translateZ(0);
            will-change: transform;
        }
        
        /* High-quality image rendering */
        img {
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
        }
        
        /* Smooth scrolling */
        html {
            scroll-behavior: smooth;
        }
        
        /* Better text rendering */
        body {
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
        }
    </style>
    
    <!--
        CDN LIBRARIES FOR GENERATED WEBSITE OUTPUT
        These scripts are injected into a sandboxed iframe that previews the
        AI-generated website, NOT into the WordPress admin interface. They
        provide the runtime libraries (React, GSAP, Tailwind, etc.) that the
        generated website code depends on. Bundling these ~5 MB of libraries
        into the plugin distribution is impractical; they are loaded on-demand
        only when previewing a generated site.
    -->
    
    <!-- GSAP Core (Latest Version) - For advanced animations -->
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>
    
    <!-- GSAP ScrollTrigger Plugin - For scroll-based animations -->
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollTrigger.min.js"></script>
    
    <!-- GSAP ScrollToPlugin - For smooth scrolling -->
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollToPlugin.min.js"></script>
    
    <!-- GSAP Draggable Plugin - For draggable elements -->
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/Draggable.min.js"></script>
    
    <!-- GSAP MotionPathPlugin - For complex animations -->
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js"></script>

    <!-- React & ReactDOM (Development for runtime JSX compilation) -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    
    <!-- Babel Standalone (for compiling JSX in browser) -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <!-- Tailwind CSS (Play CDN for runtime styling) -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                    }
                }
            }
        }
    </script>

    <!-- Three.js (3D Graphics) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>

    <!-- Framer Motion (via CDN, requires React) -->
    <script src="https://unpkg.com/framer-motion@10.16.4/dist/framer-motion.js"></script>

    <!-- Spline Viewer (3D Scenes) -->
    <script type="module" src="https://unpkg.com/@splinetool/viewer@1.0.54/build/spline-viewer.js"></script>

    <!-- Lenis (Smooth Scroll) -->
    <script src="https://cdn.jsdelivr.net/npm/lenis@1.1.13/dist/lenis.min.js"></script>

    <!-- Locomotive Scroll -->
    <script src="https://cdn.jsdelivr.net/npm/locomotive-scroll@4.1.4/dist/locomotive-scroll.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/locomotive-scroll@4.1.4/dist/locomotive-scroll.min.css">

    <!-- Swiper.js (Modern Slider) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

    <!-- Barba.js (Page Transitions) -->
    <script src="https://unpkg.com/@barba/core"></script>

    <!-- Lottie Web (Vector Animations) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js"></script>
    
    <!-- Splide.js - Modern carousel/slider -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css">
    <script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js"></script>
    
    <!-- AOS (Animate On Scroll) - Scroll animations -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.css">
    <script src="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.js"></script>
    
    <!-- Font Awesome - Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <!-- VMO Analytics Tracking - Fix #4 -->
    <script>
        // VMO Website Analytics Tracker (self-hosted)
        (function() {
            'use strict';

            var ajaxUrl = (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : null;
            var siteOwnerId = (typeof vmo_ajax !== 'undefined' && (vmo_ajax.userId || vmo_ajax.user_id)) ? (vmo_ajax.userId || vmo_ajax.user_id) : null;
            var contactKey = 'vmo_contact_id';
            var contactId = (function(){ try { return localStorage.getItem(contactKey) || ''; } catch(e){ return ''; } })();

            function post(action, params) {
                if (!ajaxUrl || !siteOwnerId) return Promise.resolve(null);
                var body = new URLSearchParams(Object.assign({ action: action, site_owner_id: siteOwnerId }, params || {}));
                return fetch(ajaxUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: body
                }).then(function(r){ return r.json(); }).catch(function(){ return null; });
            }

            // Initialize VMO Analytics
            window.vmoAnalytics = {
                pageViews: 0,
                events: [],
                sessionStart: Date.now(),

                trackVisit: function() {
                    var self = this;
                    return post('vmo_track_visit', {
                        contact_id: contactId,
                        page_url: window.location.href,
                        page_title: document.title,
                        referrer: document.referrer
                    }).then(function(res){
                        if (res && res.success && res.data && res.data.contact_id) {
                            contactId = res.data.contact_id;
                            try { localStorage.setItem(contactKey, contactId); } catch(e) {}
                        }
                        return res;
                    });
                },

                // Track page view
                trackPageView: function() {
                    this.pageViews++;
                    this.events.push({ type: 'pageview', data: { page_url: window.location.href } });
                    if (!contactId) return;
                    return post('vmo_track_pageview', {
                        contact_id: contactId,
                        page_url: window.location.href,
                        page_title: document.title,
                        time_on_page: 0
                    });
                },

                // Track custom event
                trackEvent: function(category, action, label, value) {
                    var payload = { category: category, action: action, label: label, value: value, timestamp: Date.now() };
                    this.events.push({ type: 'event', data: payload });
                    if (!contactId) return;
                    return post('vmo_track_event', {
                        contact_id: contactId,
                        event_name: category + ':' + action,
                        event_data: JSON.stringify(payload)
                    });
                },

                trackExit: function() {
                    if (!ajaxUrl || !siteOwnerId || !contactId) return;
                    var seconds = Math.round((Date.now() - window.vmoAnalytics.sessionStart) / 1000);
                    var data = new FormData();
                    data.append('action', 'vmo_track_exit');
                    data.append('site_owner_id', siteOwnerId);
                    data.append('contact_id', contactId);
                    data.append('page_url', window.location.href);
                    data.append('duration_seconds', seconds);
                    data.append('duration_minutes', Math.round(seconds / 60));
                    try {
                        if (navigator.sendBeacon) {
                            navigator.sendBeacon(ajaxUrl, data);
                        }
                    } catch(e) {}
                }
            };
            
            // Auto-track initial page view
            window.addEventListener('load', function() {
                window.vmoAnalytics.trackVisit().then(function(){
                    window.vmoAnalytics.trackPageView();
                });
            });
            
            // Track outbound links
            document.addEventListener('click', function(e) {
                var link = e.target.closest('a');
                if (link && link.href && !link.href.startsWith(window.location.origin)) {
                    window.vmoAnalytics.trackEvent('outbound', 'click', link.href);
                }
            });
            
            // Track time on page
            window.addEventListener('beforeunload', function() {
                var timeOnPage = Math.round((Date.now() - window.vmoAnalytics.sessionStart) / 1000);
                window.vmoAnalytics.trackEvent('engagement', 'time_on_page', '', timeOnPage);
                window.vmoAnalytics.trackExit();
            });
            
            console.log('[VMO Analytics] Tracking initialized ✅');
        })();
    </script>
    
    <!-- Google Fonts - Modern Typography (Common Fonts) -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Playfair+Display:wght@400;500;600;700;800;900&family=Montserrat:wght@300;400;500;600;700;800;900&family=Poppins:wght@300;400;500;600;700;800;900&family=Roboto:wght@300;400;500;700;900&display=swap" rel="stylesheet">
    ${motionRuntimeTag}
    
    <!-- Initialization Script -->
    <script>
        // Initialize GSAP plugins
        if (typeof gsap !== 'undefined') {
            gsap.registerPlugin(ScrollTrigger, ScrollToPlugin, Draggable, MotionPathPlugin);
            
            // Configure ScrollTrigger defaults for better performance
            ScrollTrigger.config({
                limitCallbacks: true,
                syncInterval: 150
            });
            
            // Refresh ScrollTrigger on window resize
            let resizeTimer;
            window.addEventListener('resize', function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function() {
                    ScrollTrigger.refresh();
                }, 250);
            });
        }
        
        // Initialize AOS
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Lenis (Smooth Scroll)
            if (typeof Lenis !== 'undefined') {
                const lenis = new Lenis({
                    duration: 1.2,
                    easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
                    direction: 'vertical',
                    gestureDirection: 'vertical',
                    smooth: true,
                    mouseMultiplier: 1,
                    smoothTouch: false,
                    touchMultiplier: 2,
                });

                function raf(time) {
                    lenis.raf(time);
                    requestAnimationFrame(raf);
                }
                requestAnimationFrame(raf);
                
                // Connect Lenis to GSAP ScrollTrigger
                if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
                    lenis.on('scroll', ScrollTrigger.update);
                    gsap.ticker.add((time) => {
                        lenis.raf(time * 1000);
                    });
                    gsap.ticker.lagSmoothing(0);
                }
            }

            // Initialize Barba.js (Page Transitions)
            if (typeof barba !== 'undefined') {
                try {
                    barba.init({
                        transitions: [{
                            name: 'opacity-transition',
                            leave(data) {
                                return gsap.to(data.current.container, { opacity: 0 });
                            },
                            enter(data) {
                                return gsap.from(data.next.container, { opacity: 0 });
                            }
                        }]
                    });
                } catch(e) { /* Barba init skipped (likely single page mode) */ }
            }

            if (typeof AOS !== 'undefined') {
                AOS.init({
                    duration: 800,
                    easing: 'ease-in-out',
                    once: false,
                    mirror: true,
                    offset: 50
                });
            }
            
            // Auto-initialize Swiper carousels
            if (typeof Swiper !== 'undefined') {
                document.querySelectorAll('.swiper').forEach(function(element) {
                    if (!element.classList.contains('swiper-initialized')) {
                        new Swiper(element, {
                            loop: true,
                            autoplay: { delay: 3000 },
                            pagination: { el: '.swiper-pagination', clickable: true },
                            navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }
                        });
                    }
                });
            }

            // Auto-initialize Splide carousels
            if (typeof Splide !== 'undefined') {
                document.querySelectorAll('.splide').forEach(function(element) {
                    if (!element.classList.contains('splide-initialized')) {
                        new Splide(element, {
                            type: 'loop',
                            perPage: 3,
                            perMove: 1,
                            gap: '1rem',
                            autoplay: true,
                            interval: 3000,
                            pauseOnHover: true,
                            breakpoints: {
                                768: { perPage: 1 },
                                1024: { perPage: 2 }
                            }
                        }).mount();
                        element.classList.add('splide-initialized');
                    }
                });
            }
            
            // Enable smooth scrolling for anchor links
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    const target = document.querySelector(this.getAttribute('href'));
                    if (target) {
                        if (typeof gsap !== 'undefined' && gsap.plugins.scrollTo) {
                            gsap.to(window, {
                                duration: 1,
                                scrollTo: { y: target, offsetY: 50 },
                                ease: 'power2.inOut'
                            });
                        } else {
                            target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }
                    }
                });
            });
            
            // Add lazy loading for images
            if ('IntersectionObserver' in window) {
                const imageObserver = new IntersectionObserver((entries, observer) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            if (img.dataset.src) {
                                img.src = img.dataset.src;
                                img.classList.add('loaded');
                                observer.unobserve(img);
                            }
                        }
                    });
                });
                
                document.querySelectorAll('img[data-src]').forEach(img => {
                    imageObserver.observe(img);
                });
            }
            
            // Performance monitoring
            if (window.performance && window.performance.mark) {
                performance.mark('vmo-iframe-ready');
            }

            if (window.vmoGeneratedSiteEffects && typeof window.vmoGeneratedSiteEffects.init === 'function') {
                window.vmoGeneratedSiteEffects.init();
            }
        });
        
        // Global utilities for generated websites
        window.VMO = {
            version: '2.0.0',
            
            // Animate element with GSAP
            animate: function(element, properties, duration = 0.5) {
                if (typeof gsap !== 'undefined') {
                    return gsap.to(element, { ...properties, duration: duration });
                }
            },
            
            // Scroll to element
            scrollTo: function(element, offset = 0) {
                if (typeof gsap !== 'undefined' && gsap.plugins.scrollTo) {
                    gsap.to(window, {
                        duration: 1,
                        scrollTo: { y: element, offsetY: offset },
                        ease: 'power2.inOut'
                    });
                } else if (element) {
                    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            },
            
            // Refresh animations
            refresh: function() {
                if (window.vmoGeneratedSiteEffects && typeof window.vmoGeneratedSiteEffects.refresh === 'function') {
                    window.vmoGeneratedSiteEffects.refresh();
                }
                if (typeof ScrollTrigger !== 'undefined') {
                    ScrollTrigger.refresh();
                }
                if (typeof AOS !== 'undefined') {
                    AOS.refresh();
                }
            },
            
            // Initialize new carousels dynamically
            initCarousel: function(element, options = {}) {
                if (typeof Splide !== 'undefined' && element) {
                    return new Splide(element, {
                        type: 'loop',
                        perPage: 3,
                        perMove: 1,
                        gap: '1rem',
                        autoplay: true,
                        interval: 3000,
                        pauseOnHover: true,
                        ...options
                    }).mount();
                }
            }
        };
        
        // Console styling
        console.log('%cVMO Iframe Ready! 🚀', 'color: #00e2ff; font-size: 16px; font-weight: bold;');
        console.log('%cGSAP, ScrollTrigger, Splide, AOS, and Font Awesome loaded', 'color: #00e2ff;');
    </script>
</head>
<body>
    ${sanitizedContent}
    
    <!-- Additional performance optimizations -->
    <script>
        // Smooth scroll restoration
        if ('scrollRestoration' in history) {
            history.scrollRestoration = 'manual';
        }
        
        // Report ready state
        window.addEventListener('load', function() {
            console.log('%cVMO Website Fully Loaded ✨', 'color: #00ff00; font-size: 14px; font-weight: bold;');
            
            // Final refresh of animations
            if (window.VMO) {
                setTimeout(function() {
                    window.VMO.refresh();
                }, 100);
            }
        });
    </script>
</body>
</html>`;
    };

    /**
     * Reinitialize iframe when content changes
     */
    window.reinitializeIframeLibraries = function(iframeElement) {
        if (!iframeElement || !iframeElement.contentWindow) return;
        
        const iframeWindow = iframeElement.contentWindow;
        const iframeDocument = iframeElement.contentDocument || iframeWindow.document;
        
        try {
            // Wait for iframe to be ready
            if (iframeDocument.readyState === 'complete') {
                initializeIframeContent(iframeWindow, iframeDocument);
            } else {
                iframeWindow.addEventListener('load', function() {
                    initializeIframeContent(iframeWindow, iframeDocument);
                });
            }
        } catch(e) {
            console.warn('[VMO] Could not reinitialize iframe libraries:', e);
        }
    };
    
    function initializeIframeContent(iframeWindow, iframeDocument) {
        // Initialize GSAP if available
        if (iframeWindow.gsap && iframeWindow.ScrollTrigger) {
            iframeWindow.gsap.registerPlugin(iframeWindow.ScrollTrigger);
            iframeWindow.ScrollTrigger.refresh();
        }
        
        // Initialize AOS if available
        if (iframeWindow.AOS) {
            iframeWindow.AOS.init({
                duration: 800,
                once: false,
                mirror: true
            });
        }
        
        // Initialize Splide carousels
        if (iframeWindow.Splide) {
            iframeDocument.querySelectorAll('.splide:not(.splide-initialized)').forEach(function(element) {
                new iframeWindow.Splide(element, {
                    type: 'loop',
                    perPage: 3,
                    perMove: 1,
                    gap: '1rem',
                    autoplay: true,
                    interval: 3000,
                    pauseOnHover: true,
                    breakpoints: {
                        768: { perPage: 1 },
                        1024: { perPage: 2 }
                    }
                }).mount();
                element.classList.add('splide-initialized');
            });
        }

        if (iframeWindow.vmoGeneratedSiteEffects && typeof iframeWindow.vmoGeneratedSiteEffects.refresh === 'function') {
            iframeWindow.vmoGeneratedSiteEffects.refresh();
        }
        
        console.log('[VMO] Iframe libraries reinitialized');
    }

    console.log('[VMO] Iframe wrapper system loaded ✅');
})();
