;(function($){
    // Minimal media module: delegate replace modal to vmo-main.js

    window.vmoMediaModalContext = window.vmoMediaModalContext || {};

    // Called after selecting media from library or generator in replace mode
    window.vmoOnMediaSelected = function(url){
        const ctx = window.vmoMediaModalContext; if(!ctx || !ctx.selector) return;
        const iframe = document.getElementById('vmo-preview-iframe');
        if (!iframe || !iframe.contentDocument) return;
        const doc = iframe.contentDocument;
        const wrap = doc.querySelector(ctx.selector);
        if (!wrap) { window.showToast && showToast('Target element not found.','error'); return; }

        // If this is a background-image target, set CSS instead of injecting child
        if (wrap.dataset && wrap.dataset.bg === '1') {
            wrap.style.backgroundImage = `url('${url}')`;
            wrap.style.backgroundSize = wrap.style.backgroundSize || 'cover';
            wrap.style.backgroundPosition = wrap.style.backgroundPosition || 'center';
        } else {
            // Clear and insert media element
            while (wrap.firstChild) wrap.removeChild(wrap.firstChild);
            const el = ctx.mediaType==='video' ? doc.createElement('video') : doc.createElement('img');
            if (ctx.mediaType==='video') { Object.assign(el,{src:url,autoplay:true,muted:true,loop:true,playsInline:true}); }
            else { el.src=url; el.alt=''; }
            el.style.cssText='width:100%;height:100%;object-fit:cover;display:block;';
            wrap.appendChild(el);
        }

        if (!wrap.dataset.mediaId) wrap.dataset.mediaId = (window.vmoGenerateMediaId? vmoGenerateMediaId(): ('media-'+Date.now()));
        wrap.dataset.type = ctx.mediaType || 'image';
        wrap.classList.add('vmo-media-placeholder');

        // Persist into state
        const blockEl = wrap.closest('[data-block-id]');
        if (blockEl && window.vmoState && Array.isArray(window.vmoState.blocks)) {
            const bid = blockEl.dataset.blockId;
            const block = window.vmoState.blocks.find(b=> String(b.id)===String(bid));
            if (block) {
                block.html = blockEl.innerHTML;
                if (typeof window.vmoSyncLastContent === 'function') window.vmoSyncLastContent();
            }
        } else if (typeof window.vmoSyncPreviewStateFromIframe === 'function') {
            window.vmoSyncPreviewStateFromIframe({ markUnsaved: true });
        }

        if (typeof window.vmoInjectReplaceButtonsInIframe==='function') window.vmoInjectReplaceButtonsInIframe();
        if (typeof window.vmoReplaceMediaInBlocks==='function') window.vmoReplaceMediaInBlocks(wrap.dataset.mediaId, url, ctx.mediaType || 'image');
    window.showToast && showToast('Media replaced!','success');
    };

    /* ========== 🔧 FIX: MISSING MEDIA REPLACEMENT LOGIC ========== */
    
    // Legacy helpers kept for compatibility with templates that create placeholders
    window.replaceMediaElement = function(selector, newUrl, mediaType = 'image') {
        const iframe = document.getElementById('vmo-preview-iframe');
        if (!iframe?.contentDocument) return false;
        
        const doc = iframe.contentDocument;
        const targetElement = doc.querySelector(selector);
        
        if (!targetElement) {
            console.error('[VMO] Target element not found:', selector);
            return false;
        }

        // If flagged as background image container, swap background CSS only
        if (targetElement.dataset && targetElement.dataset.bg === '1') {
            targetElement.style.backgroundImage = `url('${newUrl}')`;
            targetElement.style.backgroundSize = targetElement.style.backgroundSize || 'cover';
            targetElement.style.backgroundPosition = targetElement.style.backgroundPosition || 'center';
            console.log('[VMO] Background image replaced successfully:', selector);
            return true;
        }

        // Otherwise, clear child nodes and inject media element
        while (targetElement.firstChild) targetElement.removeChild(targetElement.firstChild);

        // Create new media element
        let mediaElement;
        if (mediaType === 'video') {
            mediaElement = doc.createElement('video');
            mediaElement.src = newUrl;
            mediaElement.autoplay = true;
            mediaElement.muted = true;
            mediaElement.loop = true;
            mediaElement.playsInline = true;
            mediaElement.style.cssText = 'width:100%;height:100%;object-fit:cover;display:block;';
        } else if (mediaType === 'audio') {
            mediaElement = doc.createElement('audio');
            mediaElement.src = newUrl;
            mediaElement.controls = true;
            mediaElement.style.cssText = 'width:100%;display:block;';
        } else {
            mediaElement = doc.createElement('img');
            mediaElement.src = newUrl;
            mediaElement.alt = 'Generated Media';
            mediaElement.style.cssText = 'width:100%;height:100%;object-fit:cover;display:block;';
        }

        // Insert new media
        targetElement.appendChild(mediaElement);
        
        // Update placeholder styling
        targetElement.style.overflow = 'hidden';
        targetElement.style.position = targetElement.style.position || 'relative';
        
        console.log(`[VMO] Media replaced successfully: ${selector}`, newUrl);
        return true;
    };

    // Create media preview with replace button (calls working modal)
    window.createMediaPreview = function(container, mediaUrl, mediaType = 'image', mediaId = null) {
        if (!container) return;

        const previewHtml = `
            <div class="vmo-media-preview" data-media-id="${mediaId || Date.now()}" style="position: relative; display: inline-block; max-width: 100%;">
                ${mediaType === 'video' ? 
                    `<video src="${mediaUrl}" style="max-width: 100%; height: auto;" controls></video>` :
                    `<img src="${mediaUrl}" alt="Preview" style="max-width: 100%; height: auto;">`
                }
                <div class="vmo-media-overlay" style="position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.7); border-radius: 4px; padding: 5px;">
                    <button class="vmo-replace-media-btn" data-media-id="${mediaId}" data-type="${mediaType}" 
                            style="background: #6366f1; color: white; border: none; border-radius: 3px; padding: 4px 8px; font-size: 12px; cursor: pointer;">
                        Replace
                    </button>
                </div>
            </div>
        `;

        if (typeof container === 'string') {
            document.querySelector(container).innerHTML = previewHtml;
        } else {
            container.innerHTML = previewHtml;
        }

        // Bind replace button
        const replaceBtn = container.querySelector('.vmo-replace-media-btn');
        if (replaceBtn) {
            replaceBtn.addEventListener('click', function() {
                const mediaId = this.dataset.mediaId;
                const mediaType = this.dataset.type;
                const selector = `[data-media-id="${mediaId}"]`;
                if (window.openReplaceMediaModal) {
                    window.openReplaceMediaModal(selector, mediaType);
                } else if (window.vmoOpenMediaPicker) {
                    window.vmoOpenMediaPicker({ iframeId:'vmo-preview-iframe', selector, type: mediaType });
                }
            });
        }

        console.log('[VMO] Media preview created with replace functionality');
    };

    // 🔧 FIX: Enhanced media insertion with visual feedback
    window.insertMediaWithPreview = function(sectionIndex, mediaType, description) {
        const normalizedType = mediaType === 'video' ? 'video' : (mediaType === 'audio' ? 'audio' : 'image');
        const mediaId = `media_${Date.now()}`;
        const escapedPrompt = String(description || '').replace(/[&<>"']/g, function(match) {
            return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[match];
        });
        const placeholder = `<div class="vmo-media-placeholder" data-media-id="${mediaId}" data-type="${normalizedType}" data-vmo-generate="true" data-vmo-prompt="${escapedPrompt}" style="width: 100%; height: 300px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 8px; margin: 20px 0;">
            <span style="color: #666; font-size: 14px;">Generating ${normalizedType}...</span>
        </div>`;

        if (window.vmoState?.blocks?.[sectionIndex]) {
            window.vmoState.blocks[sectionIndex].html += placeholder;
            if (window.renderBlocks) window.renderBlocks();
        }

        if (typeof window.vmoCreateMediaReplacementJob !== 'function') {
            window.showToast('Queued media generation is not ready yet. Please try again after the builder finishes loading.', 'error');
            return;
        }

        window.vmoMediaModalContext = {
            mode: 'replace',
            selector: `[data-media-id="${mediaId}"]`,
            mediaId,
            mediaType: normalizedType,
            slot_id: mediaId,
            placement_role: normalizedType === 'video' ? 'section_video' : (normalizedType === 'audio' ? 'section_audio' : 'section_image'),
            section_id: String(sectionIndex),
            source: 'insert_media_with_preview'
        };

        window.showToast('Media job queued...', 'info', true, true);
        window.vmoCreateMediaReplacementJob({
            replacementType: normalizedType === 'video' ? 'ai_video' : (normalizedType === 'audio' ? 'ai_audio' : 'ai_image'),
            mediaType: normalizedType,
            prompt: description,
            source: 'insert-media'
        }).finally(function() {
            if (typeof window.hideToast === 'function') window.hideToast(true);
        });
    };

    // Overlay injection handled centrally in vmo-theme.js

    // 🔧 FIX: Initialize media system on document ready
    $(document).ready(function() {
        // Bind global media insertion buttons
        $(document).on('click', '[data-media-insert]', function() {
            const mediaType = $(this).data('media-insert') || 'image';
            const description = prompt(`Enter description for the ${mediaType}:`);
            if (description?.trim()) {
                window.insertMediaWithPreview(0, mediaType, description.trim());
            }
        });

        console.log('[VMO] Media system loaded with replacement and preview functionality');
    });

    /*
     * LEGACY REPLACE IMAGE HANDLER (Optional) 
     * If you have existing .vmo-replace-img-btn triggers or older logic,
     * you can adapt them to use vmoOpenMediaModal({ mode: 'replace', ... }).
     */

})(jQuery);