(function($){

function isShowcasePlaceholderActive() {
    if (typeof window.vmoIsShowcasePreviewActive === 'function') {
        return !!window.vmoIsShowcasePreviewActive();
    }

    const iframe = document.getElementById('vmo-preview-iframe');
    if (!iframe) return false;
    if (iframe.dataset && iframe.dataset.vmoPreviewMode === 'showcase-placeholder') return true;

    try {
        return !!iframe.contentDocument?.getElementById('vmo-demo-showcase');
    } catch (_) {
        return false;
    }
}

function getPlaceholderPublishMessage() {
    return 'There is no real website in the builder yet. Generate a website before publishing.';
}

// Remove overlay buttons before publishing
function stripReplaceOverlays(html) {
    const input = String(html || '');
    if (!input) return '';

    if (typeof window.vmoStripEditorOnlyMediaOverlays === 'function') {
        return window.vmoStripEditorOnlyMediaOverlays(input);
    }

    return input
        .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(html) {
    const input = String(html || '');
    if (!input) return '';

    if (typeof window.vmoSanitizeGeneratedHtml === 'function') {
        return window.vmoSanitizeGeneratedHtml(input);
    }

    return 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 getCurrentProjectHtml() {
    let html = '';

    if (isShowcasePlaceholderActive()) {
        return '';
    }

    if (window.vmoState && window.vmoState.blocks && window.vmoState.blocks.length) {
        // Combine all block HTML, but strip overlays!
        html = sanitizeGeneratedHtml(window.vmoState.blocks.map(b => stripReplaceOverlays(b.html)).join('\n'));
    } else {
        html = sanitizeGeneratedHtml(stripReplaceOverlays(window.lastContent || ''));
    }

    if (typeof window.vmoShouldTreatAsRealContent === 'function' && !window.vmoShouldTreatAsRealContent(html, window.vmoState)) {
        return '';
    }

    return html;
}

function getPublishCost() {
    const currentPlan = (typeof vmo_ajax !== 'undefined' ? vmo_ajax.current_plan : '') || 'free';
    if (['starter', 'pro', 'elite'].includes(currentPlan)) return 500;
    if (currentPlan === 'topup') return 550;
    return 625;
}

function wrapContentForPublish(html) {
    html = sanitizeGeneratedHtml(html);
    const criticalCSS = `
        <link href="https://fonts.googleapis.com/css?family=Inter:400,700&display=swap" rel="stylesheet">
        <style>
            html { scroll-behavior: smooth; }
            body { margin: 0; }
            .vmo-root {
                position: relative;
                overflow-x: clip;
            }
            @supports not (overflow: clip) {
                .vmo-root { overflow-x: hidden; }
            }
        </style>
    `;
    if (html.trim().toLowerCase().startsWith('<!doctype') || html.trim().toLowerCase().startsWith('<html')) {
        return html;
    }
    return `${criticalCSS}<div class="vmo-root vmo-motion-scope" data-vmo-motion-scope="generated-site">${html}</div>`;
}

function renderBuilderPreviewFromHtml(html) {
    const iframeEl = document.getElementById('vmo-preview-iframe');
    const sourceHtml = sanitizeGeneratedHtml(stripReplaceOverlays(html || window.lastContent || getCurrentProjectHtml()));

    if (!iframeEl || !sourceHtml || !sourceHtml.trim()) {
        return false;
    }

    window.vmoPreviewIsLive = false;
    window.vmoHasContent = true;
    window.lastContent = sourceHtml;
    iframeEl.removeAttribute('src');
    if (iframeEl.dataset) {
        delete iframeEl.dataset.vmoPreviewMode;
        delete iframeEl.dataset.vmoShowcaseRecoveryCount;
        delete iframeEl.dataset.vmoShowcaseMediaState;
    }

    const wrappedHtml = typeof window.wrapIframeContent === 'function'
        ? window.wrapIframeContent(sourceHtml)
        : sourceHtml;

    iframeEl.setAttribute('srcdoc', wrappedHtml);
    iframeEl.addEventListener('load', function once(){
        iframeEl.removeEventListener('load', once);
        if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') {
            setTimeout(window.vmoInjectReplaceButtonsInIframe, 150);
        }
        if (typeof window.makeIframeTextEditable === 'function') {
            setTimeout(function(){ window.makeIframeTextEditable(iframeEl); }, 175);
        }
    });

    return true;
}

function findStandaloneBlockers(html) {
    const input = String(html || '');
    const blockers = [];
    const checks = [
        [/admin-ajax\.php/i, 'admin-ajax.php'],
        [/\/wp-json\//i, 'wp-json'],
        [/wp-content\/plugins/i, 'plugin asset'],
        [/wp-content\/themes/i, 'theme asset'],
        [/wp-includes/i, 'WordPress core asset'],
        [/window\.wp\b|wp\.apiFetch/i, 'WordPress JavaScript'],
        [/<\?php/i, 'PHP markup']
    ];
    checks.forEach(([pattern, label]) => {
        if (pattern.test(input)) blockers.push(label);
    });
    const shortcodePattern = /(^|[\s>])\[(?!generated_image|generated_video)([a-z][a-z0-9_:-]*)(?:\s+[^\]]*)?\](?:\s*\[\/\2\])?/ig;
    let match;
    while ((match = shortcodePattern.exec(input)) !== null) {
        const name = String(match[2] || '').toLowerCase();
        if (name && !name.startsWith('data-') && !name.startsWith('aria-')) {
            blockers.push(`shortcode [${name}]`);
            break;
        }
    }
    return [...new Set(blockers)];
}

function findMediaCompletionBlockers(html) {
    const input = String(html || '');
    const blockers = [];
    const checks = [
        [/data-vmo-internal-fallback|vmo-internal-fallback|vmo-fallback-page|data-vmo-preview-blocked/i, 'internal fallback draft'],
        [/data-vmo-generate\s*=|\[(generated_image):/i, 'unresolved generated image'],
        [/data-vmo-sora\s*=|\[(generated_video):/i, 'unresolved generated video'],
        [/vmo-media-placeholder/i, 'unresolved media placeholder'],
        [/AI\s+(?:Image|Video)\s+Generating|A professional (?:image|video) will appear here/i, 'visible media placeholder copy']
    ];
    checks.forEach(([pattern, label]) => {
        if (pattern.test(input)) blockers.push(label);
    });
    return [...new Set(blockers)];
}

function getCurrentProjectId() {
    return parseInt(window.currentProjectId || window.vmoCurrentProjectId || 0, 10) || 0;
}

function ensureCanonicalPreviewPublishable(html) {
    if (!getCurrentProjectId()) {
        showToast('Publish requires a canonical VMO project source. Reload or regenerate this website through the VMO website pipeline before publishing.', 'error', false, true);
        return false;
    }

    if (window.vmoPreviewGateLocked === true) {
        showToast('This website is still locked by final QA or media generation. Publish is blocked until the canonical preview gate clears.', 'error', false, true);
        return false;
    }

    const blockers = findMediaCompletionBlockers(html);
    if (!blockers.length) return true;
    showToast(`This site still has unresolved generation work: ${blockers.join(', ')}. VMO must finish this before publish/export.`, 'error', false, true);
    return false;
}

function ensureStandalonePublishable(html) {
    const blockers = findStandaloneBlockers(html);
    if (!blockers.length) return true;
    showToast(`This site still has WordPress-only runtime dependencies: ${blockers.join(', ')}. VMO must resolve those before publish/export.`, 'error', false, true);
    return false;
}

function inferBusinessName() {
    try {
        const c = window.vmoConsultation;
        const ex = c && c.consultation_data && c.consultation_data.extracted_information;
        const fromConsultation = ex && (ex.businessName || ex.business_name);
        return fromConsultation || window.currentProjectTitle || window.vmoLivePageTitle || 'My Website';
    } catch(_e) {
        return window.currentProjectTitle || window.vmoLivePageTitle || 'My Website';
    }
}

function inferDomainLabel() {
    try {
        const c = window.vmoConsultation;
        const ex = c && c.consultation_data && c.consultation_data.extracted_information;
        let domain = ex && ex.domain;
        if (!domain || typeof domain !== 'string') return '';
        domain = domain.trim();
        domain = domain.replace(/^https?:\/\//i, '').replace(/^www\./i, '');
        domain = domain.split('/')[0];
        const parts = domain.split('.').filter(Boolean);
        return parts.length ? parts[0] : '';
    } catch(_e) {
        return '';
    }
}

function slugify(input) {
    const raw = (input || '').toString().trim().toLowerCase();
    // Convert common separators to dashes
    return raw
        .replace(/^https?:\/\//i, '')
        .replace(/^www\./i, '')
        .replace(/\s+/g, '-')
        .replace(/[^a-z0-9\-]+/g, '-')
        .replace(/\-\-+/g, '-')
        .replace(/^\-+|\-+$/g, '');
}

function buildPublishToast(defaultTitle) {
    const nameSlug = slugify(defaultTitle);
    const domainLabel = inferDomainLabel();
    const domainSlug = domainLabel ? slugify(domainLabel) : '';
    const origin = window.location.origin;
    const previewSlug = nameSlug || domainSlug || 'my-website';

    const domainOption = domainSlug
        ? `<label style="display:block;margin:6px 0;">
                <input type="radio" name="vmo_slug_choice" value="domain" />
                Use domain (${domainLabel}): <code style="color:#0ea5e9">${domainSlug}</code>
           </label>`
        : '';

    return `
        <div style="min-width:320px;max-width:520px;">
            <div style="font-weight:700;margin-bottom:8px;">Publish Website</div>
            <div style="font-size:12px;opacity:.9;margin-bottom:10px;">Choose your website name and the URL extension (slug) for the page.</div>

            <div style="margin:10px 0;">
                <label style="display:block;font-size:12px;margin-bottom:6px;">Website name</label>
                <input id="vmo-publish-title" value="${String(defaultTitle).replace(/"/g, '&quot;')}" style="width:100%;padding:10px;border-radius:8px;border:1px solid rgba(255,255,255,.2);background:rgba(0,0,0,.25);color:#fff;" />
            </div>

            <div style="margin:10px 0;">
                <div style="font-size:12px;margin-bottom:6px;">Website address extension</div>
                <label style="display:block;margin:6px 0;">
                    <input type="radio" name="vmo_slug_choice" value="name" checked />
                    Use business name: <code style="color:#22c55e">${nameSlug || 'my-website'}</code>
                </label>
                ${domainOption}
                <label style="display:block;margin:6px 0;">
                    <input type="radio" name="vmo_slug_choice" value="custom" />
                    Custom: <input id="vmo-publish-slug-custom" placeholder="e.g. ${previewSlug}" style="width:180px;margin-left:6px;padding:6px;border-radius:6px;border:1px solid rgba(255,255,255,.2);background:rgba(0,0,0,.25);color:#fff;" />
                </label>
                <div style="font-size:12px;opacity:.85;margin-top:8px;">Preview: <span id="vmo-publish-url-preview" style="color:#00e2ff;">${origin}/${previewSlug}/</span></div>
            </div>

            <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:12px;">
                <button id="vmo-publish-cancel" style="background:#475569;color:#fff;border:none;padding:10px 14px;border-radius:8px;cursor:pointer;">Cancel</button>
                <button id="vmo-publish-confirm" style="background:#22c55e;color:#052e16;border:none;padding:10px 14px;border-radius:8px;font-weight:700;cursor:pointer;">Publish</button>
            </div>
        </div>
    `;
}

function resolveChosenSlug() {
    const choice = $('input[name="vmo_slug_choice"]:checked').val() || 'name';
    const title = ($('#vmo-publish-title').val() || '').toString().trim();
    const nameSlug = slugify(title);
    const domainSlug = slugify(inferDomainLabel());
    const custom = slugify($('#vmo-publish-slug-custom').val());

    if (choice === 'domain' && domainSlug) return { title, slug: domainSlug };
    if (choice === 'custom' && custom) return { title, slug: custom };
    return { title, slug: nameSlug };
}

function buildPublishingToast(title, slug) {
    const origin = window.location.origin;
    const safeTitle = String(title || '').replace(/"/g, '&quot;');
    const safeSlug = String(slug || '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return `
        <div style="min-width:320px;max-width:520px;">
            <div style="font-weight:700;margin-bottom:8px;">Publishing…</div>
            <div style="font-size:12px;opacity:.9;margin-bottom:10px;">
                "${safeTitle}" → <span style="color:#00e2ff;">${origin}/${safeSlug}/</span>
            </div>
            <div style="height:8px;background:rgba(255,255,255,.15);border-radius:999px;overflow:hidden;">
                <div style="height:100%;width:35%;background:linear-gradient(90deg,#22c55e,#00e2ff);animation:vmoPublishBar 1.1s ease-in-out infinite;"></div>
            </div>
            <style>
                @keyframes vmoPublishBar {
                    0% { transform: translateX(-60%); }
                    50% { transform: translateX(80%); }
                    100% { transform: translateX(180%); }
                }
            </style>
            <div style="font-size:12px;opacity:.85;margin-top:10px;">Please wait…</div>
        </div>
    `;
}

// Update UI to reflect published state
function setPublishedState(isPublished, pageId, permalink, title) {
    const $btn = $('#vmo-publish-btn');
    const $updateBtn = $('#vmo-update-live-btn');
    
    if (isPublished) {
        $btn.attr('data-published', 'true')
            .html('🔴 Unpublish')
            .css({
                'background': 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                'border-color': '#ef4444'
            });
        $updateBtn.show();
        window.currentLivePageId = pageId;
        window.vmoLivePermalink = permalink;
        window.vmoLivePageTitle = title;
        window.vmoPreviewIsLive = false;
    } else {
        $btn.attr('data-published', 'false')
            .html('✅ Publish')
            .css({
                'background': '',
                'border-color': ''
            });
        $updateBtn.hide();
        window.currentLivePageId = null;
        window.vmoLivePermalink = null;
        window.vmoPreviewIsLive = false;
    }
}

// Check initial state on load
function checkInitialPublishState() {
    if (window.currentLivePageId && parseInt(window.currentLivePageId) > 0) {
        setPublishedState(true, window.currentLivePageId, window.vmoLivePermalink, window.vmoLivePageTitle);
    }
}

// === Publish/Unpublish Toggle Button ===
$('#vmo-publish-btn').off('click').on('click', function () {
    if (typeof vmo_ajax === 'undefined') {
        showToast('System error: AJAX not initialized. Please refresh the page.', 'error');
        return;
    }
    
    const isPublished = $(this).attr('data-published') === 'true';
    
    if (isPublished) {
        // === UNPUBLISH ===
        if (!confirm('Take this website offline? It will no longer be accessible to visitors.')) return;
        
        showToast('Unpublishing...', 'info');
        
        $.post(vmo_ajax.ajaxurl, {
            action: 'vmo_unpublish_website',
            security: vmo_ajax.nonce,
            page_id: window.currentLivePageId
        }, function(res) {
            if (res.success) {
                setPublishedState(false);
                showToast('Website unpublished. It\'s now offline and only visible in the builder.', 'success');
                
                // Switch preview back to srcdoc mode
                const iframeEl = document.getElementById('vmo-preview-iframe');
                if (iframeEl && window.lastContent) {
                    const wrapped = wrapContentForPublish(getCurrentProjectHtml());
                    if (typeof window.wrapIframeContent === 'function') {
                        iframeEl.setAttribute('srcdoc', window.wrapIframeContent(wrapped));
                    } else {
                        iframeEl.setAttribute('srcdoc', wrapped);
                    }
                }
            } else {
                showToast('Failed to unpublish: ' + (res.data?.message || 'Unknown error'), 'error');
            }
        }).fail(function() {
            showToast('Unpublish failed. Please try again.', 'error');
        });
        
    } else {
        // === PUBLISH ===
        if (isShowcasePlaceholderActive()) {
            showToast(getPlaceholderPublishMessage(), 'warning');
            return;
        }

        const currentBalance = parseInt(vmo_ajax.token_balance) || 0;
        const publishCost = getPublishCost();
        
        if (currentBalance < publishCost) {
            showToast(`Insufficient balance for publishing. Need ${publishCost}, have ${currentBalance}. Consider upgrading your plan.`, 'error');
            return;
        }
        
        // Show toast to pick website name + URL extension (slug)
        const defaultTitle = inferBusinessName();
        showToast(buildPublishToast(defaultTitle), 'info', false, true);

        // Live preview of URL as user types/selects
        $(document).off('input.vmoPublish change.vmoPublish', '#vmo-publish-title, #vmo-publish-slug-custom, input[name="vmo_slug_choice"]');
        $(document).on('input.vmoPublish change.vmoPublish', '#vmo-publish-title, #vmo-publish-slug-custom, input[name="vmo_slug_choice"]', function(){
            const { slug } = resolveChosenSlug();
            const origin = window.location.origin;
            const s = slug || 'my-website';
            $('#vmo-publish-url-preview').text(`${origin}/${s}/`);
        });

        $(document).off('click.vmoPublish', '#vmo-publish-cancel');
        $(document).on('click.vmoPublish', '#vmo-publish-cancel', function(){
            hideToast(true);
            $(document).off('input.vmoPublish change.vmoPublish click.vmoPublish');
        });

        $(document).off('click.vmoPublish', '#vmo-publish-confirm');
        $(document).on('click.vmoPublish', '#vmo-publish-confirm', function(){
            const resolved = resolveChosenSlug();
            const title = resolved.title;
            const slug = resolved.slug;
            if (!title) {
                showToast('Website name is required to publish.', 'error');
                return;
            }
            if (!slug) {
                showToast('Please choose a valid URL extension.', 'error');
                return;
            }

            let latestHtml = getCurrentProjectHtml();
            if (!latestHtml || latestHtml.trim().length < 50) {
                return showToast(isShowcasePlaceholderActive()
                    ? getPlaceholderPublishMessage()
                    : 'No content to publish. Please create your website first.', 'error');
            }

            window.lastContent = latestHtml;
            const publishContent = wrapContentForPublish(latestHtml);
            if (!ensureCanonicalPreviewPublishable(publishContent)) return;
            if (!ensureStandalonePublishable(publishContent)) return;

            // Sticky toast that stays open while publishing + shows spinner/progress
            showToast(buildPublishingToast(title, slug), 'info', true, true);

            // Save undo state
            $.post(vmo_ajax.ajaxurl, {
                action: 'vmo_save_undo',
                security: vmo_ajax.nonce,
                html: publishContent
            });

            if (typeof renderBlocks === 'function') renderBlocks();

            $.post(vmo_ajax.ajaxurl, {
                action: 'vmo_save_generated_page',
                security: vmo_ajax.nonce,
                title: title,
                content: publishContent,
                type: 'page',
                status: 'publish',
                slug: slug,
                project_id: getCurrentProjectId()
            }, function (res) {
            if (res.success) {
                // Deduct publishing balance
                vmo_ajax.token_balance = Math.max(0, parseInt(vmo_ajax.token_balance) - publishCost);
                $('#vmo-token-balance').text('Balance: ' + vmo_ajax.token_balance);
                
                window.isUnsaved = false;
                const pageId = res.data?.id;
                const link = res.data?.link || `${window.location.origin}/?p=${pageId}`;
                
                // Update to published state
                setPublishedState(true, pageId, link, title);
                
                // Keep the builder preview on VMO-generated HTML. The live URL is stored for View In Browser.
                try {
                    renderBuilderPreviewFromHtml(latestHtml || publishContent);
                } catch(_e){}
                
                showToast(`
                    <strong>🎉 Website Published!</strong><br><br>
                    "${title}" is now live.<br>
                    Cost: ${publishCost} tokens<br><br>
                    <button id="vmo-view-now-btn" style="background:#00e2ff;color:#001a2e;border:none;padding:8px 16px;border-radius:4px;margin:5px;cursor:pointer;">View now</button>
                    <button id="vmo-view-later-btn" style="background:#666;color:#fff;border:none;padding:8px 16px;border-radius:4px;margin:5px;cursor:pointer;">Close</button>
                `, 'success', false, true);
                
                $(document).off('click', '#vmo-view-now-btn').on('click', '#vmo-view-now-btn', function () { 
                    window.open(link, '_blank'); 
                    hideToast(true); 
                });
                $(document).off('click', '#vmo-view-later-btn').on('click', '#vmo-view-later-btn', function () { 
                    hideToast(true); 
                });
            } else {
                    showToast(`Failed to publish: ${res.data?.message || 'Unknown error'}`, 'error', false, true);
            }
            }).fail(function(xhr, status, error) {
                console.error('Publish AJAX Error:', xhr.status, xhr.responseText);
                showToast(`Publish failed: ${xhr.status} ${error}. Please try again.`, 'error', false, true);
            }).always(function(){
                // Keep the publish toast handlers scoped
                $(document).off('input.vmoPublish change.vmoPublish click.vmoPublish');
            });
        });
    }
});

// === Update Live Button (push changes without unpublishing) ===
$('#vmo-update-live-btn').off('click').on('click', function () {
    if (typeof vmo_ajax === 'undefined') {
        showToast('System error: AJAX not initialized.', 'error');
        return;
    }

    if (isShowcasePlaceholderActive()) {
        showToast(getPlaceholderPublishMessage(), 'warning');
        return;
    }
    
    const pageId = window.currentLivePageId;
    if (!pageId) {
        showToast('No live page to update. Please publish first.', 'error');
        return;
    }
    
    let latestHtml = getCurrentProjectHtml();
    if (!latestHtml || latestHtml.trim().length < 50) {
        return showToast('No content to update.', 'error');
    }
    
    const publishContent = wrapContentForPublish(latestHtml);
    if (!ensureCanonicalPreviewPublishable(publishContent)) return;
    if (!ensureStandalonePublishable(publishContent)) return;
    const title = window.vmoLivePageTitle || window.currentProjectTitle || 'Updated Page';
    
    showToast('Updating live website...', 'info');
    
    // Save undo state before updating
    $.post(vmo_ajax.ajaxurl, {
        action: 'vmo_save_undo', 
        security: vmo_ajax.nonce, 
        html: publishContent
    });
    
    $.post(vmo_ajax.ajaxurl, {
        action: 'vmo_save_generated_page', 
        security: vmo_ajax.nonce,
        title: title, 
        content: publishContent, 
        type: 'page', 
        status: 'publish',
        page_id: pageId,
        project_id: getCurrentProjectId()
    }, function (res) {
        if (res.success) {
            window.isUnsaved = false;
            const link = res.data?.link || window.vmoLivePermalink;
            window.vmoLivePermalink = link || window.vmoLivePermalink || '';
            window.vmoPreviewIsLive = false;
            
            // Refresh the builder preview using srcdoc so WordPress chrome never appears in the iframe.
            try {
                renderBuilderPreviewFromHtml(latestHtml || publishContent);
            } catch(_e){}
            
            showToast('✅ Live website updated! Your changes are now visible to visitors.', 'success');
        } else {
            showToast(`Update failed: ${res.data?.message || 'Unknown error'}`, 'error');
        }
    }).fail(function(xhr) {
        console.error('Update Live Error:', xhr.status, xhr.responseText);
        showToast('Update failed. Please try again.', 'error');
    });
});

// Initialize on document ready
$(document).ready(function() {
    checkInitialPublishState();
});

// Expose for external use
window.vmoSetPublishedState = setPublishedState;
window.vmoCheckPublishState = checkInitialPublishState;

})(jQuery);