/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /assets/js/amai-seo-meta-box.js
   Description: SEO meta box JS — char counts, advanced toggle, Fix It AJAX, rescan, sidebar widget, orchestrator
   Last Edited: 2026-05-03
   ================================================== */

(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {

        initCharCounts();
        initAdvancedToggle();
        initFixButtons();
        initTipButtons();
        initRescan();
        initSidebarWidget();
        initOrchestrator();
        initTagWatcher();
        initSnippetModal();
    initFacebookModal();
        initFeaturedImagePicker();
        maybeAutoOptimize();

        // --------------------------------------------------
        // Character count indicators
        // --------------------------------------------------
        function initCharCounts() {
            var titleInput = document.getElementById('amai_meta_title');
            var titleCount = document.getElementById('amai-title-count');
            var titleBar   = document.getElementById('amai-title-bar');
            var descInput  = document.getElementById('amai_meta_description');
            var descCount  = document.getElementById('amai-desc-count');
            var descBar    = document.getElementById('amai-desc-bar');

            if (titleInput) {
                titleInput.addEventListener('input', function () {
                    updateCharCount(titleInput, titleCount, titleBar, 50, 60);
                });
                updateCharCount(titleInput, titleCount, titleBar, 50, 60);
            }

            if (descInput) {
                descInput.addEventListener('input', function () {
                    updateCharCount(descInput, descCount, descBar, 150, 160);
                });
                updateCharCount(descInput, descCount, descBar, 150, 160);
            }
        }

        function updateCharCount(input, counter, bar, min, max) {
            var len = input.value.length;
            if (counter) {
                counter.textContent = len + '/' + max;
                counter.style.color = (len >= min && len <= max) ? '#16A34A' : (len > 0 ? '#D97706' : '#A8A29E');
            }
            if (bar) {
                bar.style.width = Math.min(100, Math.round(len / max * 100)) + '%';
                bar.style.background = (len >= min && len <= max) ? '#16A34A' : '#D97757';
            }
        }

        // --------------------------------------------------
        // Advanced settings toggle
        // --------------------------------------------------
        function initAdvancedToggle() {
            var toggle = document.getElementById('amai-advanced-toggle');
            var panel  = document.getElementById('amai-advanced-panel');
            if (!toggle || !panel) { return; }
            toggle.addEventListener('click', function () {
                var open = panel.style.display !== 'none';
                panel.style.display = open ? 'none' : 'block';
                toggle.textContent  = open ? 'Advanced settings' : 'Hide advanced settings';
            });
        }

        // --------------------------------------------------

        // --------------------------------------------------
        // Auto-save and re-analyze when user removes a tag from the WP tags metabox
        // --------------------------------------------------
        function initTagWatcher() {
            setTimeout(function () {
                // Max-10 tag enforcement on WP Add button
                var addBtn = document.querySelector('#post_tag .tagadd');
                if (addBtn) {
                    addBtn.addEventListener('click', function (e) {
                        var tagInput2 = document.getElementById('tax-input-post_tag');
                        var current   = tagInput2 ? tagInput2.value.split(',').map(function(t){return t.trim();}).filter(Boolean) : [];
                        if (current.length >= 10) {
                            e.preventDefault();
                            e.stopImmediatePropagation();
                            var notice = document.getElementById('amai-tag-max-notice');
                            if (!notice) {
                                notice = document.createElement('p');
                                notice.id = 'amai-tag-max-notice';
                                notice.style.cssText = 'color:#b91c1c;font-size:12px;margin:4px 0 0;';
                                notice.textContent = 'Maximum 10 tags allowed. Remove a tag before adding another.';
                                var howto = document.getElementById('new-tag-post_tag-desc');
                                if (howto) { howto.parentNode.insertBefore(notice, howto.nextSibling); }
                            }
                            setTimeout(function () { var n = document.getElementById('amai-tag-max-notice'); if (n) { n.remove(); } }, 3000);
                        }
                    }, true);
                }
            }, 1000);
        }

        function initFixButtons() {
            var sidebar = document.getElementById('amai-seo-sidebar-widget');
            if (sidebar) {
                sidebar.addEventListener('click', function (e) {
                    var btn = e.target.closest('.amai-seo-fix-btn');
                    if (!btn) { return; }
                    handleFix(btn);
                });
                sidebar.addEventListener('click', function (e) {
                    var sBtn = e.target.closest('.amai-seo-suggest-links-btn');
                    if (!sBtn) { return; }
                    handleSuggestLinks(sBtn);
                });
            }
            var box = document.getElementById('amai-seo-box');
            if (!box) { return; }
            box.addEventListener('click', function (e) {
                var btn = e.target.closest('.amai-seo-fix-btn');
                if (!btn) { return; }
                handleFix(btn);
            });
            box.addEventListener('click', function (e) {
                var sBtn = e.target.closest('.amai-seo-suggest-links-btn');
                if (!sBtn) { return; }
                handleSuggestLinks(sBtn);
            });
        }

        function handleFix(btn) {
            var field      = btn.getAttribute('data-field') || '';
            var issueIndex = btn.getAttribute('data-issue-index') || '';
            var postId     = window.amaiSeo ? window.amaiSeo.postId : 0;
            var ajaxurl    = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce      = window.amaiSeo ? window.amaiSeo.nonce : '';
            var fixMode    = btn.getAttribute('data-fix-mode') || '';

            // Internal links injection uses its own AJAX action
            if (field === 'internal_links') {
                handleInjectInternalLinks(btn);
                return;
            }
            // Outbound links injection uses its own AJAX action
            if (field === 'outbound_links') {
                handleInjectLinks(btn);
                return;
            }
                        if (!field || issueIndex === '' || !postId) { return; }

            var originalText = btn.textContent;
            btn.disabled    = true;
            btn.textContent = 'Fixing...';

            var body = new URLSearchParams();
            body.append('action',     'amai_seo_fix_it');
            body.append('nonce',      nonce);
            body.append('post_id',    postId);
            body.append('field',      field);
            body.append('issue_index', issueIndex);
            body.append('fix_mode',     fixMode);

            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled    = false;
                btn.textContent = originalText;
                if (!data.success) {
                    showError(btn, data.data && data.data.message ? data.data.message : 'Something went wrong.');
                    return;
                }
                var respMode    = (data.data && data.data.mode)    ? data.data.mode    : '';
                var respPatches = (data.data && data.data.patches) ? data.data.patches : [];
                if (respMode === 'paragraphs' && respPatches.length > 0) {
                    applyParagraphPatches(respPatches);
                    var postId2  = window.amaiSeo ? window.amaiSeo.postId  : 0;
                    var nonce2   = window.amaiSeo ? window.amaiSeo.nonce   : '';
                    var ajaxurl2 = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
                    saveTinyMceContent(postId2, nonce2, ajaxurl2, function () {
                        var rescanBtn = document.getElementById('amai-rescan-btn');
                        if (rescanBtn) { setTimeout(function () { rescanBtn.click(); }, 800); }
                    });
                } else {
                    showAiResult(field, (data.data && data.data.value) ? data.data.value : '', btn);
                }
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = originalText;
                showError(btn, 'Request failed. Please try again.');
            });
        }

        // --------------------------------------------------
        // Show AI result with Accept / Dismiss inline
        // --------------------------------------------------
        function showAiResult(field, value, triggerBtn) {
            var existing = document.getElementById('amai-ai-result-' + field);
            if (existing) { existing.remove(); }

            var wrap = document.createElement('div');
            wrap.id = 'amai-ai-result-' + field;
            wrap.style.cssText = 'margin-top:8px;padding:10px;background:#FFF8F5;border:1.5px solid #F5C9B8;border-radius:8px;font-size:12.5px;line-height:1.5;color:#1C1917;';

            var text = document.createElement('div');
            text.style.marginBottom = '8px';
            if (field === 'post_content' || field === 'post_first_para') {
                text.innerHTML = value;
            } else {
                text.textContent = value;
            }
            wrap.appendChild(text);

            var actions = document.createElement('div');
            actions.style.cssText = 'display:flex;gap:8px;';

            var acceptBtn = document.createElement('button');
            acceptBtn.type = 'button';
            acceptBtn.textContent = 'Accept';
            acceptBtn.style.cssText = 'padding:4px 12px;background:#D97757;color:#fff;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;';

            var dismissBtn = document.createElement('button');
            dismissBtn.type = 'button';
            dismissBtn.textContent = 'Dismiss';
            dismissBtn.style.cssText = 'padding:4px 12px;background:transparent;color:#78716C;border:1.5px solid #E7DDD5;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;';

            actions.appendChild(acceptBtn);
            actions.appendChild(dismissBtn);
            wrap.appendChild(actions);

            triggerBtn.parentNode.insertAdjacentElement('afterend', wrap);

            acceptBtn.addEventListener('click', function () {
                if (field !== 'post_tags') { applyToField(field, value); }
                wrap.remove();
                if (field === 'post_title' || field === 'post_content' || field === 'post_slug' || field === 'post_first_para') {
                    var rescanBtn = document.getElementById('amai-rescan-btn');
                    if (field === 'post_content' || field === 'post_first_para') {
                        // Save to DB first so rescan reads the updated content
                        var savePostId = window.amaiSeo ? window.amaiSeo.postId : 0;
                        var saveNonce  = window.amaiSeo ? window.amaiSeo.nonce  : '';
                        var saveAjax   = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
                        var saveVal    = field === 'post_first_para' ? (function () {
                            if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                                return tinyMCE.activeEditor.getContent();
                            }
                            var ta = document.getElementById('content');
                            return ta ? ta.value : value;
                        })() : value;
                        var sb = new URLSearchParams();
                        sb.append('action',  'amai_seo_save_field');
                        sb.append('nonce',   saveNonce);
                        sb.append('post_id', savePostId);
                        sb.append('field',   field === 'post_first_para' ? 'post_content' : field);
                        sb.append('value',   saveVal);
                        fetch(saveAjax, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: sb.toString(),
                        })
                        .then(function () {
                            if (rescanBtn) { setTimeout(function () { rescanBtn.click(); }, 800); }
                        })
                        .catch(function () {
                            if (rescanBtn) { setTimeout(function () { rescanBtn.click(); }, 800); }
                        });
                    } else {
                        var rescanDelay = 600;
                        if (rescanBtn) { setTimeout(function () { rescanBtn.click(); }, rescanDelay); }
                    }
                } else if (field === 'internal_links') {
                    // Orchestrator: inject internal links server-side and rescan
                    var intBody = new URLSearchParams();
                    intBody.append('action',  'amai_seo_inject_internal_links');
                    intBody.append('nonce',   nonce);
                    intBody.append('post_id', postId);
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: intBody.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function () { scheduleNextPass(passIndex, status, btn, field, succeeded); })
                    .catch(function () { scheduleNextPass(passIndex, status, btn, field, succeeded); });
                } else if (field === 'outbound_links') {
                    // Orchestrator: inject links without page reload
                    var injectBody = new URLSearchParams();
                    injectBody.append('action',  'amai_seo_inject_links');
                    injectBody.append('nonce',   nonce);
                    injectBody.append('post_id', postId);
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: injectBody.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function () { scheduleNextPass(passIndex, status, btn, field, succeeded); })
                    .catch(function () { scheduleNextPass(passIndex, status, btn, field, succeeded); });
                } else if (field === 'post_content_prepend') {
                    // Orchestrator: prepend H2 to TinyMCE content and save
                    if (value && typeof tinymce !== 'undefined' && tinymce.get('content')) {
                        var ed = tinymce.get('content');
                        ed.setContent(value + '\n' + ed.getContent());
                        saveTinyMceContent(postId, nonce, ajaxurl, function () {
                            scheduleNextPass(passIndex, status, btn, field, succeeded);
                        });
                    } else {
                        scheduleNextPass(passIndex, status, btn, field, succeeded);
                    }
                } else if (field === 'post_tags') {
                    var tagSaveBody = new URLSearchParams();
                    tagSaveBody.append('action',  'amai_seo_save_field');
                    tagSaveBody.append('nonce',   window.amaiSeo ? window.amaiSeo.nonce : '');
                    tagSaveBody.append('post_id', window.amaiSeo ? window.amaiSeo.postId : 0);
                    tagSaveBody.append('field',   'post_tags');
                    tagSaveBody.append('value',   value);
                    fetch(window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: tagSaveBody.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function (tagData) {
                        if (tagData.success) {
                            var tagInput = document.getElementById('tax-input-post_tag');
                            if (tagInput) { tagInput.value = value.split(',').map(function(t){return t.trim();}).filter(Boolean).join(','); }
                            try { if (window.tagBox) { window.tagBox.flushTags(document.getElementById('post_tag'), false, 1); } } catch (e) {}
                            try { localStorage.removeItem('wp-autosave-' + (window.amaiSeo ? window.amaiSeo.postId : '')); } catch (e) {}
                            setTimeout(function () { triggerReanalyze(); }, 500);
                        }
                    })
                    .catch(function () {});
                } else {
                    var postId  = window.amaiSeo ? window.amaiSeo.postId : 0;
                    var nonce   = window.amaiSeo ? window.amaiSeo.nonce : '';
                    var saveBody = new URLSearchParams();
                    saveBody.append('action',   'amai_seo_save_field');
                    saveBody.append('nonce',    nonce);
                    saveBody.append('post_id',  postId);
                    saveBody.append('field',    field);
                    saveBody.append('value',    value);
                    fetch(window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: saveBody.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        if (data.success) { renderRescanResult(data.data); }
                    })
                    .catch(function () {});
                }
            });

            dismissBtn.addEventListener('click', function () { wrap.remove(); });
        }

        // --------------------------------------------------
        // Apply accepted value to the correct input
        // --------------------------------------------------
        function applyToField(field, value) {
            if (field === 'post_first_para') {
                if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                    var currentContent = tinyMCE.activeEditor.getContent();
                    var spliced = currentContent.replace(/<p(\b[^>]*)>.*?<\/p>/i, '<p$1>' + value + '</p>');
                    tinyMCE.activeEditor.setContent(spliced);
                } else {
                    var ta = document.getElementById('content');
                    if (ta) {
                        var spliced2 = ta.value.replace(/<p(\b[^>]*)>.*?<\/p>/i, '<p$1>' + value + '</p>');
                        ta.value = spliced2;
                    }
                }
                return;
            }
            if (field === 'post_title') {
                var titleEl = document.getElementById('title');
                if (titleEl) {
                    titleEl.value = value;
                    titleEl.dispatchEvent(new Event('input'));
                }
                return;
            }
            if (field === 'post_content') {
                if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                    tinyMCE.activeEditor.setContent(value);
                } else {
                    var contentEl = document.getElementById('content');
                    if (contentEl) { contentEl.value = value; }
                }
                return;
            }
            if (field === 'post_slug') {
                var slugEl = document.getElementById('post_name');
                if (slugEl) { slugEl.value = value; }
                var slugSpan = document.getElementById('editable-post-name');
                if (slugSpan) { slugSpan.textContent = value; }
                var slugFull = document.getElementById('editable-post-name-full');
                if (slugFull) { slugFull.textContent = value; }
                return;
            }
            var map = {
                'meta_title':       'amai_meta_title',
                'meta_description': 'amai_meta_description',
                'canonical_url':    'amai_canonical_url',
            };
            var inputId = map[field];
            if (!inputId) { return; }
            var input = document.getElementById(inputId);
            if (!input) { return; }
            input.value = value;
            input.dispatchEvent(new Event('input'));
        }

        // --------------------------------------------------
        // How to fix tip buttons (static guidance)
        // --------------------------------------------------
        function initTipButtons() {
            var box = document.getElementById('amai-seo-box');
            if (!box) { return; }
            box.addEventListener('click', function (e) {
                var btn = e.target.closest('.amai-seo-tip-btn');
                if (!btn) { return; }
                var tip = btn.getAttribute('data-tip') || '';
                if (!tip) { return; }
                var existing = document.getElementById('amai-tip-popup');
                if (existing) { existing.remove(); return; }
                var wrap = document.createElement('div');
                wrap.id = 'amai-tip-popup';
                wrap.style.cssText = 'margin-top:6px;padding:9px 12px;background:#F0FDF4;border:1.5px solid #BBF7D0;border-radius:8px;font-size:12px;line-height:1.5;color:#166534;position:relative;';
                var closeBtn = document.createElement('button');
                closeBtn.type = 'button';
                closeBtn.textContent = 'x';
                closeBtn.style.cssText = 'position:absolute;top:6px;right:8px;background:none;border:none;cursor:pointer;font-size:11px;color:#166534;padding:0;';
                closeBtn.addEventListener('click', function () { wrap.remove(); });
                var text = document.createElement('span');
                text.textContent = tip;
                wrap.appendChild(text);
                wrap.appendChild(closeBtn);
                btn.parentNode.insertAdjacentElement('afterend', wrap);
            });
        }

        var SEO_TIP_MAP = {
            'One or more images are missing alt text.': 'Click any image in the editor, then add a description in the Alt Text field in the right sidebar. Alt text helps search engines and screen readers.',
            'No image alt text contains your focus keyword.': 'Edit the alt text on your most relevant image to naturally include your focus keyword. Click the image in the editor to access the Alt Text field.',
        };

        // --------------------------------------------------
        // Re-render scores, badges, and issues after rescan
        // --------------------------------------------------
        function renderRescanResult(data) {
            var scoreSeo  = data.score_seo  || 0;
            var scoreRead = data.score_readability || 0;
            var issues    = data.issues || [];

            var dials = document.querySelectorAll('.amai-seo-score-dial');
            if (dials.length >= 2) {
                updateDial(dials[0], scoreSeo);
                updateDial(dials[1], scoreRead);
            }

            var summary = document.querySelector('.amai-seo-score-summary');
            if (summary) {
                var errors      = issues.filter(function(i) { return i.severity === 'error'; });
                var warnings    = issues.filter(function(i) { return i.severity === 'warning'; });
                var suggestions = issues.filter(function(i) { return i.severity === 'suggestion'; });
                var html = '';
                if (errors.length)      { html += '<span class="amai-seo-badge amai-seo-badge--error">' + errors.length + ' error' + (errors.length !== 1 ? 's' : '') + '</span>'; }
                if (warnings.length)    { html += '<span class="amai-seo-badge amai-seo-badge--warning">' + warnings.length + ' warning' + (warnings.length !== 1 ? 's' : '') + '</span>'; }
                if (suggestions.length) { html += '<span class="amai-seo-badge amai-seo-badge--suggestion">' + suggestions.length + ' suggestion' + (suggestions.length !== 1 ? 's' : '') + '</span>'; }
                if (!errors.length && !warnings.length && !suggestions.length) { html += '<span class="amai-seo-badge amai-seo-badge--perfect">All good</span>'; }
                summary.innerHTML = html;
            }

            var box = document.getElementById('amai-seo-box');
            if (!box) { return; }
            var existing = box.querySelector('.amai-seo-issues');
            if (existing) { existing.remove(); }

            var visibleIssues = issues.filter(function(i) { return i.message !== ''; });
            if (visibleIssues.length === 0) { return; }

            var footer = box.querySelector('.amai-seo-footer');
            var issuesDiv = document.createElement('div');
            issuesDiv.className = 'amai-seo-issues';
            var title = document.createElement('div');
            title.className = 'amai-seo-issues-title';
            title.textContent = 'Issues';
            issuesDiv.appendChild(title);

            visibleIssues.forEach(function(issue) {
                var row = document.createElement('div');
                row.className = 'amai-seo-issue amai-seo-issue--' + issue.severity;
                var dot = document.createElement('span');
                dot.className = 'amai-seo-issue-dot';
                var msg = document.createElement('span');
                msg.className = 'amai-seo-issue-msg';
                msg.textContent = issue.message;
                row.appendChild(dot);
                row.appendChild(msg);
                if (issue.issue_index !== undefined && issue.issue_index !== null && issue.issue_index !== '') {
                    var fixBtn = document.createElement('button');
                    fixBtn.type = 'button';
                    fixBtn.className = 'amai-seo-fix-btn amai-seo-fix-btn--inline';
                    fixBtn.setAttribute('data-field', issue.field);
                    fixBtn.setAttribute('data-issue-index', issue.issue_index !== undefined ? String(issue.issue_index) : '');
                    fixBtn.setAttribute('data-fix-mode', issue.fix_mode || '');
                    fixBtn.textContent = 'Fix';
                    row.appendChild(fixBtn);
                } else if (issue.message === 'No internal links found. Link to at least 2 related posts or pages.' || issue.message === 'Only one internal link found. Add at least one more.') {
                    var sugBtn = document.createElement('button');
                    sugBtn.type = 'button';
                    sugBtn.className = 'amai-seo-suggest-links-btn';
                    sugBtn.textContent = 'Suggest links';
                    row.appendChild(sugBtn);
                } else if (SEO_TIP_MAP[issue.message]) {
                    var tipBtn = document.createElement('button');
                    tipBtn.type = 'button';
                    tipBtn.className = 'amai-seo-tip-btn';
                    tipBtn.setAttribute('data-tip', SEO_TIP_MAP[issue.message]);
                    tipBtn.textContent = 'How to fix';
                    row.appendChild(tipBtn);
                }
                issuesDiv.appendChild(row);
            });

            if (footer) {
                box.insertBefore(issuesDiv, footer);
            } else {
                box.appendChild(issuesDiv);
            }

            updateSidebarWidget(data);
        }

        function updateDial(el, score) {
            el.textContent = score;
            el.className = 'amai-seo-score-dial';
            if (score >= 70)      { el.classList.add('amai-seo-score-dial--good'); }
            else if (score >= 40) { el.classList.add('amai-seo-score-dial--ok'); }
            else                  { el.classList.add('amai-seo-score-dial--poor'); }
        }

        // --------------------------------------------------
        // Re-analyze button
        // --------------------------------------------------
        window.triggerReanalyze = function () {
            var btn    = document.getElementById('amai-rescan-btn');
            var status = document.getElementById('amai-seo-status');
            var box    = document.getElementById('amai-seo-box');
            var postId  = window.amaiSeo ? window.amaiSeo.postId : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce : '';
            if (!postId) { return; }
            if (btn) { btn.disabled = true; btn.textContent = 'Analyzing...'; }
            if (status) { status.textContent = ''; }
            if (box) { box.classList.add('amai-seo-loading'); }
            var body = new URLSearchParams();
            body.append('action',  'amai_seo_rescan');
            body.append('nonce',   nonce);
            body.append('post_id', postId);
            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (btn) { btn.disabled = false; btn.textContent = 'Re-analyze'; }
                if (box) { box.classList.remove('amai-seo-loading'); }
                if (data.success) {
                    renderRescanResult(data.data);
                    if (status) { status.textContent = ''; }
                } else {
                    if (status) { status.textContent = 'Analysis failed. Please try again.'; }
                }
            })
            .catch(function () {
                if (btn) { btn.disabled = false; btn.textContent = 'Re-analyze'; }
                if (box) { box.classList.remove('amai-seo-loading'); }
                if (status) { status.textContent = 'Request failed.'; }
            });
        }

        function initRescan() {
            var btn    = document.getElementById('amai-rescan-btn');
            var status = document.getElementById('amai-seo-status');
            var box    = document.getElementById('amai-seo-box');
            if (!btn) { return; }

            btn.addEventListener('click', function () { triggerReanalyze(); });
        }

        // --------------------------------------------------
        // Sidebar widget - update dials and issue count
        // --------------------------------------------------
        function updateSidebarWidget(data) {
            var dialSeo   = document.getElementById('amai-sw-dial-seo');
            var dialRead  = document.getElementById('amai-sw-dial-read');
            var countEl   = document.getElementById('amai-sw-issue-count');
            var scoreSeo  = data.score_seo  || 0;
            var scoreRead = data.score_readability || 0;
            var issues    = data.issues || [];
            var fixable   = issues.filter(function(i) { return i.fix_prompt && i.fix_prompt !== ''; });

            function setDial(el, score) {
                if (!el) { return; }
                el.textContent = score;
                el.className = 'amai-sw-dial';
                if (score >= 70)      { el.classList.add('amai-sw-dial--good'); }
                else if (score >= 40) { el.classList.add('amai-sw-dial--ok'); }
                else                  { el.classList.add('amai-sw-dial--poor'); }
            }
            setDial(dialSeo,  scoreSeo);
            setDial(dialRead, scoreRead);

            // Update zone labels
            function setZone(scoreVal, wrapId) {
                var wrap = document.querySelector('#' + wrapId);
                if (!wrap) { return; }
                var zone = wrap.closest('.amai-sw-score-wrap');
                if (!zone) { return; }
                var zoneEl = zone.querySelector('.amai-sw-dial-zone');
                if (!zoneEl) { return; }
                zoneEl.className = 'amai-sw-dial-zone';
                if (scoreVal >= 70)      { zoneEl.textContent = 'Good'; zoneEl.classList.add('amai-sw-dial-zone--good'); }
                else if (scoreVal >= 40) { zoneEl.textContent = 'Fair'; zoneEl.classList.add('amai-sw-dial-zone--ok'); }
                else if (scoreVal > 0)   { zoneEl.textContent = 'Needs work'; zoneEl.classList.add('amai-sw-dial-zone--poor'); }
                else                     { zoneEl.textContent = '--'; zoneEl.classList.add('amai-sw-dial-zone--empty'); }
            }
            setZone(scoreSeo, 'amai-sw-dial-seo');
            setZone(scoreRead, 'amai-sw-dial-read');
            var gradeEl = document.getElementById('amai-sw-grade');
            if (gradeEl) {
                var sentence;
                if (scoreSeo === 0 && scoreRead === 0) {
                    sentence = 'Write your post and we\'ll score it.';
                } else if (scoreSeo >= 70 && scoreRead >= 70 && fixable.length === 0) {
                    sentence = 'This post is ready to publish.';
                } else if (scoreSeo >= 70 && scoreRead >= 70) {
                    sentence = 'Almost there - fix ' + fixable.length + ' thing' + (fixable.length !== 1 ? 's' : '') + ' and you\'re good to go.';
                } else if (scoreSeo >= 40 && scoreRead >= 40) {
                    sentence = 'Good start - a few things to clean up.';
                } else {
                    sentence = 'This post needs some work before it\'s ready.';
                }
                gradeEl.textContent = sentence;
            }
            var optimizeBtn = document.getElementById('amai-sw-optimize-btn');
            if (optimizeBtn) {
                optimizeBtn.style.display = 'block';
            }
            if (countEl) {
                countEl.textContent = fixable.length > 0
                    ? fixable.length + ' issue' + (fixable.length !== 1 ? 's' : '') + ' to fix'
                    : 'All good';
            }
        }

        // --------------------------------------------------
        // Sidebar widget init - wire up to rescan results
        // --------------------------------------------------
        function initSidebarWidget() {
            var widget = document.getElementById('amai-seo-sidebar-widget');
            if (!widget) { return; }
        }

        // --------------------------------------------------
        // Auto-optimize orchestrator
        // --------------------------------------------------
        // Priority order: fields fixed first to last when multiple issues exist.
        // Each pass fixes exactly ONE issue then rescans. 5 passes max per run.
        var FIELD_PRIORITY = [
            'meta_title', 'meta_description', 'post_title', 'post_slug',
            'focus_keyword', 'post_first_para', 'post_tags', 'post_content', 'outbound_links', 'internal_links'
        ];
        var SEVERITY_RANK = { 'error': 0, 'warning': 1, 'suggestion': 2 };

        var FIELD_LABELS = {
            'meta_title':       'Fixing content title...',
            'meta_description': 'Fixing Google snippet...',
            'post_slug':        'Fixing URL slug...',
            'post_tags':        'Fixing tags...',
            'post_title':       'Fixing post title...',
            'outbound_links':  'Adding outbound links...',
            'internal_links': 'Adding internal links...',
            'post_content':     'Rewriting content...',
            'post_first_para':  'Fixing first paragraph...',
            'focus_keyword':    'Fixing focus topic...',
        };

        function pickNextIssue(issues, succeeded) {
            var fixable = issues.filter(function(i) { return i.fix_mode && i.fix_mode !== '' && i.issue_index !== undefined && i.issue_index !== null && i.issue_index !== '' && !succeeded.has(i.field); });
            if (fixable.length === 0) { return null; }
            fixable.sort(function(a, b) {
                // Sort by field priority first -- easy/metadata fields before content rewrites
                var priA = FIELD_PRIORITY.indexOf(a.field);
                var priB = FIELD_PRIORITY.indexOf(b.field);
                if (priA === -1) { priA = 99; }
                if (priB === -1) { priB = 99; }
                if (priA !== priB) { return priA - priB; }
                // Same field -- sort by severity
                var sevA = SEVERITY_RANK[a.severity] !== undefined ? SEVERITY_RANK[a.severity] : 9;
                var sevB = SEVERITY_RANK[b.severity] !== undefined ? SEVERITY_RANK[b.severity] : 9;
                return sevA - sevB;
            });
            return fixable[0];
        }

        function initOrchestrator() {
            var btn    = document.getElementById('amai-sw-optimize-btn');
            var status = document.getElementById('amai-sw-status');
            if (!btn) { return; }
            btn.addEventListener('click', function () {
                btn.disabled = true;
                btn.textContent = 'Optimizing...';
                if (status) { status.textContent = 'Starting...'; status.classList.remove('amai-sw-status--warn'); }
                var ep = document.getElementById('amai-sw-publish-prompt'); if (ep) { ep.style.display = 'none'; }
                var hint = document.getElementById('amai-sw-optimize-hint'); if (hint) { hint.style.display = 'none'; }
                runOrchestrator(0, status, btn, new Set());
            });
        }

        function runOrchestrator(passIndex, status, btn, succeeded) {
            if (passIndex >= 5) {
                finishOrchestrator(status, btn, 'More issues found - click Auto-Optimize again to continue.');
                return;
            }
            var postId  = window.amaiSeo ? window.amaiSeo.postId : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce : '';
            if (status) { status.textContent = 'Analyzing...'; }
            var body = new URLSearchParams();
            body.append('action',  'amai_seo_rescan');
            body.append('nonce',   nonce);
            body.append('post_id', postId);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) {
                    finishOrchestrator(status, btn, 'Analysis failed.');
                    return;
                }
                renderRescanResult(data.data);
                var issue = pickNextIssue(data.data.issues || [], succeeded);
                if (!issue) {
                    finishOrchestrator(status, btn, 'All done! Everything looks great.');
                    return;
                }
                fixOneIssue(issue, passIndex, status, btn, succeeded);
            })
            .catch(function () {
                finishOrchestrator(status, btn, 'Request failed.');
            });
        }

        function fixOneIssue(issue, passIndex, status, btn, succeeded) {
            var postId  = window.amaiSeo ? window.amaiSeo.postId : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce : '';
            var label   = FIELD_LABELS[issue.field] || ('Fixing ' + issue.field + '...');
            if (status) { status.textContent = label; }
            var body = new URLSearchParams();
            body.append('action',     'amai_seo_fix_it');
            body.append('nonce',      nonce);
            body.append('post_id',    postId);
            body.append('field',      issue.field);
            body.append('issue_index', issue.issue_index !== undefined ? String(issue.issue_index) : '');
            body.append('fix_mode',    issue.fix_mode || '');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                var field = data.success ? (data.data.field || '') : '';
                var value = data.success ? (data.data.value || '') : '';
                if (!data.success) {
                    setTimeout(function () { runOrchestrator(passIndex + 1, status, btn, succeeded); }, 500);
                    return;
                }
                if (field === 'post_title' || field === 'post_slug') {
                    var currentVal = '';
                    if (field === 'post_title') {
                        var titleEl = document.getElementById('title');
                        currentVal = titleEl ? titleEl.value.trim() : '';
                    } else {
                        var slugEl = document.getElementById('post_name');
                        currentVal = slugEl ? slugEl.value.trim() : '';
                    }
                    var didChange = value.trim() !== currentVal;
                    applyToField(field, value);
                    scheduleNextPass(passIndex, status, btn, field, succeeded, didChange);
                } else if (field === 'post_content') {
                    var mode    = (data.data && data.data.mode)    ? data.data.mode    : '';
                    var patches = (data.data && data.data.patches) ? data.data.patches : [];
                    if (mode === 'paragraphs' && patches.length > 0) {
                        applyParagraphPatches(patches);
                        saveTinyMceContent(postId, nonce, ajaxurl, function () {
                            scheduleNextPass(passIndex, status, btn, field, succeeded, true);
                        });
                    } else if (value) {
                        var currentContent = '';
                        if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                            currentContent = tinyMCE.activeEditor.getContent().trim();
                        } else {
                            var contentEl = document.getElementById('content');
                            currentContent = contentEl ? contentEl.value.trim() : '';
                        }
                        var didChangeContent = value.trim() !== currentContent;
                        applyToField('post_content', value);
                        saveTinyMceContent(postId, nonce, ajaxurl, function () {
                            scheduleNextPass(passIndex, status, btn, field, succeeded, didChangeContent);
                        });
                    } else {
                        scheduleNextPass(passIndex, status, btn, field, succeeded, false);
                    }
                } else if (field === 'post_first_para') {
                    var firstParaEl = document.getElementById('content');
                    var currentFirst = firstParaEl ? firstParaEl.value.trim() : '';
                    if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                        currentFirst = tinyMCE.activeEditor.getContent().trim();
                    }
                    var didChangeFirst = value.trim() !== currentFirst;
                    applyToField('post_first_para', value);
                    saveTinyMceContent(postId, nonce, ajaxurl, function () {
                        scheduleNextPass(passIndex, status, btn, field, succeeded, didChangeFirst);
                    });
                } else if (field === 'post_tags') {
                    var tagSaveBody2 = new URLSearchParams();
                    tagSaveBody2.append('action',  'amai_seo_save_field');
                    tagSaveBody2.append('nonce',   nonce);
                    tagSaveBody2.append('post_id', postId);
                    tagSaveBody2.append('field',   'post_tags');
                    tagSaveBody2.append('value',   value);
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: tagSaveBody2.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function (tagData2) {
                        if (tagData2.success) {
                            var tagInput = document.getElementById('tax-input-post_tag');
                            if (tagInput) { tagInput.value = value.split(',').map(function(t){return t.trim();}).filter(Boolean).join(','); }
                            try { if (window.tagBox) { window.tagBox.flushTags(document.getElementById('post_tag'), false, 1); } } catch (e) {}
                            try { localStorage.removeItem('wp-autosave-' + postId); } catch (e) {}
                        }
                        scheduleNextPass(passIndex, status, btn, field, succeeded, !!(tagData2.success));
                    })
                    .catch(function () { scheduleNextPass(passIndex, status, btn, field, succeeded, false); });
                } else {
                    var saveBody = new URLSearchParams();
                    saveBody.append('action',  'amai_seo_save_field');
                    saveBody.append('nonce',   nonce);
                    saveBody.append('post_id', postId);
                    saveBody.append('field',   field);
                    saveBody.append('value',   value);
                    var metaEl = document.getElementById('amai-seo-' + field.replace(/_/g, '-'));
                    var currentMeta = metaEl ? metaEl.value.trim() : '';
                    var didChangeMeta = value.trim() !== currentMeta;
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: saveBody.toString(),
                    })
                    .then(function (r) { return r.json(); })
                    .then(function (saveData) {
                        if (saveData.success) { applyToField(field, value); }
                        scheduleNextPass(passIndex, status, btn, field, succeeded, saveData.success && didChangeMeta);
                    })
                    .catch(function () {
                        scheduleNextPass(passIndex, status, btn, field, succeeded, false);
                    });
                }
            })
            .catch(function () {
                setTimeout(function () { runOrchestrator(passIndex + 1, status, btn, succeeded); }, 500);
            });
        }

        function saveTinyMceContent(postId, nonce, ajaxurl, callback) {
            var content = '';
            if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                content = tinyMCE.activeEditor.getContent();
            } else {
                var ta = document.getElementById('content');
                if (ta) { content = ta.value; }
            }
            if (!content) { callback(); return; }
            var saveBody = new URLSearchParams();
            saveBody.append('action',  'amai_seo_save_field');
            saveBody.append('nonce',   nonce);
            saveBody.append('post_id', postId);
            saveBody.append('field',   'post_content');
            saveBody.append('value',   content);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: saveBody.toString(),
            })
            .then(function () { callback(); })
            .catch(function () { callback(); });
        }

        function applyParagraphPatches(patches) {
            var content = '';
            if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                content = tinyMCE.activeEditor.getContent();
            } else {
                var ta = document.getElementById('content');
                if (ta) { content = ta.value; }
            }
            if (!content) { return; }
            // Build a map of patch.index -> replacement HTML
            var patchMap = {};
            patches.forEach(function (patch) {
                if (patch.index !== undefined && (patch.fixed || patch.html)) {
                    patchMap[patch.index] = patch.fixed || patch.html;
                }
            });
            var updated;
            if (/<p[\s>]/i.test(content)) {
                // Normal path -- replace <p> tags by counter
                var counter = 0;
                updated = content.replace(/<p(\s[^>]*)?>([\s\S]*?)<\/p>/gi, function (match) {
                    var idx = counter++;
                    return patchMap.hasOwnProperty(idx) ? patchMap[idx] : match;
                });
            } else {
                // Plain-text fallback -- split on double newlines
                var chunks = content.split(/\n{2,}/);
                Object.keys(patchMap).forEach(function (k) {
                    var idx = parseInt(k, 10);
                    if (idx < chunks.length) {
                        var fixed = patchMap[k].replace(/^<p[^>]*>/i, '').replace(/<\/p>$/i, '');
                        chunks[idx] = fixed;
                    }
                });
                updated = chunks.join('\n\n');
            }
            if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                tinyMCE.activeEditor.setContent(updated);
            } else {
                var ta2 = document.getElementById('content');
                if (ta2) { ta2.value = updated; }
            }
        }
        function scheduleNextPass(passIndex, status, btn, field, succeeded, didChange) {
            if (didChange !== false) {
                succeeded.add(field);
            }
            var delay = (field === 'post_content' || field === 'post_first_para') ? 800 : 300;
            setTimeout(function () { runOrchestrator(passIndex + 1, status, btn, succeeded); }, delay);
        }

        function finishOrchestrator(status, btn) {
            var msg = arguments[2] || 'All done!';
            if (btn) {
                btn.disabled = false;
                btn.textContent = 'Auto-Optimize';
                var hint2 = document.getElementById('amai-sw-optimize-hint'); if (hint2) { hint2.style.display = ''; }
            }
            if (status) {
                status.textContent = msg;
                if (msg.indexOf('More issues found') !== -1) {
                    status.classList.add('amai-sw-status--warn');
                } else {
                    status.classList.remove('amai-sw-status--warn');
                }
            }
            var rescanBtn = document.getElementById('amai-rescan-btn');
            if (rescanBtn) {
                setTimeout(function () {
                    rescanBtn.click();
                    setTimeout(function () {
                        var widget = document.getElementById('amai-seo-sidebar-widget');
                        if (!widget) { return; }
                        var existing = document.getElementById('amai-sw-remaining');
                        if (existing) { existing.remove(); }
                        var box = document.getElementById('amai-seo-box');
                        if (!box) { return; }
                        var issueRows = box.querySelectorAll('.amai-seo-issue');
                        if (!issueRows.length) {
                            var postStatus2 = window.amaiSeo ? window.amaiSeo.postStatus : 'publish';
                            if (postStatus2 !== 'publish') {
                                var ep = document.getElementById('amai-sw-publish-prompt');
                                if (ep) { ep.remove(); }
                                var pp = document.createElement('div');
                                pp.id = 'amai-sw-publish-prompt';
                                pp.style.cssText = 'margin-top:14px;border-top:1px solid #E7DDD5;padding-top:14px;padding-left:4px;padding-right:4px;';
                                var ppt = document.createElement('div');
                                ppt.style.cssText = 'font-size:13px;font-weight:700;color:#1C1917;margin-bottom:10px;';
                                ppt.textContent = 'Ready to publish?';
                                var ppb = document.createElement('button');
                                ppb.type = 'button';
                                ppb.textContent = 'Publish now';
                                ppb.style.cssText = 'width:100%;padding:10px;background:#D97757;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;margin-bottom:8px;';
                                ppb.addEventListener('click', function () { var pb = document.getElementById('publish'); if (pb) { pb.click(); } });
                                var pnb = document.createElement('button');
                                pnb.type = 'button';
                                pnb.textContent = 'Not yet';
                                pnb.style.cssText = 'width:100%;padding:8px;background:transparent;color:#78716C;border:1.5px solid #E7DDD5;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;';
                                pnb.addEventListener('click', function () { pp.remove(); });
                                pp.appendChild(ppt);
                                pp.appendChild(ppb);
                                pp.appendChild(pnb);
                                widget.appendChild(pp);
                            }
                            return;
                        }
                        var remaining = document.createElement('div');
                        remaining.id = 'amai-sw-remaining';
                        remaining.style.cssText = 'margin-top:14px;border-top:1px solid #E7DDD5;padding-top:14px;padding-left:4px;padding-right:4px;';
                        var rtitle = document.createElement('div');
                        rtitle.style.cssText = 'font-size:11px;font-weight:700;color:#78716C;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:10px;';
                        rtitle.textContent = 'Remaining issues';
                        remaining.appendChild(rtitle);
                        var rowArr = Array.from(issueRows);
                        rowArr.sort(function(a, b) {
                            var aFix = a.querySelector('.amai-seo-fix-btn') ? 0 : 1;
                            var bFix = b.querySelector('.amai-seo-fix-btn') ? 0 : 1;
                            return aFix - bFix;
                        });
                        rowArr.forEach(function (row) {
                            var msgEl = row.querySelector('.amai-seo-issue-msg');
                            var fixBtn = row.querySelector('.amai-seo-fix-btn');
                            if (!msgEl) { return; }
                            var item = document.createElement('div');
                            item.style.cssText = 'font-size:11.5px;color:#1C1917;margin-bottom:10px;display:flex;align-items:flex-start;gap:6px;';
                            var dot = document.createElement('span');
                            dot.style.cssText = 'width:6px;height:6px;border-radius:50%;background:#D97757;flex-shrink:0;margin-top:4px;';
                            var text = document.createElement('span');
                            text.style.flex = '1';
                            text.textContent = msgEl.textContent;
                            item.appendChild(dot);
                            item.appendChild(text);
                            if (fixBtn) {
                                var btn2 = document.createElement('button');
                                btn2.type = 'button';
                                btn2.className = 'amai-seo-fix-btn';
                                btn2.setAttribute('data-field', fixBtn.getAttribute('data-field'));
                                btn2.setAttribute('data-issue-index', fixBtn.getAttribute('data-issue-index') || '');
                                btn2.setAttribute('data-fix-mode', fixBtn.getAttribute('data-fix-mode') || '');
                                btn2.textContent = 'Fix';
                                btn2.style.cssText = 'flex-shrink:0;padding:2px 8px;font-size:11px;background:#D97757;color:#fff;border:none;border-radius:4px;cursor:pointer;font-weight:600;';
                                item.appendChild(btn2);
                            }
                            remaining.appendChild(item);
                        });
                        widget.appendChild(remaining);
                        var postStatus = window.amaiSeo ? window.amaiSeo.postStatus : 'publish';
                        if (postStatus !== 'publish') {
                            var existingPrompt = document.getElementById('amai-sw-publish-prompt');
                            if (existingPrompt) { existingPrompt.remove(); }
                            var prompt = document.createElement('div');
                            prompt.id = 'amai-sw-publish-prompt';
                            prompt.style.cssText = 'margin-top:14px;border-top:1px solid #E7DDD5;padding-top:14px;padding-left:4px;padding-right:4px;';
                            var promptTitle = document.createElement('div');
                            promptTitle.style.cssText = 'font-size:13px;font-weight:700;color:#1C1917;margin-bottom:10px;';
                            promptTitle.textContent = 'Ready to publish?';
                            var publishBtn = document.createElement('button');
                            publishBtn.type = 'button';
                            publishBtn.textContent = 'Publish now';
                            publishBtn.style.cssText = 'width:100%;padding:10px;background:#D97757;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;margin-bottom:8px;';
                            publishBtn.addEventListener('click', function () {
                                var publishBtnWp = document.getElementById('publish');
                                if (publishBtnWp) { publishBtnWp.click(); }
                            });
                            var notYetBtn = document.createElement('button');
                            notYetBtn.type = 'button';
                            notYetBtn.textContent = 'Not yet';
                            notYetBtn.style.cssText = 'width:100%;padding:8px;background:transparent;color:#78716C;border:1.5px solid #E7DDD5;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;';
                            notYetBtn.addEventListener('click', function () { prompt.remove(); });
                            prompt.appendChild(promptTitle);
                            prompt.appendChild(publishBtn);
                            prompt.appendChild(notYetBtn);
                            widget.appendChild(prompt);
                        }
                    }, 2000);
                }, 1000);
            }
        }

                // --------------------------------------------------
        // Show inline error near button
        // --------------------------------------------------
        // --------------------------------------------------
        // Auto-trigger optimizer if landing from Content Health
        // --------------------------------------------------
        function maybeAutoOptimize() {
            var params = new URLSearchParams(window.location.search);
            if (params.get('amai_autooptimize') !== '1' && params.get('amai_opt') !== '1') { return; }
            // Poll until the optimize button is visible (initial rescan may not have run yet)
            var aoAttempts = 0;
            var aoPoll = setInterval(function () {
                aoAttempts++;
                var btn = document.getElementById('amai-sw-optimize-btn');
                if (btn && btn.style.display !== 'none') {
                    clearInterval(aoPoll);
                    btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    setTimeout(function () { btn.click(); }, 400);
                } else if (aoAttempts >= 20) {
                    clearInterval(aoPoll);
                }
            }, 500);
        }

        function showError(btn, message) {
            var existing = btn.parentNode.querySelector('.amai-seo-inline-error');
            if (existing) { existing.remove(); }
            var err = document.createElement('span');
            err.className = 'amai-seo-inline-error';
            err.style.cssText = 'font-size:11px;color:#EF4444;margin-left:6px;';
            err.textContent = message;
            btn.parentNode.appendChild(err);
            setTimeout(function () { err.remove(); }, 5000);
        }






        // --------------------------------------------------
        // Google snippet modal - desktop / tablet / mobile
        // --------------------------------------------------
        function initSnippetModal() {
            var openBtn  = document.getElementById('amai-sw-preview-btn');
            var modal    = document.getElementById('amai-snippet-modal');
            var closeBtn = document.getElementById('amai-snm-close');
            var backdrop = modal ? modal.querySelector('.amai-snm-backdrop') : null;
            if (!openBtn || !modal) { return; }

            var seo       = window.amaiSeo || {};
            var rawUrl    = seo.postUrl     || window.location.origin;
            var siteName  = seo.siteName    || '';
            var iconUrl   = seo.siteIconUrl || '';

            var currentDevice = 'desktop';
            var LIMITS = {
                desktop: { title: 60, desc: 160 },
                tablet:  { title: 55, desc: 140 },
                mobile:  { title: 50, desc: 120 },
            };

            openBtn.addEventListener('click', function () {
                renderModal();
                modal.style.display = '';
                document.body.classList.add('amai-snm-open');
            });

            if (closeBtn) {
                closeBtn.addEventListener('click', closeModal);
            }
            if (backdrop) {
                backdrop.addEventListener('click', closeModal);
            }
            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape' && modal.style.display !== 'none') { closeModal(); }
            });

            var tabs = modal.querySelectorAll('.amai-snm-tab');
            tabs.forEach(function (tab) {
                tab.addEventListener('click', function () {
                    tabs.forEach(function (t) { t.classList.remove('amai-snm-tab--active'); });
                    tab.classList.add('amai-snm-tab--active');
                    currentDevice = tab.getAttribute('data-device') || 'desktop';
                    applyDevice(currentDevice);
                    renderModal();
                });
            });

            function closeModal() {
                modal.style.display = 'none';
                document.body.classList.remove('amai-snm-open');
            }

            function applyDevice(device) {
                var viewport = modal.querySelector('.amai-snm-viewport');
                if (!viewport) { return; }
                viewport.setAttribute('data-device', device);
            }

            function renderModal() {
                var titleInput = document.getElementById('amai_meta_title');
                var descInput  = document.getElementById('amai_meta_description');
                var rawTitle   = titleInput ? titleInput.value.trim() : '';
                var rawDesc    = descInput  ? descInput.value.trim()  : '';
                var limits     = LIMITS[currentDevice] || LIMITS.desktop;

                var dispTitle = rawTitle.length > limits.title
                    ? rawTitle.slice(0, limits.title - 3) + '...'
                    : rawTitle;
                var dispDesc  = rawDesc.length > limits.desc
                    ? rawDesc.slice(0, limits.desc - 3) + '...'
                    : rawDesc;

                var slugSpan = document.getElementById('editable-post-name');
                var liveSlug = slugSpan ? slugSpan.textContent.trim() : '';

                var titleEl   = document.getElementById('amai-snm-title');
                var descEl    = document.getElementById('amai-snm-desc');
                var faviconEl = document.getElementById('amai-snm-favicon');
                var snameEl   = document.getElementById('amai-snm-sitename');
                var breadcrEl = document.getElementById('amai-snm-breadcrumb');
                var urlEl     = document.getElementById('amai-snm-url');

                if (faviconEl) {
                    if (iconUrl) { faviconEl.src = iconUrl; faviconEl.style.display = ''; }
                    else { faviconEl.style.display = 'none'; }
                }
                if (snameEl)   { snameEl.textContent  = siteName; }
                if (breadcrEl) { breadcrEl.textContent = formatBreadcrumb(rawUrl, liveSlug); }
                if (urlEl)     { urlEl.textContent     = rawUrl; }

                if (titleEl) {
                    titleEl.textContent = dispTitle || 'Your post title will appear here';
                    titleEl.classList.toggle('amai-snm-empty', !rawTitle);
                }
                if (descEl) {
                    descEl.textContent  = dispDesc  || 'Your meta description will appear here.';
                    descEl.classList.toggle('amai-snm-empty', !rawDesc);
                }

                applyDevice(currentDevice);
            }

            function formatBreadcrumb(url, slugOverride) {
                try {
                    var parsed = new URL(url);
                    var host   = parsed.hostname.replace(/^www\./, '');
                    var parts  = parsed.pathname.replace(/\/$/, '').split('/').filter(Boolean);
                    if (slugOverride) {
                        if (parts.length > 0) { parts[parts.length - 1] = slugOverride; }
                        else { parts.push(slugOverride); }
                    }
                    var segs = [host].concat(parts.map(function (p) {
                        return p.replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
                    }));
                    return segs.join(' › ');
                } catch (e) {
                    return url;
                }
            }
        }



        // --------------------------------------------------
        // Suggest internal links
        // --------------------------------------------------
        function handleSuggestLinks(btn) {
            var postId  = window.amaiSeo ? window.amaiSeo.postId  : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce   : '';
            if (!postId) { return; }

            // Remove any existing panel for this row
            var row = btn.closest('.amai-seo-issue');
            if (!row) { return; }
            var existing = row.nextElementSibling;
            if (existing && existing.classList.contains('amai-seo-link-suggestions')) {
                existing.remove();
                return;
            }

            var originalText = btn.textContent;
            btn.disabled    = true;
            btn.textContent = 'Finding...';

            var body = new URLSearchParams();
            body.append('action',  'amai_seo_suggest_links');
            body.append('nonce',   nonce);
            body.append('post_id', postId);

            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled    = false;
                btn.textContent = originalText;
                if (!data.success || !data.data || !data.data.suggestions || !data.data.suggestions.length) {
                    showError(btn, data.data && data.data.message ? data.data.message : 'No suggestions found.');
                    return;
                }
                renderLinkSuggestions(row, data.data.suggestions);
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = originalText;
                showError(btn, 'Request failed. Please try again.');
            });
        }

        function renderLinkSuggestions(row, suggestions) {
            var existing = row.nextElementSibling;
            if (existing && existing.classList.contains('amai-seo-link-suggestions')) {
                existing.remove();
            }

            var panel = document.createElement('div');
            panel.className = 'amai-seo-link-suggestions';

            var label = document.createElement('div');
            label.className = 'amai-seo-ls-label';
            label.textContent = 'Click a post to insert a link into the editor at the cursor (or at the end):';
            panel.appendChild(label);

            var list = document.createElement('div');
            list.className = 'amai-seo-ls-list';

            suggestions.forEach(function (s) {
                var chip = document.createElement('button');
                chip.type = 'button';
                chip.className = 'amai-seo-ls-chip';
                chip.textContent = s.title;
                chip.setAttribute('data-url',    s.url);
                chip.setAttribute('data-anchor', s.anchor);
                chip.addEventListener('click', function () {
                    insertInternalLink(s.url, s.anchor);
                    chip.classList.add('amai-seo-ls-chip--inserted');
                    chip.disabled = true;
                    chip.textContent = s.title + ' - inserted';
                });
                list.appendChild(chip);
            });

            panel.appendChild(list);

            var dismiss = document.createElement('button');
            dismiss.type = 'button';
            dismiss.className = 'amai-seo-ls-dismiss';
            dismiss.textContent = 'Dismiss';
            dismiss.addEventListener('click', function () { panel.remove(); });
            panel.appendChild(dismiss);

            row.insertAdjacentElement('afterend', panel);
        }

        function insertInternalLink(url, anchor) {
            var linkHtml = '<a href="' + url + '">' + anchor + '</a>';
            if (window.tinyMCE && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                var ed = tinyMCE.activeEditor;
                var sel = ed.selection.getContent({ format: 'text' });
                if (sel && sel.trim() !== '') {
                    // Wrap selection
                    ed.execCommand('mceInsertLink', false, url);
                } else {
                    // Insert at cursor
                    ed.insertContent(linkHtml);
                }
            } else {
                var ta = document.getElementById('content');
                if (!ta) { return; }
                var start = ta.selectionStart;
                var end   = ta.selectionEnd;
                if (start !== end) {
                    ta.value = ta.value.substring(0, start) + linkHtml + ta.value.substring(end);
                } else {
                    ta.value = ta.value + ' ' + linkHtml;
                }
            }
        }

        // --------------------------------------------------
        // Inject curated outbound links into post content
        // --------------------------------------------------
        function handleInjectLinks(btn) {
            var postId  = window.amaiSeo ? window.amaiSeo.postId  : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce   : '';
            if (!postId) { return; }
            var originalText = btn.textContent;
            btn.disabled    = true;
            btn.textContent = 'Adding links...';
            var body = new URLSearchParams();
            body.append('action',  'amai_seo_inject_links');
            body.append('nonce',   nonce);
            body.append('post_id', postId);
            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled    = false;
                btn.textContent = originalText;
                if (!data.success) {
                    showError(btn, data.data && data.data.message ? data.data.message : 'Could not inject links.');
                    return;
                }
                // Reload the page so the editor reflects the injected links and rescan runs
                window.location.reload();
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = originalText;
                showError(btn, 'Request failed. Please try again.');
            });
        }

        function handleInjectInternalLinks(btn) {
            var postId  = window.amaiSeo ? window.amaiSeo.postId : 0;
            var ajaxurl = window.amaiSeo ? window.amaiSeo.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiSeo ? window.amaiSeo.nonce : '';
            var originalText = btn.textContent;
            btn.disabled    = true;
            btn.textContent = 'Adding...';
            var body = new URLSearchParams();
            body.append('action',  'amai_seo_inject_internal_links');
            body.append('nonce',   nonce);
            body.append('post_id', postId);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled    = false;
                btn.textContent = originalText;
                if (!data.success) {
                    showError(btn, data.data && data.data.message ? data.data.message : 'Could not inject internal links.');
                    return;
                }
                // Reload so TinyMCE reflects injected links and rescan runs
                btn.disabled    = false;
                btn.textContent = 'Done!';
                setTimeout(function () { btn.textContent = originalText; }, 2000);
                var rescanBtn = document.getElementById('amai-rescan-btn');
                if (rescanBtn) { setTimeout(function () { rescanBtn.click(); }, 800); }
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = originalText;
                showError(btn, 'Request failed.');
            });
        }

    });

    // --------------------------------------------------
    // Facebook OG preview modal
    // --------------------------------------------------
    function initFacebookModal() {
        var openBtn  = document.getElementById('amai-sw-fb-preview-btn');
        var modal    = document.getElementById('amai-fb-modal');
        var closeBtn = document.getElementById('amai-fbm-close');
        var backdrop = modal ? modal.querySelector('.amai-fbm-backdrop') : null;
        if (!openBtn || !modal) { return; }

        var seo      = window.amaiSeo || {};
        var postUrl  = seo.postUrl          || window.location.origin;
        var imgUrl   = seo.featuredImageUrl || '';

        openBtn.addEventListener('click', function () {
            renderFbModal();
            modal.style.display = '';
            document.body.classList.add('amai-fbm-open');
        });

        if (closeBtn) { closeBtn.addEventListener('click', closeFbModal); }
        if (backdrop) { backdrop.addEventListener('click', closeFbModal); }
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && modal.style.display !== 'none') { closeFbModal(); }
        });

        function closeFbModal() {
            modal.style.display = 'none';
            document.body.classList.remove('amai-fbm-open');
        }

        function renderFbModal() {
            var titleInput = document.getElementById('amai_meta_title');
            var descInput  = document.getElementById('amai_meta_description');
            var rawTitle   = titleInput ? titleInput.value.trim() : '';
            var rawDesc    = descInput  ? descInput.value.trim()  : '';

            // Facebook truncation: title ~88 chars, desc ~300 chars
            var dispTitle = rawTitle.length > 88  ? rawTitle.slice(0, 85)  + '...' : rawTitle;
            var dispDesc  = rawDesc.length  > 300 ? rawDesc.slice(0, 297)  + '...' : rawDesc;

            // Domain — strip protocol
            var domain = postUrl.replace(/^https?:\/\//, '').split('/')[0].toUpperCase();

            var imgEl       = document.getElementById('amai-fbm-image');
            var imgEmptyEl  = document.getElementById('amai-fbm-image-empty');
            var domainEl    = document.getElementById('amai-fbm-domain');
            var titleEl     = document.getElementById('amai-fbm-card-title');
            var descEl      = document.getElementById('amai-fbm-card-desc');

            // Featured image — use localized value; listen for WP featured image changes
            var currentImg = imgUrl || getCurrentFeaturedImageUrl();
            if (currentImg) {
                if (imgEl)      { imgEl.src = currentImg; imgEl.style.display = ''; }
                if (imgEmptyEl) { imgEmptyEl.style.display = 'none'; }
            } else {
                if (imgEl)      { imgEl.style.display = 'none'; }
                if (imgEmptyEl) { imgEmptyEl.style.display = ''; }
            }

            if (domainEl) { domainEl.textContent = domain; }
            if (titleEl) {
                titleEl.textContent = dispTitle || 'Your post title will appear here';
                titleEl.classList.toggle('amai-fbm-empty', !rawTitle);
            }
            if (descEl) {
                descEl.textContent  = dispDesc  || 'Your meta description will appear here.';
                descEl.classList.toggle('amai-fbm-empty', !rawDesc);
            }
        }

        function getCurrentFeaturedImageUrl() {
            // WP sets #set-post-thumbnail img src when a featured image is chosen
            var thumb = document.querySelector('#set-post-thumbnail img');
            return thumb ? (thumb.src || '') : '';
        }
    }

    // --------------------------------------------------
    // Featured image picker
    // --------------------------------------------------
    function initFeaturedImagePicker() {
        var nonce       = (amaiSeo.nonce || '');
        var postId      = parseInt(amaiSeo.postId, 10);
        var hasProvider = !!amaiSeo.hasImageProvider && amaiSeo.hasImageProvider !== '0' && amaiSeo.hasImageProvider !== 'false';
        var postTitle   = amaiSeo.postTitle || '';
        var ajaxurl     = amaiSeo.ajaxurl || '';

        // Inject trigger button into WP's featured image meta box
        function injectTriggerButton() {
            var sidebar = document.getElementById('postimagediv');
            if (!sidebar) return;
            if (document.getElementById('amai-featured-image-btn')) return;
            var btn = document.createElement('button');
            btn.type = 'button';
            btn.id   = 'amai-featured-image-btn';
            btn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg> Choose image';
            var inside = sidebar.querySelector('.inside');
            if (inside) inside.appendChild(btn);
        }
        injectTriggerButton();

        // Hide WP native featured image links on load
        (function () {
            var wpSetLink    = document.getElementById('set-post-thumbnail-desc');
            var wpRemoveLink = document.getElementById('remove-post-thumbnail');
            if (wpSetLink)    wpSetLink.style.display    = 'none';
            if (wpRemoveLink) wpRemoveLink.style.display = 'none';
        }());

        var modal       = document.getElementById('amai-fip-modal');
        var backdrop    = document.getElementById('amai-fip-backdrop');
        var closeBtn    = document.getElementById('amai-fip-close');
        var cancelBtn   = document.getElementById('amai-fip-cancel');
        var setBtn      = document.getElementById('amai-fip-set-btn');
        var statusEl    = document.getElementById('amai-fip-status');
        var tabs        = document.querySelectorAll('.amai-fip-tab');
        var panes       = document.querySelectorAll('.amai-fip-pane');
        var mediaGrid   = document.getElementById('amai-fip-media-grid');
        var mediaSearch = document.getElementById('amai-fip-media-search');
        var uploadBtn   = document.getElementById('amai-fip-upload-btn');
        var uInput      = document.getElementById('amai-fip-unsplash-input');
        var uBtn        = document.getElementById('amai-fip-unsplash-btn');
        var uGrid       = document.getElementById('amai-fip-unsplash-grid');
        var aiBtn       = document.getElementById('amai-fip-ai-btn');
        var aiPromptEl  = document.getElementById('amai-fip-ai-prompt');
        var aiPreview   = document.getElementById('amai-fip-ai-preview');
        var aiPreviewImg = document.getElementById('amai-fip-ai-preview-img');

        if (!modal) return;

        var activeTab    = 'media';
        var selectedType = null;
        var selectedData = null;
        var mediaLoaded  = false;

        // Open
        document.addEventListener('click', function (e) {
            if (!e.target.closest('#amai-featured-image-btn')) return;
            openModal();
        });

        function openModal() {
            modal.classList.add('is-open');
            setStatus('');
            setBtn.disabled = true;
            if (!mediaLoaded) loadMediaLibrary();
            updateAiPrompt();
            autoSearchUnsplash();
            // Hide WP native featured image links
            var wpSetLink    = document.getElementById('set-post-thumbnail-desc');
            var wpRemoveLink = document.getElementById('remove-post-thumbnail');
            if (wpSetLink)    wpSetLink.style.display    = 'none';
            if (wpRemoveLink) wpRemoveLink.style.display = 'none';
            if (!hasProvider) {
                var aiCenter = document.getElementById('amai-fip-ai-center');
                if (aiCenter) {
                    aiCenter.innerHTML = '<div class="amai-fip-ai-no-provider">No image provider is active. Enable an AI image module (Imagen, DALL-E, or Aurora) in the Modules page to use this feature.</div>';
                }
            }
        }

        function closeModal() { modal.classList.remove('is-open'); }
        if (closeBtn)  closeBtn.addEventListener('click', closeModal);
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
        if (backdrop)  backdrop.addEventListener('click', closeModal);
        document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeModal(); });

        // Tabs
        tabs.forEach(function (tab) {
            tab.addEventListener('click', function () {
                var target = tab.dataset.tab;
                tabs.forEach(function (t) { t.classList.remove('is-active'); });
                panes.forEach(function (p) { p.classList.remove('is-active'); });
                tab.classList.add('is-active');
                var pane = document.querySelector('.amai-fip-pane[data-pane="' + target + '"]');
                if (pane) pane.classList.add('is-active');
                activeTab = target;
                setStatus('');
                updateSetBtn();
            });
        });

        // ── Media Library ──
        function loadMediaLibrary(search) {
            mediaGrid.innerHTML = '<div class="amai-fip-media-loading">Loading...</div>';
            var fd = new FormData();
            fd.append('action', 'amai_seo_media_library');
            fd.append('nonce', nonce);
            if (search) fd.append('search', search);
            fetch(ajaxurl, { method: 'POST', body: fd })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    mediaLoaded = true;
                    if (!data.success || !data.data.items.length) {
                        mediaGrid.innerHTML = '<div class="amai-fip-media-empty">No images found.</div>';
                        return;
                    }
                    renderMediaGrid(data.data.items);
                })
                .catch(function () {
                    mediaGrid.innerHTML = '<div class="amai-fip-media-empty">Failed to load media library.</div>';
                });
        }

        function renderMediaGrid(items) {
            mediaGrid.innerHTML = '';
            items.forEach(function (item) {
                var div = document.createElement('div');
                div.className = 'amai-fip-media-item';
                div.dataset.attachmentId = item.id;
                div.innerHTML = '<img src="' + item.thumb + '" alt="' + item.title + '" loading="lazy"><div class="amai-fip-media-check">&#10003;</div>';
                div.addEventListener('click', function () {
                    document.querySelectorAll('.amai-fip-media-item').forEach(function (el) { el.classList.remove('is-selected'); });
                    div.classList.add('is-selected');
                    selectedType = 'media';
                    selectedData = { attachmentId: item.id, url: item.full };
                    updateSetBtn();
                });
                mediaGrid.appendChild(div);
            });
        }

        if (uploadBtn) {
            uploadBtn.addEventListener('click', function () {
                var frame = window.wp && window.wp.media ? window.wp.media({
                    title: 'Upload or choose image',
                    button: { text: 'Use this image' },
                    multiple: false,
                    library: { type: 'image' }
                }) : null;
                if (!frame) return;
                frame.on('select', function () {
                    var attachment = frame.state().get('selection').first().toJSON();
                    selectedType = 'media';
                    selectedData = { attachmentId: attachment.id, url: attachment.url };
                    mediaLoaded = false;
                    loadMediaLibrary();
                    updateSetBtn();
                });
                frame.open();
            });
        }

        var mediaSearchTimer;
        if (mediaSearch) {
            mediaSearch.addEventListener('input', function () {
                clearTimeout(mediaSearchTimer);
                mediaSearchTimer = setTimeout(function () { loadMediaLibrary(mediaSearch.value.trim()); }, 400);
            });
        }

        // ── Unsplash ──
        function searchUnsplash(query) {
            uGrid.innerHTML = '<div class="amai-fip-unsplash-loading" style="grid-column:1/-1">Searching Unsplash...</div>';
            uBtn.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_seo_unsplash_search');
            fd.append('nonce', nonce);
            fd.append('query', query);
            fetch(ajaxurl, { method: 'POST', body: fd })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    uBtn.disabled = false;
                    if (!data.success || !data.data.results.length) {
                        uGrid.innerHTML = '<div class="amai-fip-unsplash-empty" style="grid-column:1/-1">No photos found. Try different keywords.</div>';
                        return;
                    }
                    renderUnsplashGrid(data.data.results);
                })
                .catch(function () {
                    uBtn.disabled = false;
                    uGrid.innerHTML = '<div class="amai-fip-unsplash-empty" style="grid-column:1/-1">Search failed. Please try again.</div>';
                });
        }

        function renderUnsplashGrid(results) {
            uGrid.innerHTML = '';
            results.forEach(function (photo) {
                var div = document.createElement('div');
                div.className = 'amai-fip-unsplash-item';
                div.innerHTML = '<img src="' + photo.thumb + '" alt="Photo by ' + photo.photographer + '" loading="lazy">'
                    + '<div class="amai-fip-unsplash-credit">Photo by <a href="' + photo.profile_url + '?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener">' + photo.photographer + '</a> on <a href="https://unsplash.com/?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener">Unsplash</a></div>'
                    + '<div class="amai-fip-unsplash-check">&#10003;</div>';
                div.addEventListener('click', function () {
                    document.querySelectorAll('.amai-fip-unsplash-item').forEach(function (el) { el.classList.remove('is-selected'); });
                    div.classList.add('is-selected');
                    selectedType = 'unsplash';
                    selectedData = photo;
                    updateSetBtn();
                });
                uGrid.appendChild(div);
            });
        }

        if (uBtn) {
            uBtn.addEventListener('click', function () { var q = uInput.value.trim(); if (q) searchUnsplash(q); });
        }
        if (uInput) {
            uInput.addEventListener('keydown', function (e) { if (e.key === 'Enter') { var q = uInput.value.trim(); if (q) searchUnsplash(q); } });
        }

        // ── AI Generate ──
        function updateAiPrompt() {
            if (!aiPromptEl) return;
            var keyword = '';
            var kwInput = document.getElementById('amai_focus_keyword');
            if (kwInput) keyword = kwInput.value.trim();
            var prompt = 'A high-quality professional photograph for a blog post titled "' + postTitle + '"';
            if (keyword) prompt += ', about ' + keyword;
            prompt += '. Bright, clean, modern style. No text or logos.';
            aiPromptEl.textContent = prompt;
        }

        function autoSearchUnsplash() {
            var kwInput = document.getElementById('amai_focus_keyword');
            var kw = kwInput ? kwInput.value.trim() : '';
            if (!kw) {
                var words = postTitle.split(' ').filter(function (w) { return w.length > 3; }).slice(0, 3);
                kw = words.join(' ');
            }
            if (!kw) return;
            if (uInput) uInput.value = kw;
            searchUnsplash(kw);
        }

        if (aiBtn) {
            aiBtn.addEventListener('click', function () {
                if (!hasProvider) return;
                aiBtn.disabled = true;
                aiBtn.classList.add('is-loading');
                setStatus('Generating image - this may take 20-30 seconds...');
                var fd = new FormData();
                fd.append('action', 'amai_seo_featured_image_ai');
                fd.append('nonce', nonce);
                fd.append('post_id', postId);
                fetch(ajaxurl, { method: 'POST', body: fd })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        aiBtn.disabled = false;
                        aiBtn.classList.remove('is-loading');
                        if (!data.success) {
                            setStatus((data.data && data.data.message) ? data.data.message : 'Generation failed.', true);
                            return;
                        }
                        setStatus('');
                        aiPreviewImg.src = data.data.url;
                        aiPreview.classList.add('is-visible');
                        selectedType = 'ai';
                        selectedData = { url: data.data.url, attachmentId: data.data.attachment_id };
                        updateSetBtn();
                    })
                    .catch(function () {
                        aiBtn.disabled = false;
                        aiBtn.classList.remove('is-loading');
                        setStatus('Request failed. Please try again.', true);
                    });
            });
        }

        // ── Set image button ──
        function updateSetBtn() {
            var ok = (activeTab === 'media' && selectedType === 'media')
                  || (activeTab === 'unsplash' && selectedType === 'unsplash')
                  || (activeTab === 'ai' && selectedType === 'ai');
            setBtn.disabled = !ok;
        }

        if (setBtn) {
            setBtn.addEventListener('click', function () {
                if (!selectedType || !selectedData) return;
                setBtn.classList.add('is-loading');
                setBtn.disabled = true;
                setStatus('');
                if (selectedType === 'media') {
                    var fd = new FormData();
                    fd.append('action', 'amai_seo_set_media_featured');
                    fd.append('nonce', nonce);
                    fd.append('post_id', postId);
                    fd.append('attachment_id', selectedData.attachmentId);
                    fetch(ajaxurl, { method: 'POST', body: fd })
                        .then(function (r) { return r.json(); })
                        .then(function (data) { handleSetResponse(data); })
                        .catch(handleSetError);
                } else if (selectedType === 'unsplash') {
                    var fd2 = new FormData();
                    fd2.append('action', 'amai_seo_unsplash_set');
                    fd2.append('nonce', nonce);
                    fd2.append('post_id', postId);
                    fd2.append('url', selectedData.url);
                    fd2.append('photographer', selectedData.photographer || '');
                    fd2.append('profile_url', selectedData.profile_url || '');
                    fd2.append('download_location', selectedData.download_location || '');
                    setStatus('Downloading photo...');
                    fetch(ajaxurl, { method: 'POST', body: fd2 })
                        .then(function (r) { return r.json(); })
                        .then(function (data) { handleSetResponse(data); })
                        .catch(handleSetError);
                } else if (selectedType === 'ai') {
                    if (selectedData.attachmentId) {
                        var fd3 = new FormData();
                        fd3.append('action', 'amai_seo_set_media_featured');
                        fd3.append('nonce', nonce);
                        fd3.append('post_id', postId);
                        fd3.append('attachment_id', selectedData.attachmentId);
                        fetch(ajaxurl, { method: 'POST', body: fd3 })
                            .then(function (r) { return r.json(); })
                            .then(function (data) { handleSetResponse(data); })
                            .catch(handleSetError);
                    } else {
                        updateWpFeaturedImageUI(selectedData.url, selectedData.attachmentId);
                        setStatus('Image set. Save the post to apply.', false);
                        setBtn.classList.remove('is-loading');
                        closeModal();
                    }
                }
            });
        }

        function handleSetResponse(data) {
            setBtn.classList.remove('is-loading');
            if (!data.success) {
                setBtn.disabled = false;
                setStatus((data.data && data.data.message) ? data.data.message : 'Failed to set image.', true);
                return;
            }
            updateWpFeaturedImageUI(data.data.url, data.data.attachment_id);
            closeModal();
        }

        function handleSetError() {
            setBtn.classList.remove('is-loading');
            setBtn.disabled = false;
            setStatus('Request failed. Please try again.', true);
        }

        function updateWpFeaturedImageUI(url, attachmentId) {
            // Update hidden _thumbnail_id so WP saves it on Update
            if (attachmentId) {
                var hiddenInput = document.getElementById('_thumbnail_id');
                if (!hiddenInput) {
                    hiddenInput = document.createElement('input');
                    hiddenInput.type = 'hidden';
                    hiddenInput.id   = '_thumbnail_id';
                    hiddenInput.name = '_thumbnail_id';
                    var postForm = document.getElementById('post');
                    if (postForm) postForm.appendChild(hiddenInput);
                }
                if (hiddenInput) hiddenInput.value = attachmentId;
            }
            // Update the featured image thumbnail display
            var thumb = document.getElementById('set-post-thumbnail');
            if (thumb) {
                thumb.innerHTML = '<img src="' + url + '" style="max-width:100%;height:auto;border-radius:4px;" alt="Featured image">';
            }
            // Hide WP native links -- our button is the only way in
            var wpSetLink    = document.getElementById('set-post-thumbnail-desc');
            var wpRemoveLink = document.getElementById('remove-post-thumbnail');
            if (wpSetLink)    wpSetLink.style.display    = 'none';
            if (wpRemoveLink) wpRemoveLink.style.display = 'none';
            amaiSeo.featuredImageUrl = url;
            var fbImg   = document.getElementById('amai-fbm-image');
            var fbEmpty = document.getElementById('amai-fbm-image-empty');
            if (fbImg && url) {
                fbImg.src = url;
                fbImg.style.display = 'block';
                if (fbEmpty) fbEmpty.style.display = 'none';
            }
        }

        function setStatus(msg, isError) {
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.className = 'amai-fip-status' + (isError ? ' is-error' : (msg ? ' is-success' : ''));
        }
    }

}());