/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /assets/js/amai-social.js
   Description: Social Media module JavaScript — picker, notices, create page modal, disconnect modal, post panel
   Last Edited: 2026-04-10
   ================================================== */
(function () {
    'use strict';
    // ---- Bio dashboard sync helper ----
    function amaiSyncBioToDashboard(bioText) {
        var dashTextarea = document.getElementById('amai-bio-textarea');
        var dashResult   = document.getElementById('amai-bio-result');
        var dashBadge    = document.querySelector('.amai-bio-card-toggle-label .amai-bio-status-badge');
        if (dashTextarea) { dashTextarea.value = bioText; }
        if (dashResult) { dashResult.style.display = 'block'; }
        if (dashBadge) {
            dashBadge.className = 'amai-bio-status-badge amai-bio-status-done';
            dashBadge.textContent = '✓ Bio saved';
        }
    }

    // ---- Page picker: card selection ----
    var cards       = document.querySelectorAll('.amai-fb-page-card');
    var pageIdInput = document.getElementById('amai-selected-page-id');
    var selectBtn   = document.getElementById('amai-fb-select-btn');
    if (cards.length && pageIdInput && selectBtn) {
        // Auto-select when there is only one page
        if (cards.length === 1) {
            cards[0].classList.add('selected');
            pageIdInput.value = cards[0].dataset.pageId || '';
            selectBtn.disabled = false;
        }
        cards.forEach(function (card) {
            card.addEventListener('click', function () {
                cards.forEach(function (c) { c.classList.remove('selected'); });
                card.classList.add('selected');
                pageIdInput.value = card.dataset.pageId || '';
                selectBtn.disabled = false;
            });
            card.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    card.click();
                }
            });
        });
    }

    // ---- Auto-dismiss soft notices after 7 seconds ----
    var autoNotice = document.getElementById('amai-fb-notice-auto');
    if (autoNotice) {
        setTimeout(function () {
            autoNotice.style.transition = 'opacity 0.8s ease';
            autoNotice.style.opacity = '0';
            setTimeout(function () {
                if (autoNotice.parentNode) {
                    autoNotice.parentNode.removeChild(autoNotice);
                }
            }, 800);
        }, 7000);
    }

    // ---- Instagram disconnect modal ----
    var igDcModal      = document.getElementById('amai-ig-disconnect-modal');
    var igDcTrigger    = document.getElementById('amai-ig-disconnect-trigger');
    var igDcClose      = document.getElementById('amai-ig-dc-close');
    var igDcCancel     = document.getElementById('amai-ig-dc-cancel');
    var igDcConfirmBtn = document.getElementById('amai-ig-dc-confirm-btn');
    if (igDcTrigger && igDcModal) {
        igDcTrigger.addEventListener('click', function () {
            igDcModal.style.display = 'flex';
        });
    }
    if (igDcClose && igDcModal) {
        igDcClose.addEventListener('click', function () { igDcModal.style.display = 'none'; });
    }
    if (igDcCancel && igDcModal) {
        igDcCancel.addEventListener('click', function () { igDcModal.style.display = 'none'; });
    }
    if (igDcModal) {
        igDcModal.addEventListener('click', function (e) {
            if (e.target === igDcModal) { igDcModal.style.display = 'none'; }
        });
    }
    if (igDcConfirmBtn) {
        igDcConfirmBtn.addEventListener('click', function () {
            var nonce = igDcConfirmBtn.getAttribute('data-nonce') || '';
            igDcConfirmBtn.disabled = true;
            igDcConfirmBtn.textContent = 'Disconnecting…';
            var formData = new FormData();
            formData.append('action', 'amai_ig_disconnect');
            formData.append('_wpnonce', nonce);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', { method: 'POST', body: formData })
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.success && res.data && res.data.redirect) {
                        window.location.href = res.data.redirect;
                    } else {
                        igDcConfirmBtn.disabled = false;
                        igDcConfirmBtn.textContent = 'Yes, disconnect';
                        var msg = res.data && res.data.message ? res.data.message : 'Disconnect failed. Please try again.';
                        alert(msg);
                    }
                })
                .catch(function () {
                    igDcConfirmBtn.disabled = false;
                    igDcConfirmBtn.textContent = 'Yes, disconnect';
                    alert('Request failed. Please try again.');
                });
        });
    }

        // ---- Auto-dismiss disconnected toast after 7 seconds ----
    var dcToast = document.getElementById('amai-fb-disconnected-toast');
    if (dcToast) {
        setTimeout(function () {
            dcToast.classList.add('amai-fb-toast-dismissing');
            setTimeout(function () {
                if (dcToast.parentNode) {
                    dcToast.parentNode.removeChild(dcToast);
                }
            }, 600);
        }, 7000);
    }

    // =====================================================
    // DISCONNECT CONFIRMATION MODAL
    // =====================================================

    var dcModal      = document.getElementById('amai-disconnect-modal');
    var dcTrigger    = document.getElementById('amai-fb-disconnect-trigger');
    var dcClose      = document.getElementById('amai-dc-close');
    var dcCancel     = document.getElementById('amai-dc-cancel');
    var dcConfirmBtn = document.getElementById('amai-dc-confirm-btn');

    if (dcModal && dcTrigger) {

        function dcOpen() {
            dcModal.classList.add('show');
        }

        function dcCloseModal() {
            dcModal.classList.remove('show');
        }

        dcTrigger.addEventListener('click', function (e) {
            e.preventDefault();
            dcOpen();
        });

        dcClose.addEventListener('click', dcCloseModal);
        dcCancel.addEventListener('click', dcCloseModal);
        dcModal.addEventListener('click', function (e) {
            if (e.target === dcModal) { dcCloseModal(); }
        });

        if (dcConfirmBtn) {
            dcConfirmBtn.addEventListener('click', function () {
                var nonce = dcConfirmBtn.dataset.nonce || '';
                dcConfirmBtn.disabled = true;
                dcConfirmBtn.textContent = 'Disconnecting...';

                var formData = new FormData();
                formData.append('action', 'amai_fb_disconnect');
                formData.append('_wpnonce', nonce);

                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData,
                })
                .then(function (response) { return response.json(); })
                .then(function (data) {
                    if (data && data.success) {
                        window.location.href = data.data.redirect || window.location.href;
                    } else {
                        var msg = (data && data.data && data.data.message) ? data.data.message : 'Something went wrong. Please try again.';
                        dcConfirmBtn.textContent = msg;
                        setTimeout(function () {
                            dcConfirmBtn.textContent = 'Yes, disconnect';
                            dcConfirmBtn.disabled = false;
                        }, 3000);
                    }
                })
                .catch(function () {
                    dcConfirmBtn.textContent = 'Network error - try again';
                    setTimeout(function () {
                        dcConfirmBtn.textContent = 'Yes, disconnect';
                        dcConfirmBtn.disabled = false;
                    }, 3000);
                });
            });
        }

        document.addEventListener('keydown', function (e) {
            if (!dcModal.classList.contains('show')) { return; }
            if (e.key === 'Escape') { dcCloseModal(); }
        });
    }

    // =====================================================
    // CREATE PAGE WALKTHROUGH MODAL
    // =====================================================

    var cpModal = document.getElementById('amai-create-page-modal');

    if (cpModal) {

        var cpClose   = document.getElementById('amai-cp-close');
        var cpBack    = document.getElementById('amai-cp-back');
        var cpNext    = document.getElementById('amai-cp-next');
        var cpGoFb    = document.getElementById('amai-cp-go-fb');
        var cpGoConn  = document.getElementById('amai-cp-go-connect');
        var cpBody    = document.getElementById('amai-cp-body');
        var cpLabels  = document.getElementById('amai-cp-labels');
        var cpFill    = document.getElementById('amai-cp-fill');
        var cpCounter = document.getElementById('amai-cp-counter');
        var cpTip     = document.getElementById('amai-cp-tip');

        var cpCur = 0;

        var cpSteps = [
            {
                label: 'Get Started',
                tip:   'Takes about 4 minutes total',
                inst:  'Log into Facebook. Click the <strong>grid icon</strong> (9 dots, top right) to open the menu, then click <strong>Pages</strong>. On the Pages screen, click <strong>+ Create Page</strong>. Select <strong>Public Page</strong> and click <strong>Next</strong>, then <strong>Get started</strong>. <a href="https://www.facebook.com/pages/?category=your_pages&amp;ref=bookmarks" target="_blank" rel="noopener noreferrer" style="color:#1877F2;font-weight:500;">Open Pages on Facebook →</a>',
                note:  'Use the same Facebook account you\'ll authorize AutoMarketer AI with.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="width:180px;">' +
                        '<div class="amai-cp-mock-sidebar-title">Pages</div>' +
                        '<div class="amai-cp-mock-btn-fb amai-cp-hl" style="margin-top:8px;">+ Create Page</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview" style="align-items:flex-start;padding:14px;">' +
                        '<div class="amai-cp-mock-sidebar-title" style="margin-bottom:8px;">Which option is best for you?</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl" style="margin-bottom:6px;display:flex;align-items:center;gap:6px;"><span style="width:10px;height:10px;border-radius:50%;border:2px solid #1877F2;display:inline-block;flex-shrink:0;"></span>Public Page</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="display:flex;align-items:center;gap:6px;"><span style="width:10px;height:10px;border-radius:50%;border:2px solid #4B5563;display:inline-block;flex-shrink:0;"></span>Upgrade your existing profile</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Name & Category',
                tip:   'Use the name your customers already know',
                inst:  'Enter your <strong>Page name</strong> - use your business name exactly as customers know it. Then click <strong>Category</strong> and start typing what your business does. Pick the closest match. Skip the Bio field for now - we cover that on the next step.',
                note:  'This is the page AutoMarketer AI will learn and post for. Pick the one you\'re sticking with.',
                noteType: 'warn',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar">' +
                        '<div class="amai-cp-mock-sidebar-title">Create a Page</div>' +
                        '<div class="amai-cp-mock-sidebar-sub">Your Page is where people go to learn more about you.</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl">Your Business Name</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl">Plumber · Local Business</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-field-tall">Bio (optional)</div>' +
                        '<div class="amai-cp-mock-btn-fb" style="opacity:0.5;">Create Page</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name amai-cp-hl">Your Business Name</div>' +
                        '<div style="font-size:9px;color:#6B7280;text-align:center;margin-top:3px;">Local Business</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Bio',
                tip:   'Fill this in now - you won\'t come back',
                inst:  'The <strong>Bio</strong> field says optional. Ignore that. This is the single most important thing you can fill in right now. AutoMarketer AI reads your bio to write posts that sound like <em>your</em> business - not a generic template. One sentence. Who you help, what you do, where you do it.',
                note:  'Example: "We help homeowners across the GTA with plumbing repairs, installations, and emergency service." Write yours the same way - who you help, what you do, where.',
                noteType: 'warn',
                bioButton: true,
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar">' +
                        '<div class="amai-cp-mock-sidebar-title">Create a Page</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled">Your Business Name</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled">Plumber · Local Business</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-mock-field-tall amai-cp-hl" style="font-size:8.5px;line-height:1.4;">We help homeowners with plumbing repairs, installations, and emergency service.</div>' +
                        '<div class="amai-cp-mock-btn-fb">Create Page</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business Name</div>' +
                        '<div style="font-size:7.5px;color:#9CA3AF;text-align:center;margin-top:3px;line-height:1.4;">We help homeowners with plumbing repairs...</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Create Page',
                tip:   'Your page goes live the moment you click',
                inst:  'Click <strong>Create Page</strong>. Facebook creates your page instantly. You\'ll land on a setup flow - "Finish setting up your Page" - with 5 steps. Don\'t skip them. The next few steps walk you through exactly what to fill in.',
                note:  'Your page is live but incomplete. The setup steps that follow are what make it trustworthy to customers.',
                noteType: 'success',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar">' +
                        '<div class="amai-cp-mock-sidebar-title">Create a Page</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled">Your Business Name</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled">Plumber · Local Business</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-mock-field-tall" style="font-size:8.5px;line-height:1.4;">We help homeowners with plumbing repairs...</div>' +
                        '<div class="amai-cp-mock-btn-fb amai-cp-hl">Create Page</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business Name</div>' +
                        '<div style="font-size:9px;color:#1877F2;text-align:center;margin-top:4px;">Local Business · 0 Followers</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Contact & Location',
                tip:   'Customers use this to find and call you',
                inst:  'Facebook shows <strong>Step 1 of 5 - Finish setting up your Page</strong>. Fill in your <strong>Website</strong>, <strong>Phone number</strong>, <strong>Email</strong>, then your <strong>Address</strong>, <strong>City</strong>, and <strong>ZIP code</strong>. Every field you fill in shows up on your page and in local search.',
                note:  'Website is the most important one - every post we write can drive traffic there. No website yet? Add your phone number at minimum.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="gap:5px;">' +
                        '<div class="amai-cp-mock-sidebar-sub" style="color:#4ADE80;font-weight:600;font-size:8px;">Step 1 of 5 - Finish setting up your Page</div>' +
                        '<div class="amai-cp-mock-sidebar-title" style="font-size:10px;">Contact</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl" style="font-size:8.5px;">yoursite.com</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled" style="font-size:8.5px;">+1 555-867-5309</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled" style="font-size:8.5px;">hello@yoursite.com</div>' +
                        '<div class="amai-cp-mock-sidebar-title" style="font-size:10px;margin-top:2px;">Location</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled" style="font-size:8.5px;">123 Main Street</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8.5px;">City / ZIP</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business</div>' +
                        '<div style="font-size:7.5px;color:#9CA3AF;text-align:center;margin-top:3px;line-height:1.6;">123 Main Street<br>+1 555-867-5309</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Hours',
                tip:   'Customers check hours before they call',
                inst:  'Scroll down on the same screen to find <strong>Hours</strong>. Pick one: <strong>No hours available</strong>, <strong>Always open</strong>, or <strong>Open at selected hours</strong> if you want to set specific days and times. Then click <strong>Next</strong>.',
                note:  'Facebook surfaces hours in local search results. A page with hours listed looks more trustworthy and ranks better than one without.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="gap:6px;">' +
                        '<div class="amai-cp-mock-sidebar-sub" style="color:#4ADE80;font-weight:600;font-size:8px;">Step 1 of 5 - scroll down</div>' +
                        '<div class="amai-cp-mock-sidebar-title" style="font-size:10px;">Hours</div>' +
                        '<div class="amai-cp-mock-sidebar-sub" style="margin-bottom:2px;">Let people know your location\'s hours.</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8.5px;display:flex;align-items:center;gap:6px;"><span style="width:9px;height:9px;border-radius:50%;border:1.5px solid #4B5563;display:inline-block;flex-shrink:0;"></span>No hours available</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl" style="font-size:8.5px;display:flex;align-items:center;gap:6px;"><span style="width:9px;height:9px;border-radius:50%;border:2px solid #1877F2;background:#1877F2;display:inline-block;flex-shrink:0;"></span>Always open</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8.5px;display:flex;align-items:center;gap:6px;"><span style="width:9px;height:9px;border-radius:50%;border:1.5px solid #4B5563;display:inline-block;flex-shrink:0;"></span>Open at selected hours</div>' +
                        '<div class="amai-cp-mock-btn-fb" style="margin-top:auto;">Next</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business</div>' +
                        '<div style="font-size:7.5px;color:#9CA3AF;text-align:center;margin-top:3px;">Always open</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Photo & Cover',
                tip:   'First impressions happen before anyone reads a word',
                inst:  '<strong>Step 2 of 5 - Customize your Page.</strong> Upload a <strong>Profile picture</strong> (your logo works perfectly) and a <strong>Cover photo</strong> (a job site, your team, or a branded banner). Drag to reposition the cover after uploading.',
                note:  'A blank profile picture makes your page look like a bot. Every post we publish shows your profile picture next to it in the feed.',
                noteType: 'warn',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="gap:6px;">' +
                        '<div class="amai-cp-mock-sidebar-sub" style="color:#4ADE80;font-weight:600;font-size:8px;">Step 2 of 5 - Customize your Page</div>' +
                        '<div class="amai-cp-mock-sidebar-sub" style="margin-bottom:2px;">Your profile picture is one of the first things people see.</div>' +
                        '<div class="amai-cp-mock-upload-box amai-cp-hl" style="margin-bottom:6px;">+ Add profile picture</div>' +
                        '<div class="amai-cp-mock-upload-box">+ Add cover photo</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover" style="background:#252839;display:flex;align-items:center;justify-content:center;"><span style="font-size:8px;color:#4B5563;">Cover photo</span></div>' +
                        '<div class="amai-cp-mock-preview-avatar" style="background:#1877F2;display:flex;align-items:center;justify-content:center;"><span style="font-size:7px;color:#fff;font-weight:700;">YB</span></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Action Button',
                tip:   '"Call now" wins for most service businesses',
                inst:  'On the same screen, click <strong>Action Button</strong>. A panel opens with options. For most service businesses, pick <strong>Call now</strong> under "Get people to contact you", enter your phone number, and click <strong>Save</strong>.',
                note:  'This puts a \'Call now\' button directly on your page. Customers tap it on mobile and your phone rings - no extra clicks.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="gap:4px;">' +
                        '<div class="amai-cp-mock-sidebar-sub" style="color:#4ADE80;font-weight:600;font-size:8px;">Action button</div>' +
                        '<div class="amai-cp-mock-sidebar-sub" style="margin-bottom:4px;">Get people to contact you</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8px;display:flex;align-items:center;gap:5px;"><span style="width:9px;height:9px;border-radius:50%;border:1.5px solid #4B5563;display:inline-block;flex-shrink:0;"></span>Send message</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8px;display:flex;align-items:center;gap:5px;"><span style="width:9px;height:9px;border-radius:50%;border:1.5px solid #4B5563;display:inline-block;flex-shrink:0;"></span>Send WhatsApp message</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl" style="font-size:8px;display:flex;align-items:center;gap:5px;"><span style="width:9px;height:9px;border-radius:50%;border:2px solid #1877F2;background:#1877F2;display:inline-block;flex-shrink:0;"></span>Call now</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl" style="font-size:8px;color:#E2E8F0;">+1 555-867-5309</div>' +
                        '<div class="amai-cp-mock-btn-fb" style="margin-top:auto;">Save</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover"></div>' +
                        '<div class="amai-cp-mock-preview-avatar"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business</div>' +
                        '<div style="background:#1877F2;color:#fff;font-size:8px;font-weight:600;padding:3px 8px;border-radius:3px;margin-top:5px;text-align:center;">Call now</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Done',
                tip:   'Come straight back here when you\'re done',
                inst:  'Facebook shows Steps 3, 4, and 5 - <strong>WhatsApp</strong>, <strong>Invite friends</strong>, and <strong>Notifications</strong>. Skip all three. Click <strong>Next</strong> or <strong>Skip</strong> through to the end, then click <strong>Done</strong>. Your page is ready - come back here and click <strong>Connect with Facebook</strong>.',
                note:  'Your page doesn\'t need to be perfect. AutoMarketer AI will help you grow it from here.',
                noteType: 'success',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span style="background:#FF5F57"></span><span style="background:#FFBD2E"></span><span style="background:#28C840"></span></div><div class="amai-cp-mock-url">facebook.com/pages/creation</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar" style="gap:6px;">' +
                        '<div class="amai-cp-mock-sidebar-sub" style="color:#4ADE80;font-weight:600;font-size:8px;">Step 5 of 5</div>' +
                        '<div class="amai-cp-mock-sidebar-title" style="font-size:10px;">Stay informed about your Page</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled" style="font-size:8px;display:flex;align-items:center;justify-content:space-between;">Page notifications<span style="background:#1877F2;width:22px;height:12px;border-radius:6px;display:inline-block;flex-shrink:0;"></span></div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty" style="font-size:8px;display:flex;align-items:center;justify-content:space-between;">Marketing emails<span style="background:#3D4160;width:22px;height:12px;border-radius:6px;display:inline-block;flex-shrink:0;"></span></div>' +
                        '<div class="amai-cp-mock-btn-fb amai-cp-hl" style="margin-top:auto;">Done</div>' +
                        '</div>' +
                        '<div class="amai-cp-mock-preview">' +
                        '<div class="amai-cp-mock-preview-label">Desktop Preview</div>' +
                        '<div class="amai-cp-mock-preview-cover" style="background:#1A3A5C;"></div>' +
                        '<div class="amai-cp-mock-preview-avatar" style="background:#1877F2;"></div>' +
                        '<div class="amai-cp-mock-preview-name">Your Business</div>' +
                        '<div style="font-size:7.5px;color:#4ADE80;text-align:center;margin-top:3px;">Page health: Good</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
        ];

        function cpRender() {
            var total = cpSteps.length;
            var step  = cpSteps[cpCur];
            var pct   = total <= 1 ? 100 : Math.round((cpCur / (total - 1)) * 88 + 12);

            var labHtml = '';
            cpSteps.forEach(function (s, i) {
                var cls = i === cpCur ? 'active' : (i < cpCur ? 'done' : '');
                labHtml += '<span class="amai-cp-lbl ' + cls + '">' + s.label + '</span>';
            });
            cpLabels.innerHTML = labHtml;
            cpFill.style.width = pct + '%';
            cpCounter.textContent = 'Step ' + (cpCur + 1) + ' of ' + total;
            cpTip.textContent = step.tip;

            var noteCls = 'amai-cp-note';
            if (step.noteType === 'success') { noteCls = 'amai-cp-success'; }
            if (step.noteType === 'warn')    { noteCls = 'amai-cp-warn'; }

            var noteHtml = step.note ? '<div class="' + noteCls + '">' + step.note + '</div>' : '';
            var bioBtn     = step.bioButton ? '<button type="button" class="amai-cp-bio-btn" id="amai-cp-bio-trigger">\u2728 Write my bio with AI</button>' : '';

            cpBody.innerHTML =
                '<div class="amai-cp-step">' +
                '<div class="amai-cp-headline">' + step.label + '</div>' +
                '<div class="amai-cp-text">' + step.inst + '</div>' +
                step.mockup() +
                noteHtml +
                bioBtn +
                '</div>';

            cpBack.disabled = cpCur === 0;
            var isLast = cpCur === total - 1;
            cpNext.style.display = isLast ? 'none' : '';

            if (cpGoFb)   { cpGoFb.style.display   = 'none'; }
            if (cpGoConn) { cpGoConn.style.display  = isLast ? 'inline-flex' : 'none'; }
        }

        function cpOpen() {
            cpCur = 0;
            cpRender();
            cpModal.classList.add('show');
        }

        function cpCloseModal() {
            cpModal.classList.remove('show');
        }

        document.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('amai-create-page-trigger')) {
                e.preventDefault();
                cpOpen();
            }

        // Bio writer mini-modal
        document.addEventListener('click', function (e) {
            var bioTrigger = e.target && e.target.closest ? e.target.closest('#amai-cp-bio-trigger') : null;
            if (bioTrigger) {
                var bioModal = document.getElementById('amai-bio-modal');
                if (!bioModal) { return; }
                document.getElementById('amai-biom-result').style.display = 'none';
                var errEl = document.getElementById('amai-biom-error');
                errEl.style.display = 'none';
                errEl.textContent = '';
                document.getElementById('amai-bio-output').value = '';
                var genBtn = document.getElementById('amai-bio-generate');
                genBtn.textContent = 'Generate bio';
                genBtn.disabled = false;
                var nameField = document.getElementById('amai-bio-biz-name');
                var siteField = document.getElementById('amai-bio-website');
                if (nameField && !nameField.value && amaiSocial.pageName) { nameField.value = amaiSocial.pageName; }
                if (siteField && !siteField.value && amaiSocial.websiteUrl) { siteField.value = amaiSocial.websiteUrl; }
                // Pre-fill from existing dashboard bio if present
                var dashBio = document.getElementById('amai-bio-textarea');
                var modalOutput = document.getElementById('amai-bio-output');
                var modalResult = document.getElementById('amai-biom-result');
                if (dashBio && dashBio.value.trim() && modalOutput && modalResult) {
                    modalOutput.value = dashBio.value.trim();
                    modalResult.style.display = 'block';
                }
                bioModal.style.display = 'flex';
            }
        });
        document.addEventListener('click', function (e) {
            if (e.target && e.target.id === 'amai-bio-modal-close') {
                document.getElementById('amai-bio-modal').style.display = 'none';
            }
        });
        document.addEventListener('click', function (e) {
            if (e.target && e.target.id === 'amai-bio-generate') {
                var website = document.getElementById('amai-bio-website').value.trim();
                var bizName = document.getElementById('amai-bio-biz-name').value.trim();
                var genBtn  = document.getElementById('amai-bio-generate');
                var errEl   = document.getElementById('amai-biom-error');
                var resEl   = document.getElementById('amai-biom-result');
                errEl.style.display = 'none';
                errEl.textContent = '';
                resEl.style.display = 'none';
                genBtn.textContent = 'Generating...';
                genBtn.disabled = true;
                var xhr = new XMLHttpRequest();
                xhr.open('POST', amaiSocial.ajaxUrl);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function () {
                    genBtn.textContent = 'Generate bio';
                    genBtn.disabled = false;
                    try {
                        var r = JSON.parse(xhr.responseText);
                        if (r.success && r.data && r.data.bio) {
                            document.getElementById('amai-bio-output').value = r.data.bio;
                            resEl.style.display = 'flex';
                        } else {
                            errEl.textContent = (r.data && r.data.message) ? r.data.message : 'Generation failed - please try again.';
                            errEl.style.display = 'block';
                        }
                    } catch (ex) {
                        errEl.textContent = 'Unexpected error - please try again.';
                        errEl.style.display = 'block';
                    }
                };
                xhr.onerror = function () {
                    genBtn.textContent = 'Generate bio';
                    genBtn.disabled = false;
                    errEl.textContent = 'Connection error - please try again.';
                    errEl.style.display = 'block';
                };
                xhr.send('action=amai_generate_fb_bio&_wpnonce=' + encodeURIComponent(amaiSocial.bioNonce) + '&website_url=' + encodeURIComponent(website) + '&business_name_override=' + encodeURIComponent(bizName));
            }
        });
        document.addEventListener('click', function (e) {
            if (e.target && e.target.id === 'amai-bio-copy') {
                var text = document.getElementById('amai-bio-output').value;
                if (!text) { return; }
                var copyBtn = document.getElementById('amai-bio-copy');
                // Always close after 1.2s regardless of clipboard API outcome
                copyBtn.textContent = 'Copied!';
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(text).catch(function () {
                        try { document.getElementById('amai-bio-output').select(); document.execCommand('copy'); } catch (ignored) {}
                    });
                } else {
                    try { document.getElementById('amai-bio-output').select(); document.execCommand('copy'); } catch (ignored) {}
                }
                setTimeout(function () {
                    amaiSyncBioToDashboard(text);
                    document.getElementById('amai-bio-modal').style.display = 'none';
                }, 1200);
            }
        });
        });

        cpClose.addEventListener('click', cpCloseModal);

        cpNext.addEventListener('click', function () {
            if (cpCur < cpSteps.length - 1) { cpCur++; cpRender(); }
        });
        cpBack.addEventListener('click', function () {
            if (cpCur > 0) { cpCur--; cpRender(); }
        });

        if (cpGoConn) {
            cpGoConn.addEventListener('click', function () { cpCloseModal(); });
        }

        document.addEventListener('keydown', function (e) {
            if (!cpModal.classList.contains('show')) { return; }
        if (e.key === 'Escape') { var bm = document.getElementById('amai-bio-modal'); if (bm && bm.style.display !== 'none') { bm.style.display = 'none'; return; } cpCloseModal(); }
            if (e.key === 'ArrowRight') { cpNext.click(); }
            if (e.key === 'ArrowLeft')  { cpBack.click(); }
        });

    } // end cpModal block

    // =====================================================
    // TIKTOK CREATE ACCOUNT WALKTHROUGH
    // =====================================================
    var tkCpModal = document.getElementById('amai-create-tk-modal');
    if (tkCpModal) {
        var tkClose   = document.getElementById('amai-tk-cp-close');
        var tkBack    = document.getElementById('amai-tk-cp-back');
        var tkNext    = document.getElementById('amai-tk-cp-next');
        var tkDone    = document.getElementById('amai-tk-cp-done');
        var tkBody    = document.getElementById('amai-tk-cp-body');
        var tkLabels  = document.getElementById('amai-tk-cp-labels');
        var tkFill    = document.getElementById('amai-tk-cp-fill');
        var tkCounter = document.getElementById('amai-tk-cp-counter');
        var tkTip     = document.getElementById('amai-tk-cp-tip');
        var tkCur     = 0;

        var tkSteps = [
            {
                label: 'Get TikTok',
                tip:   'Works on phone, tablet, or computer',
                inst:  '<strong>On your phone:</strong> Download the TikTok app from the <a href="https://apps.apple.com/app/tiktok/id835599320" target="_blank" rel="noopener noreferrer" class="amai-cp-link">App Store</a> or <a href="https://play.google.com/store/apps/details?id=com.zhiliaoapp.musically" target="_blank" rel="noopener noreferrer" class="amai-cp-link">Google Play</a>.<br><br><strong>On your computer:</strong> Go to <a href="https://www.tiktok.com/signup" target="_blank" rel="noopener noreferrer" class="amai-cp-link">tiktok.com/signup</a> and create your account there. Everything works the same way.',
                note:  'If you already have the app or a TikTok account, skip ahead to Step 3.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span></span><span></span><span></span></div><div class="amai-cp-mock-url">tiktok.com/signup</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar amai-cp-mock-full">' +
                        '<div class="amai-cp-mock-sidebar-title amai-cp-mock-center">Sign up for TikTok</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-center-text">Use phone or email</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-center-text">Continue with Google</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-center-text">Continue with Facebook</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Create Account',
                tip:   'Use an email you check regularly',
                inst:  'Sign up with your <strong>email</strong>, <strong>phone number</strong>, or an existing <strong>Google</strong> or <strong>Facebook</strong> account. Pick a username that matches your business name - keep it simple and recognizable. Add a profile photo (your logo works great).',
                note:  'Use the same email you use for your business. If you sign up on a computer, the account works on the app too - and vice versa.',
                noteType: 'info',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span></span><span></span><span></span></div><div class="amai-cp-mock-url">tiktok.com</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar amai-cp-mock-full">' +
                        '<div class="amai-cp-mock-sidebar-title">Edit profile</div>' +
                        '<div class="amai-cp-mock-upload-box amai-cp-hl amai-cp-mock-avatar-circle">+ Photo</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl">@yourbusiness</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled">Your Business Name</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-mock-field-tall">Your 80-character bio goes here</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Switch to Business',
                tip:   'This unlocks posting through AutoMarketer AI',
                inst:  '<strong>On the app:</strong> Go to your <strong>Profile</strong> tab, tap the <strong>three lines</strong> (top right), tap <strong>Settings and privacy</strong>, then <strong>Manage account</strong>, then <strong>Switch to Business Account</strong>. Pick the category that fits your business.<br><br><strong>On your computer:</strong> Go to <a href="https://www.tiktok.com/setting" target="_blank" rel="noopener noreferrer" class="amai-cp-link">tiktok.com/setting</a>, click <strong>Manage account</strong>, then <strong>Switch to Business Account</strong>.',
                note:  'A Business Account is free and gives you access to analytics, a contact button, and the ability to connect with tools like AutoMarketer AI. If you don\'t see Switch to Business Account, you\'re already on one.',
                noteType: 'warn',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span></span><span></span><span></span></div><div class="amai-cp-mock-url">tiktok.com/setting</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar amai-cp-mock-full">' +
                        '<div class="amai-cp-mock-sidebar-title">Settings and privacy</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty">Manage account</div>' +
                        '<div class="amai-cp-mock-sidebar-title amai-cp-mock-mt">Manage account</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl">Switch to Business Account</div>' +
                        '<div class="amai-cp-mock-sidebar-title amai-cp-mock-mt">Choose a category</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-radio"><span class="amai-cp-mock-radio-dot"></span>Professional Services</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-filled amai-cp-hl amai-cp-mock-radio"><span class="amai-cp-mock-radio-dot amai-cp-mock-radio-dot--active"></span>Local Business</div>' +
                        '<div class="amai-cp-mock-field amai-cp-mock-field-empty amai-cp-mock-radio"><span class="amai-cp-mock-radio-dot"></span>Retail</div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
            {
                label: 'Done',
                tip:   'Come straight back here when you are done',
                inst:  'That is it - your TikTok Business Account is ready. Come back here and click <strong>Connect with TikTok</strong> to link your account to AutoMarketer AI. We will start creating posts for you right away.',
                note:  'Your account does not need to be perfect. AutoMarketer AI will help you grow it from here.',
                noteType: 'success',
                mockup: function () {
                    return '<div class="amai-cp-mock">' +
                        '<div class="amai-cp-mock-chrome"><div class="amai-cp-mock-dots"><span></span><span></span><span></span></div><div class="amai-cp-mock-url">tiktok.com/@yourbusiness</div></div>' +
                        '<div class="amai-cp-mock-screen">' +
                        '<div class="amai-cp-mock-sidebar amai-cp-mock-full amai-cp-mock-center">' +
                        '<div class="amai-cp-mock-upload-box amai-cp-hl amai-cp-mock-avatar-circle amai-cp-mock-avatar-done">YB</div>' +
                        '<div class="amai-cp-mock-sidebar-title amai-cp-mock-center">@yourbusiness</div>' +
                        '<div class="amai-cp-mock-sidebar-sub amai-cp-mock-center">Your Business Name</div>' +
                        '<div class="amai-cp-mock-sidebar-sub amai-cp-mock-center amai-cp-mock-bio-text">Your 80-character bio goes here</div>' +
                        '<div class="amai-cp-mock-stats"><span>0 Following</span><span>0 Followers</span><span>0 Likes</span></div>' +
                        '</div>' +
                        '</div></div>';
                },
            },
        ];

        function tkRender() {
            var total = tkSteps.length;
            var step  = tkSteps[tkCur];
            var pct   = total <= 1 ? 100 : Math.round((tkCur / (total - 1)) * 88 + 12);

            var labHtml = '';
            tkSteps.forEach(function (s, i) {
                var cls = i === tkCur ? 'active' : (i < tkCur ? 'done' : '');
                labHtml += '<span class="amai-cp-lbl ' + cls + '">' + s.label + '</span>';
            });
            tkLabels.innerHTML = labHtml;
            tkFill.style.width = pct + '%';
            tkCounter.textContent = 'Step ' + (tkCur + 1) + ' of ' + total;
            tkTip.textContent = step.tip;

            var noteCls = 'amai-cp-note';
            if (step.noteType === 'success') { noteCls = 'amai-cp-success'; }
            if (step.noteType === 'warn')    { noteCls = 'amai-cp-warn'; }

            var noteHtml = step.note ? '<div class="' + noteCls + '">' + step.note + '</div>' : '';

            tkBody.innerHTML =
                '<div class="amai-cp-step">' +
                '<div class="amai-cp-headline">' + step.label + '</div>' +
                '<div class="amai-cp-text">' + step.inst + '</div>' +
                step.mockup() +
                noteHtml +
                '</div>';

            tkBack.disabled = tkCur === 0;
            var isLast = tkCur === total - 1;
            tkNext.style.display = isLast ? 'none' : '';
            if (tkDone) { tkDone.style.display = isLast ? 'inline-flex' : 'none'; }
        }

        function tkOpen() {
            tkCur = 0;
            tkRender();
            tkCpModal.classList.add('show');
        }

        function tkCloseModal() {
            tkCpModal.classList.remove('show');
        }

        document.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('amai-create-tk-trigger')) {
                e.preventDefault();
                tkOpen();
            }
        });

        tkClose.addEventListener('click', tkCloseModal);
        tkNext.addEventListener('click', function () {
            if (tkCur < tkSteps.length - 1) { tkCur++; tkRender(); }
        });
        tkBack.addEventListener('click', function () {
            if (tkCur > 0) { tkCur--; tkRender(); }
        });
        if (tkDone) {
            tkDone.addEventListener('click', function () { tkCloseModal(); });
        }
        document.addEventListener('keydown', function (e) {
            if (!tkCpModal.classList.contains('show')) { return; }
            if (e.key === 'Escape') { tkCloseModal(); }
            if (e.key === 'ArrowRight') { tkNext.click(); }
            if (e.key === 'ArrowLeft')  { tkBack.click(); }
        });
    } // end tkCpModal block

    // =====================================================
    // POST PANEL — clean mode-driven state machine
    // =====================================================

    var postPanel      = document.getElementById('amai-post-panel');
    var panelBackdrop  = document.getElementById('amai-post-panel-backdrop');
    var panelClose     = document.getElementById('amai-panel-close');
    var panelEyebrow   = document.getElementById('amai-panel-eyebrow');
    var panelTitle     = document.getElementById('amai-panel-title');
    var panelStatus    = document.getElementById('amai-panel-status');
    var panelContent   = document.getElementById('amai-panel-content');
    var panelStats    = document.getElementById('amai-panel-stats');
    var statLikes     = document.getElementById('amai-stat-likes');
    var statComments  = document.getElementById('amai-stat-comments');
    var statReach     = document.getElementById('amai-stat-reach');
    var panelTextarea  = document.getElementById('amai-panel-textarea');
    var panelCharCount = document.getElementById('amai-panel-char-count');

    // Mode containers
    var modeDraft        = document.getElementById('amai-mode-draft');
    var modeApproved     = document.getElementById('amai-mode-approved');
    var modeRejected     = document.getElementById('amai-mode-rejected');
    var modeEditing      = document.getElementById('amai-mode-editing');
    var modeRejecting    = document.getElementById('amai-mode-rejecting');
    var modeRegenerating = document.getElementById('amai-mode-regenerating');
    var modeReadonly     = document.getElementById('amai-mode-readonly');
    var modeFailed       = document.getElementById('amai-mode-failed');
    var modePosting      = document.getElementById('amai-mode-posting');
    var modePosted       = document.getElementById('amai-mode-posted');
    var allModes = [modeDraft, modeApproved, modeRejected, modeEditing, modeRejecting, modeRegenerating, modeReadonly, modeFailed, modePosting, modePosted];

    // Buttons
    var btnApprove              = document.getElementById('amai-panel-approve');
    var btnReject               = document.getElementById('amai-panel-reject');
    var btnEdit                 = document.getElementById('amai-panel-edit');
    var btnUnapproveReject      = document.getElementById('amai-panel-unapprove-reject');
    var btnUnapproveEdit        = document.getElementById('amai-panel-unapprove-edit');
    var btnKeepApproved         = document.getElementById('amai-panel-keep-approved');
    var btnRestore              = document.getElementById('amai-panel-restore');
    var btnRestoreEdit          = document.getElementById('amai-panel-restore-edit');
    var btnKeepRejected         = document.getElementById('amai-panel-keep-rejected');
    var btnApproveFromRejected  = document.getElementById('amai-panel-approve-from-rejected');
    var btnEditCancel           = document.getElementById('amai-panel-edit-cancel');
    var btnSave                 = document.getElementById('amai-panel-save');
    var btnSaveApprove          = document.getElementById('amai-panel-save-approve');
    var btnReasonCancel         = document.getElementById('amai-panel-reason-cancel');
    var btnReasonSkip           = document.getElementById('amai-panel-reason-skip');
    var btnReasonConfirm        = document.getElementById('amai-panel-reason-confirm');
    var inputReason             = document.getElementById('amai-panel-reason-input');
    var btnRegen                = document.getElementById('amai-panel-regen');
    var selectRegenType         = document.getElementById('amai-panel-regen-type');
    var btnRegenEdit            = document.getElementById('amai-panel-regen-edit');
    var selectRegenTypeEdit     = document.getElementById('amai-panel-regen-type-edit');

    var activePostId          = null;
    var activePostType        = null;
    var activeStatus          = null;
    var activeActionNonce     = null;
    var activeSaveNonce       = null;
    var activeRegenNonce      = null;
    var activePostNowNonce    = null;
    var activeUploadNonce     = null;
    var activeIsCurrentWeek   = false;
    var activeGenerationBatch = '';
    var activeImageUrl        = '';
    var activeEditImageUrl    = '';
    var activeEditImageCredit = '';
    var activeFeeling         = '';
    var dash_el        = document.querySelector('.amai-fbdash');
    var page_channel  = dash_el ? (dash_el.dataset.channel || 'facebook') : 'facebook';
    var FB_CHAR_LIMIT = (page_channel === 'instagram' || page_channel === 'tiktok') ? 2200 : (page_channel === 'x' ? 280 : (page_channel === 'google' ? 1500 : 63206));
    var CHAR_LIMIT_DISPLAY = (page_channel === 'instagram' || page_channel === 'tiktok') ? '2,200' : (page_channel === 'x' ? '280' : '63,206');

    var POST_TYPE_LABELS = {
        'educational':   'Educational',
        'product':       'Product',
        'feel_good':     'Feel-good',
        'behind_scenes': 'Behind scenes',
        'engagement':    'Engagement'
    };

    if (postPanel) {

        // --------------------------------------------------
        // Core: set mode
        // --------------------------------------------------
        function panelSetMode(mode) {
            allModes.forEach(function (el) { if (el) { el.style.display = 'none'; } });
            var target = {
                'draft':         modeDraft,
                'approved':      modeApproved,
                'rejected':      modeRejected,
                'editing':       modeEditing,
                'rejecting':     modeRejecting,
                'regenerating':  modeRegenerating,
                'readonly':      modeReadonly,
                'failed':        modeFailed,
                'posting':       modePosting,
                'posted':        modePosted,
            }[mode];
            if (target) { target.style.display = ''; }

            var isEditing = (mode === 'editing');
            panelContent.style.display   = isEditing ? 'none' : '';
            var taWrap = document.getElementById('amai-textarea-wrap');
            if (taWrap) { taWrap.style.display = isEditing ? '' : 'none'; }
            panelCharCount.style.display = isEditing ? '' : 'none';
            var editImgBlock = document.getElementById('amai-edit-img-block');
            if (editImgBlock) { editImgBlock.style.display = isEditing ? '' : 'none'; }
            var viewImageEl = document.getElementById('amai-panel-view-image');
            if (viewImageEl) { viewImageEl.style.display = (isEditing || activeImageUrl === '') ? 'none' : ''; }
        }

        // --------------------------------------------------
        // Open panel
        // --------------------------------------------------
        function panelOpen(row) {
            activePostId          = row.dataset.postId || null;
            activePostType        = row.dataset.postType || '';
            activeStatus          = row.dataset.postStatus || '';
            activeActionNonce     = row.dataset.actionNonce || '';
            activeSaveNonce       = row.dataset.saveNonce || '';
            activeRegenNonce      = row.dataset.regenNonce || '';
            activePostNowNonce    = row.dataset.postNowNonce || '';
            activeUploadNonce     = row.dataset.uploadNonce || '';
            activeIsCurrentWeek   = row.dataset.isCurrentWeek === '1';
            activeGenerationBatch = row.dataset.generationBatch || '';
            activeImageUrl        = row.dataset.postImageUrl || row.dataset.unsplashUrl || '';
            activeFeeling              = row.dataset.feeling || '';
            var unsplashUrl            = row.dataset.unsplashUrl || '';
            var unsplashCredit         = row.dataset.unsplashCredit || '';
            var unsplashAttachmentId   = row.dataset.unsplashAttachmentId || '0';

            var postTypeLabel = row.dataset.postTypeLabel || '';
            var content       = row.dataset.postContent || '';
            var date          = row.dataset.scheduledDate || '';
            var soc           = window.amaiSocial || {};
            var postImageUrl  = row.dataset.postImageUrl || row.dataset.unsplashUrl || '';

            panelEyebrow.textContent = postTypeLabel;
            panelTitle.textContent   = date;
            panelContent.textContent = content;
            var viewImg = document.getElementById('amai-panel-view-image');
            var viewImgEl = document.getElementById('amai-panel-view-img');
            if (viewImg && viewImgEl) {
                if (activeImageUrl) {
                    viewImgEl.src = activeImageUrl;
                    viewImg.style.display = '';
                } else {
                    viewImgEl.src = '';
                    viewImg.style.display = 'none';
                }
            }
            var statsFetched = row.dataset.statsFetched === '1';
            if (panelStats) {
                if (statsFetched) {
                    var _likes    = row.dataset.statLikes    !== '' ? parseInt(row.dataset.statLikes,    10) : 0;
                    var _comments = row.dataset.statComments !== '' ? parseInt(row.dataset.statComments, 10) : 0;
                    var _reach    = row.dataset.statReach    !== '' ? parseInt(row.dataset.statReach,    10) : 0;
                    var _hasStats = _likes > 0 || _comments > 0 || _reach > 0;
                    if (_hasStats) {
                        if (statLikes)    { statLikes.textContent    = _likes    > 0 ? String(_likes)    : '0'; }
                        if (statComments) { statComments.textContent = _comments > 0 ? String(_comments) : '0'; }
                        if (statReach)    { statReach.textContent    = _reach    > 0 ? String(_reach)    : '—'; }
                        panelStats.style.display = '';
                    } else {
                        panelStats.style.display = 'none';
                    }
                } else {
                    panelStats.style.display = 'none';
                }
            }
            panelTextarea.value      = content;

            // Instagram preview -- reset
            var igPostPreviewReset = document.getElementById('amai-ig-post-preview');
            var igPreviewBtnReset  = document.getElementById('amai-ig-preview-btn');
            if (igPostPreviewReset) { igPostPreviewReset.style.display = 'none'; }
            if (igPreviewBtnReset)  { igPreviewBtnReset.textContent = 'Show preview'; }

            // X preview -- reset
            var xPostPreviewReset = document.getElementById('amai-x-post-preview');
            var xPreviewBtnReset  = document.getElementById('amai-x-preview-btn');
            if (xPostPreviewReset) { xPostPreviewReset.style.display = 'none'; }
            if (xPreviewBtnReset)  { xPreviewBtnReset.textContent = 'Show preview'; }

            // Facebook post preview -- reset and populate from row data
            var fbPreviewBtnReset = document.getElementById('amai-fb-preview-btn');
            var fbPostPreviewReset = document.getElementById('amai-fb-post-preview');
            var viewImgReset = document.getElementById('amai-panel-view-image');
            if (fbPostPreviewReset) { fbPostPreviewReset.style.display = 'none'; }
            if (fbPreviewBtnReset) { fbPreviewBtnReset.textContent = 'Show preview'; }
            if (viewImgReset) { viewImgReset.style.display = ''; }

            // Facebook post preview -- populate from row data
            var fbPreviewToggle = document.getElementById('amai-fb-preview-toggle');
            var fbPostPreview   = document.getElementById('amai-fb-post-preview');
            if (fbPreviewToggle) {
                fbPreviewToggle.style.display = '';
                if (fbPostPreview) { fbPostPreview.style.display = 'none'; }
            }
            var fbpName   = document.getElementById('amai-fbp-name');
            var fbpAvatar = document.getElementById('amai-fbp-avatar');
            var fbpCopy   = document.getElementById('amai-fbp-copy');
            var fbpImgWrap = document.getElementById('amai-fbp-image-wrap');
            var fbpImg    = document.getElementById('amai-fbp-image');
            if (fbpName)   { fbpName.textContent = soc.pageName || ''; }
            if (fbpAvatar) {
                if (soc.pageAvatarUrl) { fbpAvatar.src = soc.pageAvatarUrl; fbpAvatar.style.display = ''; }
                else { fbpAvatar.style.display = 'none'; }
            }
            if (fbpCopy)   { fbpCopy.textContent = content || ''; }
            if (fbpImgWrap && fbpImg) {
                if (postImageUrl) {
                    fbpImg.src = postImageUrl;
                    fbpImgWrap.style.display = '';
                } else {
                    fbpImgWrap.style.display = 'none';
                }
            }

            if (selectRegenType)     { selectRegenType.value = ''; }
            if (selectRegenTypeEdit) { selectRegenTypeEdit.value = ''; }
            enrichHide();
            enrichResetToValues(activeImageUrl, activeFeeling);
            unsplashBlockReset(unsplashUrl, unsplashCredit, unsplashAttachmentId);
            editImgReset(activeImageUrl, unsplashUrl, unsplashCredit);

            panelStatus.textContent = activeStatus.charAt(0).toUpperCase() + activeStatus.slice(1);
            panelStatus.className   = 'amai-post-panel-status status-' + activeStatus;

            var dash = document.querySelector('.amai-fbdash');
            var isAutopilot = dash && dash.dataset.approvalMode === 'autopilot';

            if (activeStatus === 'posted' && activeGenerationBatch === 'manual') {
                panelSetMode('posted');
            } else if (activeStatus === 'failed' && activeIsCurrentWeek) {
                panelSetMode('failed');
            } else if (isAutopilot) {
                panelSetMode('readonly');
            } else {
                panelSetMode(activeStatus === 'draft'     ? 'draft'    :
                             activeStatus === 'approved'  ? 'approved' :
                             activeStatus === 'rejected'  ? 'rejected' : 'draft');
            }

            document.querySelectorAll('.amai-feed-row').forEach(function (r) {
                r.classList.remove('selected');
            });
            // Shared social preview data

            // Instagram preview -- populate
            var igPreviewToggle = document.getElementById('amai-ig-preview-toggle');
            if (igPreviewToggle) { igPreviewToggle.style.display = ''; }
            var igpUsername = document.getElementById('amai-igp-username');
            var igpAvatar   = document.getElementById('amai-igp-avatar');
            var igpCaption  = document.getElementById('amai-igp-caption');
            var igpImgWrap  = document.getElementById('amai-igp-image-wrap');
            var igpImg      = document.getElementById('amai-igp-image');
            if (igpUsername) { igpUsername.textContent = soc.pageName || ''; }
            if (igpAvatar) {
                if (soc.pageAvatarUrl) { igpAvatar.src = soc.pageAvatarUrl; igpAvatar.style.display = ''; }
                else { igpAvatar.style.display = 'none'; }
            }
            if (igpCaption) { igpCaption.textContent = content || ''; }
            if (igpImgWrap && igpImg) {
                if (postImageUrl) { igpImg.src = postImageUrl; igpImgWrap.style.display = ''; }
                else { igpImgWrap.style.display = 'none'; }
            }

            // X preview -- populate
            var xPreviewToggle = document.getElementById('amai-x-preview-toggle');
            if (xPreviewToggle) { xPreviewToggle.style.display = ''; }
            var xpDisplayName = document.getElementById('amai-xp-display-name');
            var xpHandle      = document.getElementById('amai-xp-handle');
            var xpAvatar      = document.getElementById('amai-xp-avatar');
            var xpCopy        = document.getElementById('amai-xp-copy');
            var xpImgWrap     = document.getElementById('amai-xp-image-wrap');
            var xpImg         = document.getElementById('amai-xp-image');
            if (xpDisplayName) { xpDisplayName.textContent = soc.xDisplayName || ''; }
            if (xpHandle)      { xpHandle.textContent = soc.xUsername ? '@' + soc.xUsername : ''; }
            if (xpAvatar) {
                if (soc.xAvatarUrl) { xpAvatar.src = soc.xAvatarUrl; xpAvatar.style.display = ''; }
                else { xpAvatar.style.display = 'none'; }
            }
            if (xpCopy)   { xpCopy.textContent = content || ''; }
            if (xpImgWrap && xpImg) {
                if (postImageUrl) { xpImg.src = postImageUrl; xpImgWrap.style.display = ''; }
                else { xpImgWrap.style.display = 'none'; }
            }


            row.classList.add('selected');

            postPanel.classList.add('open');
            postPanel.setAttribute('aria-hidden', 'false');
        }

        // Facebook preview toggle button
        var fbPreviewBtn = document.getElementById('amai-fb-preview-btn');
        if (fbPreviewBtn) {
            fbPreviewBtn.addEventListener('click', function () {
                var preview = document.getElementById('amai-fb-post-preview');
                if (!preview) { return; }
                var isOpen = preview.style.display !== 'none';
                preview.style.display = isOpen ? 'none' : '';
                fbPreviewBtn.textContent = isOpen ? 'Show preview' : 'Hide preview';
                var fbPanelContent  = document.getElementById('amai-panel-content');
                var fbStandaloneImg = document.getElementById('amai-panel-view-image');
                if (fbPanelContent)  { fbPanelContent.style.display  = isOpen ? '' : 'none'; }
                if (fbStandaloneImg) { fbStandaloneImg.style.display = isOpen ? '' : 'none'; }
            });
        }

        // Instagram preview toggle button
        var igPreviewBtn = document.getElementById('amai-ig-preview-btn');
        if (igPreviewBtn) {
            igPreviewBtn.addEventListener('click', function () {
                var preview = document.getElementById('amai-ig-post-preview');
                var viewImg = document.getElementById('amai-panel-view-image');
                if (!preview) { return; }
                var isOpen = preview.style.display !== 'none';
                preview.style.display = isOpen ? 'none' : '';
                igPreviewBtn.textContent = isOpen ? 'Show preview' : 'Hide preview';
                if (viewImg) { viewImg.style.display = isOpen ? '' : 'none'; }
                var igPanelContent = document.getElementById('amai-panel-content');
                if (igPanelContent) { igPanelContent.style.display = isOpen ? '' : 'none'; }
            });
        }

        // X preview toggle button
        var xPreviewBtn = document.getElementById('amai-x-preview-btn');
        if (xPreviewBtn) {
            xPreviewBtn.addEventListener('click', function () {
                var preview = document.getElementById('amai-x-post-preview');
                var viewImg = document.getElementById('amai-panel-view-image');
                if (!preview) { return; }
                var isOpen = preview.style.display !== 'none';
                preview.style.display = isOpen ? 'none' : '';
                xPreviewBtn.textContent = isOpen ? 'Show preview' : 'Hide preview';
                if (viewImg) { viewImg.style.display = isOpen ? '' : 'none'; }
                var xPanelContent = document.getElementById('amai-panel-content');
                if (xPanelContent) { xPanelContent.style.display = isOpen ? '' : 'none'; }
            });
        }

        // Close panel
        // --------------------------------------------------
        function panelClose_() {
            postPanel.classList.remove('open');
            postPanel.setAttribute('aria-hidden', 'true');
            document.querySelectorAll('.amai-feed-row').forEach(function (r) {
                r.classList.remove('selected');
            });
            activePostId = null;
        }

        // --------------------------------------------------
        // Helpers
        // --------------------------------------------------
        function panelSetLoading(btn, loading) {
            if (!btn) { return; }
            btn.disabled = loading;
            if (loading) {
                btn.dataset.origText = btn.textContent;
                btn.textContent = '…';
            } else {
                btn.textContent = btn.dataset.origText || btn.textContent;
            }
        }

        function panelUpdateCard(postId, newStatus, newContent, newPostType) {
            var row = document.querySelector('.amai-feed-row[data-post-id="' + postId + '"]');
            if (!row) { return; }
            row.dataset.postStatus = newStatus;
            if (newContent !== undefined) {
                row.dataset.postContent = newContent;
                var preview = row.querySelector('.amai-feed-preview');
                if (preview) {
                    preview.textContent = newContent;
                }
            }
            if (newPostType !== undefined) {
                row.dataset.postType      = newPostType;
                row.dataset.postTypeLabel = POST_TYPE_LABELS[newPostType] || newPostType;
                var pill = row.querySelector('.amai-feed-pill:first-child');
                if (pill) {
                    pill.className = 'amai-feed-pill amai-feed-pill--' + newPostType;
                    pill.textContent = POST_TYPE_LABELS[newPostType] || newPostType;
                }
            }
            var dot   = row.querySelector('.amai-feed-status-dot');
            var label = row.querySelector('.amai-feed-status-label');
            if (dot)   { dot.className   = 'amai-feed-status-dot amai-feed-status-dot--' + newStatus; }
            if (label) { label.textContent = newStatus.charAt(0).toUpperCase() + newStatus.slice(1); }
        }

        function updateCharCount() {
            var len = panelTextarea.value.length;
            panelCharCount.textContent = len + ' / ' + CHAR_LIMIT_DISPLAY + ' characters';
            panelCharCount.classList.toggle('over-limit', len > FB_CHAR_LIMIT);
        }

        function doAction(action, extraData, onSuccess, btn) {
            panelSetLoading(btn, true);
            var fd = new FormData();
            fd.append('action', 'amai_fb_post_action');
            fd.append('_wpnonce', activeActionNonce);
            fd.append('post_id', activePostId);
            fd.append('post_action', action);
            if (extraData) {
                Object.keys(extraData).forEach(function (k) { fd.append(k, extraData[k]); });
            }
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                panelSetLoading(btn, false);
                if (data && data.success) {
                    onSuccess(data);
                } else {
                    if (btn) {
                        var orig = btn.dataset.origText || btn.textContent;
                        btn.textContent = 'Error - try again';
                        setTimeout(function () { btn.textContent = orig; }, 2500);
                    }
                }
            })
            .catch(function () { panelSetLoading(btn, false); });
        }

        // --------------------------------------------------
        // Shared regen logic
        // --------------------------------------------------
        function doRegen(chosenType, returnMode) {
            panelSetMode('regenerating');

            var fd = new FormData();
            fd.append('action', 'amai_fb_post_regenerate');
            fd.append('_wpnonce', activeRegenNonce);
            fd.append('post_id', activePostId);
            if (chosenType !== '') {
                fd.append('post_type', chosenType);
            }

            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success && data.data) {
                    var newContent = data.data.post_content || '';
                    var newType    = data.data.post_type    || activePostType;
                    var newLabel   = POST_TYPE_LABELS[newType] || newType;

                    panelContent.textContent = newContent;
                    panelTextarea.value      = newContent;
                    panelEyebrow.textContent = newLabel;
                    activeStatus             = 'draft';
                    activePostType           = newType;
                    panelStatus.textContent  = 'Draft';
                    panelStatus.className    = 'amai-post-panel-status status-draft';

                    if (selectRegenType)     { selectRegenType.value = ''; }
                    if (selectRegenTypeEdit) { selectRegenTypeEdit.value = ''; }

                    panelUpdateCard(activePostId, 'draft', newContent, newType);
                    panelSetMode(returnMode || 'draft');
                } else {
                    panelSetMode(returnMode || 'draft');
                    var errBtn = returnMode === 'editing' ? btnRegenEdit : btnRegen;
                    if (errBtn) {
                        errBtn.textContent = 'Error - try again';
                        setTimeout(function () { errBtn.textContent = 'Regenerate'; }, 3000);
                    }
                }
            })
            .catch(function () {
                panelSetMode(returnMode || 'draft');
                var errBtn = returnMode === 'editing' ? btnRegenEdit : btnRegen;
                if (errBtn) {
                    errBtn.textContent = 'Network error';
                    setTimeout(function () { errBtn.textContent = 'Regenerate'; }, 3000);
                }
            });
        }

        // --------------------------------------------------
        // Open on row click
        // --------------------------------------------------
        document.addEventListener('click', function (e) {
            var row = e.target.closest('.amai-feed-row[data-post-id]');
            if (row) { panelOpen(row); }
        });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                var row = e.target.closest('.amai-feed-row[data-post-id]');
                if (row) { e.preventDefault(); panelOpen(row); }
            }
            if (e.key === 'Escape' && postPanel.classList.contains('open')) { panelClose_(); }
        });

        panelClose.addEventListener('click', panelClose_);
        panelBackdrop.addEventListener('click', panelClose_);

        // --------------------------------------------------
        // DRAFT mode
        // --------------------------------------------------
        if (btnApprove) {
            btnApprove.addEventListener('click', function () {
                doAction('approve', null, function () {
                    panelUpdateCard(activePostId, 'approved');
                    panelClose_();
                }, btnApprove);
            });
        }

        if (btnReject) {
            btnReject.addEventListener('click', function () {
                if (inputReason) { inputReason.value = ''; }
                panelSetMode('rejecting');
                if (inputReason) { setTimeout(function () { inputReason.focus(); }, 50); }
            });
        }

        if (btnEdit) {
            btnEdit.addEventListener('click', function () {
                panelTextarea.value = panelContent.textContent;
                updateCharCount();
                panelSetMode('editing');
                enrichShow();
                panelTextarea.focus();
            });
        }

        if (btnRegen) {
            btnRegen.addEventListener('click', function () {
                var chosenType = selectRegenType ? selectRegenType.value : '';
                doRegen(chosenType, 'draft');
            });
        }

        // --------------------------------------------------
        // APPROVED mode
        // --------------------------------------------------
        if (btnKeepApproved) {
            btnKeepApproved.addEventListener('click', function () { panelClose_(); });
        }

        if (btnUnapproveReject) {
            btnUnapproveReject.addEventListener('click', function () {
                if (inputReason) { inputReason.value = ''; }
                panelSetMode('rejecting');
                if (inputReason) { setTimeout(function () { inputReason.focus(); }, 50); }
            });
        }

        if (btnUnapproveEdit) {
            btnUnapproveEdit.addEventListener('click', function () {
                panelTextarea.value = panelContent.textContent;
                updateCharCount();
                panelSetMode('editing');
                enrichShow();
                panelTextarea.focus();
            });
        }

        // --------------------------------------------------
        // REJECTED mode
        // --------------------------------------------------
        if (btnKeepRejected) {
            btnKeepRejected.addEventListener('click', function () { panelClose_(); });
        }

        if (btnApproveFromRejected) {
            btnApproveFromRejected.addEventListener('click', function () {
                doAction('approve', null, function () {
                    panelUpdateCard(activePostId, 'approved');
                    panelClose_();
                }, btnApproveFromRejected);
            });
        }

        if (btnRestore) {
            btnRestore.addEventListener('click', function () {
                doAction('draft', null, function () {
                    panelUpdateCard(activePostId, 'draft');
                    panelClose_();
                }, btnRestore);
            });
        }

        if (btnRestoreEdit) {
            btnRestoreEdit.addEventListener('click', function () {
                panelTextarea.value = panelContent.textContent;
                updateCharCount();
                panelSetMode('editing');
                enrichShow();
                panelTextarea.focus();
            });
        }

        // --------------------------------------------------
        // EDITING mode
        // --------------------------------------------------
        panelTextarea.addEventListener('input', updateCharCount);

        if (btnEditCancel) {
            btnEditCancel.addEventListener('click', function () {
                enrichHide();
                panelSetMode(activeStatus === 'approved' ? 'approved' :
                             activeStatus === 'rejected' ? 'rejected' : 'draft');
            });
        }

        function doSave(newContent, approveAfter, btn) {
            if (newContent === '' || newContent.length > FB_CHAR_LIMIT) { return; }
            panelSetLoading(btn, true);
            var fd = new FormData();
            fd.append('action', 'amai_fb_post_save');
            fd.append('_wpnonce', activeSaveNonce);
            fd.append('post_id', activePostId);
            fd.append('post_content', newContent);
            fd.append('post_image_url', activeEditImageUrl !== '' ? activeEditImageUrl : (activeImageUrl || ''));
            fd.append('feeling', activeFeeling || '');
            fd.append('unsplash_attachment_id', activeUnsplashAccepted ? (activeUnsplashId || '0') : '0');
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                panelSetLoading(btn, false);
                if (data && data.success) {
                    panelContent.textContent = newContent;
                    panelUpdateCard(activePostId, 'draft', newContent);
                    enrichHide();
                    activeImageUrl = activeEditImageUrl;
                    var savedRow = document.querySelector('.amai-feed-row[data-post-id="' + activePostId + '"]');
                    if (savedRow) { savedRow.dataset.postImageUrl = activeEditImageUrl; }
                    panelUpdateMetaSummary(activeImageUrl, activeFeeling);
                    if (approveAfter) {
                        doAction('approve', null, function () {
                            panelUpdateCard(activePostId, 'approved');
                            panelClose_();
                        }, null);
                    } else {
                        activeStatus = 'draft';
                        panelStatus.textContent = 'Draft';
                        panelStatus.className   = 'amai-post-panel-status status-draft';
                        panelSetMode('draft');
                    }
                } else {
                    var orig = btn ? (btn.dataset.origText || btn.textContent) : '';
                    if (btn) {
                        btn.textContent = 'Error - try again';
                        setTimeout(function () { btn.textContent = orig; }, 2500);
                    }
                }
            })
            .catch(function () { panelSetLoading(btn, false); });
        }

        if (btnSave) {
            btnSave.addEventListener('click', function () {
                doSave(panelTextarea.value.trim(), false, btnSave);
            });
        }

        if (btnSaveApprove) {
            btnSaveApprove.addEventListener('click', function () {
                doSave(panelTextarea.value.trim(), true, btnSaveApprove);
            });
        }

        if (btnRegenEdit) {
            btnRegenEdit.addEventListener('click', function () {
                var chosenType = selectRegenTypeEdit ? selectRegenTypeEdit.value : '';
                doRegen(chosenType, 'editing');
            });
        }

        // --------------------------------------------------
        // REJECTING mode
        // --------------------------------------------------
        if (inputReason) {
            inputReason.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') { e.preventDefault(); doReject(inputReason.value.trim()); }
                if (e.key === 'Escape') { panelSetMode(activeStatus === 'approved' ? 'approved' : 'draft'); }
            });
        }

        if (btnReasonCancel) {
            btnReasonCancel.addEventListener('click', function () {
                panelSetMode(activeStatus === 'approved' ? 'approved' : 'draft');
            });
        }

        if (btnReasonSkip) {
            btnReasonSkip.addEventListener('click', function () { doReject(''); });
        }

        if (btnReasonConfirm) {
            btnReasonConfirm.addEventListener('click', function () {
                doReject(inputReason ? inputReason.value.trim() : '');
            });
        }

        function doReject(reason) {
            var extra = reason !== '' ? { rejection_reason: reason } : null;
            doAction('reject', extra, function () {
                panelUpdateCard(activePostId, 'rejected');
                panelClose_();
            }, btnReasonConfirm);
        }

        // Switch-to-review from read-only panel footer
        var btnSwitchToReview = document.getElementById('amai-panel-switch-to-review');
    var btnPostNow        = document.getElementById('amai-panel-post-now');
    var btnFailedDismiss  = document.getElementById('amai-panel-failed-dismiss');
        if (btnSwitchToReview) {
            btnSwitchToReview.addEventListener('click', function () {
                var dash = document.querySelector('.amai-fbdash');
                if (dash) { dash.dataset.approvalMode = 'review'; }

                var seg = document.getElementById('amai-approval-seg');
                if (seg) {
                    seg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                        b.classList.toggle('active', b.dataset.mode === 'review');
                    });
                    var nonce = seg.dataset.nonce || '';
                    var fd = new FormData();
                    fd.append('action', 'amai_save_approval_mode');
                    fd.append('_wpnonce', nonce);
                    fd.append('mode', 'review');
                    fetch(window.ajaxurl || (window.amaiSocial && window.amaiSocial.ajaxUrl) || '/wp-admin/admin-ajax.php', {
                        method: 'POST', credentials: 'same-origin', body: fd,
                    }).catch(function () {});
                }

                var hint = document.getElementById('amai-approval-hint');
                if (hint) { hint.textContent = 'Posts need your sign-off before they go out. Click any post to review it.'; }

                panelClose_();
            });
        }

        // --------------------------------------------------
        // FAILED mode — Post Now
        // --------------------------------------------------
        function doPostNow() {
            panelSetMode('posting');
            var fd = new FormData();
            fd.append('action', 'amai_fb_post_now');
            fd.append('_wpnonce', activePostNowNonce);
            fd.append('post_id', activePostId);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success) {
                    panelUpdateCard(activePostId, 'posted');
                    panelClose_();
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Something went wrong. Please try again.';
                    panelSetMode('failed');
                    if (btnPostNow) {
                        btnPostNow.textContent = 'Error - try again';
                        setTimeout(function () { btnPostNow.textContent = 'Post now'; }, 3000);
                    }
                }
            })
            .catch(function () {
                panelSetMode('failed');
                if (btnPostNow) {
                    btnPostNow.textContent = 'Network error';
                    setTimeout(function () { btnPostNow.textContent = 'Post now'; }, 3000);
                }
            });
        }

        if (btnPostNow) {
            btnPostNow.addEventListener('click', function () {
                doPostNow();
            });
        }

        if (btnFailedDismiss) {
            btnFailedDismiss.addEventListener('click', function () {
                panelClose_();
            });
        }

        // ── POSTED mode — Duplicate ──
        var btnDuplicate = document.getElementById('amai-panel-duplicate');
        if (btnDuplicate) {
            btnDuplicate.addEventListener('click', function () {
                var postContent = panelContent.textContent || '';
                if (!postContent) { return; }
                try {
                    sessionStorage.setItem('amai_compose_prefill', JSON.stringify({
                        content: postContent,
                        feeling: activeFeeling || '',
                    }));
                } catch (e) {}
                var composeUrl = (window.amaiSocial && window.amaiSocial.composeUrl) ||
                    '/wp-admin/admin.php?page=automarketer-ai-social&channel=facebook&tab=compose';
                window.location.href = composeUrl;
            });
        }

    } // end postPanel block

    // =====================================================
    // APPROVAL MODE SEGMENTED CONTROL
    // =====================================================

    var approvalSeg   = document.getElementById('amai-approval-seg');
    var approvalHint  = document.getElementById('amai-approval-hint');

    var HINT_REVIEW   = 'Posts need your sign-off before they go out. Click any post to review it.';
    var HINT_AUTO     = 'Posts go out automatically at their scheduled time. Click any post to read it.';

    if (approvalSeg) {
        approvalSeg.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-approval-seg-btn');
            if (!btn) { return; }

            var newMode = btn.dataset.mode || '';
            if (!newMode || btn.classList.contains('active')) { return; }

            // Optimistic UI update
            approvalSeg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                b.classList.remove('active');
            });
            btn.classList.add('active');

            var dash = document.querySelector('.amai-fbdash');
            if (dash) { dash.dataset.approvalMode = newMode; }

            if (approvalHint) {
                approvalHint.textContent = newMode === 'autopilot' ? HINT_AUTO : HINT_REVIEW;
            }

            // Persist via AJAX
            var nonce = approvalSeg.dataset.nonce || '';
            var fd = new FormData();
            fd.append('action', 'amai_save_approval_mode');
            fd.append('_wpnonce', nonce);
            fd.append('mode', newMode);

            fetch(window.ajaxurl || (window.amaiSocial && window.amaiSocial.ajaxUrl) || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                credentials: 'same-origin',
                body: fd,
            })
            .then(function (r) { return r.json(); })
            .catch(function () {});
        });
    }



    // =====================================================
    // ENRICHMENT FIELDS — toolbar, image, location, feeling, emoji
    // =====================================================

    var enrichPanel   = document.getElementById('amai-panel-enrichments');
    var metaSummary   = document.getElementById('amai-panel-meta-summary');

    // Toolbar buttons
    var btnEnrichImg      = document.getElementById('amai-enrich-btn-img');
    var btnEnrichFeeling  = document.getElementById('amai-enrich-btn-feeling');
    var btnEnrichEmoji    = document.getElementById('amai-enrich-btn-emoji');

    // Image
    var imageInput        = document.getElementById('amai-image-input');
    var imageStrip        = document.getElementById('amai-image-strip');
    var imageStripPreview = document.getElementById('amai-image-strip-preview');
    var imageStripRemove  = document.getElementById('amai-image-strip-remove');
    var imageUploading    = document.getElementById('amai-image-uploading-strip');
    var imgChip           = document.getElementById('amai-img-chip');
    var imgChipRemove     = document.getElementById('amai-img-chip-remove');


    // Feeling modal
    var feelingModal      = document.getElementById('amai-feeling-modal');
    var feelingModalClose = document.getElementById('amai-feeling-modal-close');
    var feelingModalGrid  = document.getElementById('amai-feeling-modal-grid');
    var feelingChip       = document.getElementById('amai-feeling-chip');
    var feelingChipRemove = document.getElementById('amai-feeling-chip-remove');

    // Emoji
    var emojiDropdown     = document.getElementById('amai-emoji-dropdown');
    var emojiCats         = document.getElementById('amai-emoji-cats');
    var emojiGrid         = document.getElementById('amai-emoji-grid');

    // --------------------------------------------------
    // Show / hide enrichment panel
    // --------------------------------------------------
    function enrichShow() {
        if (enrichPanel) { enrichPanel.style.display = ''; }
    }

    function enrichHide() {
        if (enrichPanel)    { enrichPanel.style.display = 'none'; }
        if (emojiDropdown)  { emojiDropdown.style.display = 'none'; }
        if (feelingModal)   { feelingModal.classList.remove('show'); }
    }

    // --------------------------------------------------
    // Reset enrichment fields to stored values
    // --------------------------------------------------
    function enrichResetToValues(imgUrl, feeling) {
        activeImageUrl        = imgUrl    || '';
        activeFeeling         = feeling   || '';

        // Image
        if (imgUrl) {
            if (imageStripPreview) { imageStripPreview.src = imgUrl; }
            if (imageStrip)    { imageStrip.style.display    = ''; }
            if (imageUploading){ imageUploading.style.display = 'none'; }
            setImgChip(imgUrl);
        } else {
            if (imageStrip)    { imageStrip.style.display    = 'none'; }
            if (imageUploading){ imageUploading.style.display = 'none'; }
            setImgChip('');
        }


        // Feeling
        setFeelingChip(feeling || '');

        // Emoji — close picker
        if (emojiDropdown) { emojiDropdown.style.display = 'none'; }
        if (btnEnrichEmoji){ btnEnrichEmoji.classList.remove('active'); }
    }

    // --------------------------------------------------
    // Chip helpers
    // --------------------------------------------------
    function setImgChip(url) {
        if (!imgChip) { return; }
        if (url) {
            imgChip.style.display = '';
            if (btnEnrichImg) { btnEnrichImg.classList.add('active'); }
        } else {
            imgChip.style.display = 'none';
            if (btnEnrichImg) { btnEnrichImg.classList.remove('active'); }
        }
    }


    function setFeelingChip(value) {
        if (!feelingChip) { return; }
        if (value && FEELING_LABELS[value]) {
            feelingChip.querySelector('.amai-enrich-chip-label').textContent = FEELING_LABELS[value];
            feelingChip.style.display = '';
            if (btnEnrichFeeling) { btnEnrichFeeling.classList.add('active'); }
            // Mark active in modal grid
            if (feelingModalGrid) {
                feelingModalGrid.querySelectorAll('.amai-feeling-option').forEach(function (b) {
                    b.classList.toggle('active', b.dataset.feeling === value);
                });
            }
        } else {
            feelingChip.style.display = 'none';
            if (btnEnrichFeeling) { btnEnrichFeeling.classList.remove('active'); }
            if (feelingModalGrid) {
                feelingModalGrid.querySelectorAll('.amai-feeling-option').forEach(function (b) {
                    b.classList.remove('active');
                });
            }
        }
    }

    // --------------------------------------------------
    // Unsplash suggested image block
    // --------------------------------------------------
    var unsplashBlock      = document.getElementById('amai-unsplash-block');
    var unsplashImg        = document.getElementById('amai-unsplash-img');
    var unsplashCreditEl   = document.getElementById('amai-unsplash-credit');
    var unsplashActions    = document.getElementById('amai-unsplash-actions');
    var unsplashAccepted   = document.getElementById('amai-unsplash-accepted');
    var btnUnsplashAccept  = document.getElementById('amai-unsplash-btn-accept');
    var btnUnsplashRemove  = document.getElementById('amai-unsplash-btn-remove');
    var btnUnsplashUndo    = document.getElementById('amai-unsplash-btn-undo');
    var activeUnsplashId   = '0';
    var activeUnsplashAccepted = false;

    function unsplashBlockReset(url, credit, attachmentId) {
        activeUnsplashId       = attachmentId || '0';
        activeUnsplashAccepted = (activeUnsplashId !== '0');
        if (!unsplashBlock) { return; }
        if (activeUnsplashAccepted) {
            unsplashBlock.style.display = 'none';
            return;
        }
        if (!url || url === '') {
            unsplashBlock.style.display = 'none';
            return;
        }
        if (unsplashImg)      { unsplashImg.src = url; }
        if (unsplashCreditEl && credit) {
            var parts = credit.split('|');
            var name  = parts[0] || '';
            var link  = parts[1] || '';
            unsplashCreditEl.innerHTML = 'Photo by <a href="' + escHtml(link) + '?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener noreferrer">' + escHtml(name) + '</a> on <a href="https://unsplash.com?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener noreferrer">Unsplash</a>';
        }
        if (activeUnsplashAccepted) {
            if (unsplashActions)  { unsplashActions.style.display = 'none'; }
            if (unsplashAccepted) { unsplashAccepted.style.display = ''; }
        } else {
            if (unsplashActions)  { unsplashActions.style.display = ''; }
            if (unsplashAccepted) { unsplashAccepted.style.display = 'none'; }
        }
        unsplashBlock.style.display = '';
    }

    if (btnUnsplashAccept) {
        btnUnsplashAccept.addEventListener('click', function () {
            activeUnsplashAccepted = true;
            if (unsplashActions)  { unsplashActions.style.display = 'none'; }
            if (unsplashAccepted) { unsplashAccepted.style.display = ''; }
            if (!activePostId || !activeSaveNonce) { return; }
            var fd = new FormData();
            fd.append('action', 'amai_fb_unsplash_update');
            fd.append('_wpnonce', activeSaveNonce);
            fd.append('post_id', activePostId);
            fd.append('unsplash_attachment_id', activeUnsplashId || '0');
            var acceptRow = document.querySelector('.amai-feed-row[data-post-id="' + activePostId + '"]');
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', { method: 'POST', body: fd })
                .then(function () { if (acceptRow) { acceptRow.dataset.unsplashAttachmentId = activeUnsplashId || '0'; } })
                .catch(function () {});
        });
    }

    if (btnUnsplashUndo) {
        btnUnsplashUndo.addEventListener('click', function () {
            activeUnsplashAccepted = false;
            if (unsplashActions)  { unsplashActions.style.display = ''; }
            if (unsplashAccepted) { unsplashAccepted.style.display = 'none'; }
        });
    }

    if (btnUnsplashRemove) {
        btnUnsplashRemove.addEventListener('click', function () {
            activeUnsplashId = '0';
            activeUnsplashAccepted = false;
            if (unsplashBlock) { unsplashBlock.style.display = 'none'; }
            if (!activePostId || !activeSaveNonce) { return; }
            var fd = new FormData();
            fd.append('action', 'amai_fb_unsplash_update');
            fd.append('_wpnonce', activeSaveNonce);
            fd.append('post_id', activePostId);
            fd.append('unsplash_attachment_id', '0');
            var removeRow = document.querySelector('.amai-feed-row[data-post-id="' + activePostId + '"]');
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', { method: 'POST', body: fd })
                .then(function () { if (removeRow) { removeRow.dataset.unsplashAttachmentId = '0'; removeRow.dataset.unsplashUrl = ''; } })
                .catch(function () {});
        });
    }

    // --------------------------------------------------
    // Meta summary (read view)
    // --------------------------------------------------
    function panelUpdateMetaSummary(imgUrl, locName, feeling) {
        if (!metaSummary) { return; }
        var parts = [];
        if (imgUrl)  { parts.push('<span class="amai-meta-chip amai-meta-chip--image">📷 Photo</span>'); }
        if (feeling) {
            var flabel = FEELING_LABELS[feeling] || feeling;
            parts.push('<span class="amai-meta-chip amai-meta-chip--feeling">' + escHtml(flabel) + '</span>');
        }
        metaSummary.innerHTML = parts.length ? '<div class="amai-meta-chips">' + parts.join('') + '</div>' : '';
    }

    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    var FEELING_LABELS = {
        'HAPPY':        '😊 Happy',
        'EXCITED':      '🤩 Excited',
        'GRATEFUL':     '🙏 Grateful',
        'BLESSED':      '✨ Blessed',
        'MOTIVATED':    '💪 Motivated',
        'PROUD':        '🦁 Proud',
        'THANKFUL':     '💛 Thankful',
        'INSPIRED':     '💡 Inspired',
        'HOPEFUL':      '🌱 Hopeful',
        'DETERMINED':   '🎯 Determined',
        'OPTIMISTIC':   '☀️ Optimistic',
        'CONFIDENT':    '💼 Confident',
        'LOVED':        '❤️ Loved',
        'ACCOMPLISHED': '🏆 Accomplished',
        'ENERGIZED':    '⚡ Energized',
        'FOCUSED':      '🔍 Focused',
        'JOYFUL':       '🎉 Joyful',
        'CELEBRATED':   '🥂 Celebrated',
        'AMBITIOUS':    '🚀 Ambitious',
        'REFRESHED':    '🌿 Refreshed',
        'FANTASTIC':    '🌟 Fantastic',
        'WONDERFUL':    '🦋 Wonderful',
        'POSITIVE':     '👍 Positive',
        'STRONG':       '💥 Strong',
        'THRILLED':     '🎊 Thrilled'
    };

    // --------------------------------------------------
    // IMAGE UPLOAD
    // --------------------------------------------------
    if (btnEnrichImg) {
        btnEnrichImg.addEventListener('click', function () {
            var block = document.getElementById('amai-edit-img-block');
            if (block) {
                block.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        });
    }

    // Legacy strip/chip remove handlers removed — replaced by editImg block

    function doImageUpload(file, onSuccess) {
        editImgSetState('uploading');

        var fd = new FormData();
        fd.append('action', 'amai_fb_image_upload');
        fd.append('_wpnonce', activeUploadNonce);
        fd.append('post_id', activePostId);
        fd.append('image', file);

        fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
            method: 'POST',
            credentials: 'same-origin',
            body: fd,
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (data && data.success && data.data && data.data.url) {
                activeEditImageUrl = data.data.url;
                activeEditImageCredit = '';
                editImgShowHas(data.data.url, '');
                if (onSuccess) { onSuccess(data.data.url); }
            } else {
                editImgSetState('none');
            }
        })
        .catch(function () {
            editImgSetState('none');
        });
    }

    // --------------------------------------------------
    // LOCATION — Google Places Autocomplete
    // --------------------------------------------------

    function locSearch(q) {
        if (!q || q.length < 2) {
            return;
        }
        var fd = new FormData();
        fd.append('action', 'amai_fb_location_search');
        fd.append('_wpnonce', (amaiSocial.locationNonce || ''));
        fd.append('q', q);
        fetch(window.ajaxurl, { method: 'POST', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                if (res.success && res.data && res.data.places) {
                    locShowResults(res.data.places);
                } else {
                    locShowResults([]);
                }
            })
            .catch(function () { locShowResults([]); });
    }


    // FEELING MODAL
    // --------------------------------------------------
    if (btnEnrichFeeling) {
        btnEnrichFeeling.addEventListener('click', function () {
            if (feelingModal) { feelingModal.classList.add('show'); }
        });
    }

    if (feelingModalClose) {
        feelingModalClose.addEventListener('click', function () {
            feelingModal.classList.remove('show');
        });
    }

    if (feelingModal) {
        feelingModal.addEventListener('click', function (e) {
            if (e.target === feelingModal) { feelingModal.classList.remove('show'); }
        });
    }

    if (feelingModalGrid) {
        feelingModalGrid.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-feeling-option');
            if (!btn) { return; }
            activeFeeling = btn.dataset.feeling || '';
            setFeelingChip(activeFeeling);
            feelingModal.classList.remove('show');
        });
    }

    if (feelingChipRemove) {
        feelingChipRemove.addEventListener('click', function () {
            activeFeeling = '';
            setFeelingChip('');
        });
    }

    // --------------------------------------------------
    // EMOJI PICKER
    // --------------------------------------------------
    var EMOJI_DATA = {
        'Smileys':   ['😀','😃','😄','😁','😆','😅','😂','🤣','😊','😇','🙂','🙃','😉','😌','😍','🥰','😘','😗','😙','😚','😋','😛','😝','😜','🤪','🤨','🧐','🤓','😎','🤩','🥳','😏','😒','😞','😔','😟','😕','🙁','☹️','😣','😖','😫','😩','🥺','😢','😭','😤','😠','😡','🤬','🤯','😳','🥵','🥶','😱','😨','😰','😥','😓','🤗','🤔','🤭','🤫','🤥','😶','😐','😑','😬','🙄','😯','😦','😧','😮','😲','🥱','😴','🤤','😪','😵','🤐','🥴','🤢','🤮','🤧','😷','🤒','🤕'],
        'People':    ['👋','🤚','🖐','✋','🖖','👌','🤌','🤏','✌️','🤞','🤟','🤘','🤙','👈','👉','👆','👇','☝️','👍','👎','✊','👊','🤛','🤜','👏','🙌','👐','🤲','🤝','🙏','💅','💪','🦾','🦵','🦶','👂','🦻','👃','👀','👁','👅','👄','💋'],
        'Nature':    ['🐶','🐱','🐭','🐹','🐰','🦊','🐻','🐼','🐨','🐯','🦁','🐮','🐷','🐸','🐵','🐔','🐧','🐦','🦆','🦅','🦉','🦇','🐺','🐴','🦄','🐝','🦋','🐌','🐞','🌵','🎄','🌲','🌳','🌴','🌱','🌿','☘️','🍀','🍃','🍂','🍁','🍄','🌾','💐','🌷','🌹','🌺','🌸','🌼','🌻','🌞','🌝','🌙','🌎','🌍','🌏','💫','⭐','🌟','✨','⚡','❄️','🌈','🔥','💧','🌊'],
        'Food':      ['🍎','🍐','🍊','🍋','🍌','🍉','🍇','🍓','🫐','🍒','🍑','🥭','🍍','🥥','🥝','🍅','🍆','🥑','🥦','🌽','🥕','🧄','🥔','🥐','🍞','🥖','🧀','🥚','🍳','🥞','🧇','🥓','🥩','🍗','🍖','🌭','🍔','🍟','🍕','🥪','🌮','🌯','🥗','🍝','🍜','🍲','🍛','🍣','🍱','🥟','🍤','🍙','🍚','🧁','🍰','🎂','🍩','🍪','🍫','🍿','🍯','☕','🫖','🍵','🍺','🍻','🥂','🍷','🥃','🍸','🍹','🍾'],
        'Travel':    ['🚗','🚕','🚙','🚌','🏎','🚓','🚑','🚒','🚲','🛵','🏍','✈️','💺','🚁','🚀','🛸','🛶','⛵','🚤','🚢','⚓','🗺','🗿','🗽','🗼','🏰','🏯','🎡','🎢','⛲','🏖','🏝','🏜','🏕','⛺','🏠','🏡','🏢','🏥','🏦','🏨','🏪','🏫','🏭','💒','⛪','🕌','🛕','🕍','⛩','🕋','🌁','🌃','🏙','🌄','🌅','🌆','🌇','🌉','🌌','🎇','🎆'],
        'Objects':   ['⌚','📱','💻','🖥','🖨','🖱','💾','💿','📷','📸','📹','🎥','📞','☎️','📺','📻','⏰','🕰','💡','🔦','🕯','💰','💳','💹','📈','📉','📊','📋','📌','📍','📎','📏','📐','✂️','🔒','🔓','🔑','🗝','🔨','⚒','🛠','⚔️','🔧','🔩','⚙️','⚖️','🔗','⚗️','🧪','🧬','🔬','🔭','💊','🩺','🎭','🎨','🖼','🎰','🎲','♟','🧩','🎯','🎱','🔮','🎮','🕹'],
        'Symbols':   ['❤️','🧡','💛','💚','💙','💜','🖤','🤍','🤎','💔','❣️','💕','💞','💓','💗','💖','💘','💝','💯','♻️','✅','☑️','✔️','❎','⭕','🔴','🔵','🟢','🟡','🟠','🟣','⚫','⚪','🔶','🔷','🔸','🔹','🔺','🔻','💠','🔘','⚡','🌟','✨','🎵','🎶','🎤','🎧','🎼','🎹','🥁','🎷','🎺','🎸','🎻','🏆','🥇','🥈','🥉','🎖','🎗','🎫','🎟','🎪','🤹','🎭','🎨','🎬','🎤'],
    };

    var emojiBuilt = false;

    function buildEmojiScroll() {
        var scrollEl = document.getElementById('amai-emoji-grid');
        var stickyEl = document.getElementById('amai-emoji-sticky-cat');
        if (!scrollEl) { return; }
        var html = '';
        Object.keys(EMOJI_DATA).forEach(function (cat) {
            html += '<div class="amai-emoji-section" data-cat="' + cat + '">';
            html += '<div class="amai-emoji-section-header">' + cat + '</div>';
            html += '<div class="amai-emoji-section-grid">';
            EMOJI_DATA[cat].forEach(function (em) {
                html += '<button type="button" class="amai-emoji-item" data-emoji="' + em + '">' + em + '</button>';
            });
            html += '</div></div>';
        });
        scrollEl.innerHTML = html;
        if (stickyEl) {
            stickyEl.textContent = Object.keys(EMOJI_DATA)[0];
            var sections = scrollEl.querySelectorAll('.amai-emoji-section');
            var observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        stickyEl.textContent = entry.target.dataset.cat;
                    }
                });
            }, { root: scrollEl, threshold: 0.2 });
            sections.forEach(function (s) { observer.observe(s); });
            stickyEl.addEventListener('click', function () {
                var cur = stickyEl.textContent.trim();
                var keys = Object.keys(EMOJI_DATA);
                var idx  = keys.indexOf(cur);
                var next = keys[(idx + 1) % keys.length];
                var target = scrollEl.querySelector('.amai-emoji-section[data-cat="' + next + '"]');
                if (target) { target.scrollIntoView({ block: 'start' }); }
            });
        }
    }

    if (btnEnrichEmoji) {
        btnEnrichEmoji.addEventListener('click', function () {
            if (!emojiDropdown) { return; }
            var isOpen = emojiDropdown.style.display !== 'none' && emojiDropdown.style.display !== '';
            if (isOpen) {
                emojiDropdown.style.display = 'none';
                btnEnrichEmoji.classList.remove('active');
            } else {
                if (!emojiBuilt) {
                    buildEmojiScroll();
                    emojiBuilt = true;
                }
                emojiDropdown.style.display = '';
                btnEnrichEmoji.classList.add('active');
            }
        });
    }



    if (emojiGrid) {
        emojiGrid.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-emoji-item');
            if (!btn || !panelTextarea) { return; }
            var emoji = btn.dataset.emoji || '';
            if (!emoji) { return; }
            var start = panelTextarea.selectionStart;
            var end   = panelTextarea.selectionEnd;
            var val   = panelTextarea.value;
            panelTextarea.value = val.slice(0, start) + emoji + val.slice(end);
            panelTextarea.selectionStart = panelTextarea.selectionEnd = start + emoji.length;
            panelTextarea.focus();
            updateCharCount();
        });
    }

    // Close emoji on outside click
    document.addEventListener('click', function (e) {
        if (!emojiDropdown || emojiDropdown.style.display === 'none') { return; }
        if (btnEnrichEmoji && btnEnrichEmoji.contains(e.target)) { return; }
        if (emojiDropdown.contains(e.target)) { return; }
        emojiDropdown.style.display = 'none';
        if (btnEnrichEmoji) { btnEnrichEmoji.classList.remove('active'); }
    });



    // =====================================================
    // EDIT-MODE IMAGE BLOCK — unified for FB + IG
    // =====================================================

    var lastAiPrompt          = '';
    var lastAiImageUrl        = '';

    var editImgBlock            = document.getElementById('amai-edit-img-block');
    var editImgNone             = document.getElementById('amai-edit-img-none');
    var editImgUploading        = document.getElementById('amai-edit-img-uploading');
    var editImgHas              = document.getElementById('amai-edit-img-has');
    var editImgUnsplashState    = document.getElementById('amai-edit-img-unsplash');
    var editImgAiPromptState    = document.getElementById('amai-edit-img-ai-prompt');
    var editImgAiGenerating     = document.getElementById('amai-edit-img-ai-generating');
    var editImgAiPreviewState   = document.getElementById('amai-edit-img-ai-preview');
    var editImgAiErrorState     = document.getElementById('amai-edit-img-ai-error');

    var editImgPreview          = document.getElementById('amai-edit-img-preview');
    var editImgCredit           = document.getElementById('amai-edit-img-credit');
    var editImgRemove           = document.getElementById('amai-edit-img-remove');

    var editImgUnsplashBtn      = document.getElementById('amai-edit-img-unsplash-btn');
    var editImgUnsplashReplBtn  = document.getElementById('amai-edit-img-unsplash-replace-btn');
    var editImgAiBtn            = document.getElementById('amai-edit-img-ai-btn');
    var editImgAiReplBtn        = document.getElementById('amai-edit-img-ai-replace-btn');

    var editImgFileInput        = document.getElementById('amai-image-input');
    var editImgFileInputReplace = document.getElementById('amai-image-input-replace');

    var editImgUnsplashInput    = document.getElementById('amai-edit-img-unsplash-input');
    var editImgUnsplashSearchBtn= document.getElementById('amai-edit-img-unsplash-search-btn');
    var editImgUnsplashCancel   = document.getElementById('amai-edit-img-unsplash-cancel');
    var editImgUnsplashStatus   = document.getElementById('amai-edit-img-unsplash-status');
    var editImgUnsplashGrid     = document.getElementById('amai-edit-img-unsplash-grid');

    var editImgAiTextarea       = document.getElementById('amai-edit-img-ai-textarea');
    var editImgAiCancel         = document.getElementById('amai-edit-img-ai-cancel');
    var editImgAiGenerate       = document.getElementById('amai-edit-img-ai-generate');
    var editImgAiPreviewImg     = document.getElementById('amai-edit-img-ai-preview-img');
    var editImgAiPreviewRow     = document.getElementById('amai-edit-img-ai-preview');
    var editImgAiDiscard        = document.getElementById('amai-edit-img-ai-discard');
    var editImgAiAccept         = document.getElementById('amai-edit-img-ai-accept');
    var editImgAiRetry          = document.getElementById('amai-edit-img-ai-retry');
    var editImgAiErrorCancel    = document.getElementById('amai-edit-img-ai-error-cancel');
    var editImgAiErrorMsg       = document.getElementById('amai-edit-img-ai-error-msg');

    var ALL_EDIT_IMG_STATES = [
        editImgNone, editImgUploading, editImgHas,
        editImgUnsplashState, editImgAiPromptState,
        editImgAiGenerating, editImgAiPreviewState, editImgAiErrorState,
    ];

    function editImgSetState(state) {
        ALL_EDIT_IMG_STATES.forEach(function (el) {
            if (el) { el.style.display = 'none'; }
        });
        var map = {
            'none':         editImgNone,
            'uploading':    editImgUploading,
            'has':          editImgHas,
            'unsplash':     editImgUnsplashState,
            'ai-prompt':    editImgAiPromptState,
            'ai-generating':editImgAiGenerating,
            'ai-preview':   editImgAiPreviewState,
            'ai-error':     editImgAiErrorState,
        };
        var target = map[state];
        if (target) { target.style.display = ''; }
    }

    function editImgShowHas(url, credit) {
        if (editImgPreview)  { editImgPreview.src = url; }
        if (editImgCredit) {
            if (credit && credit !== '') {
                editImgCredit.innerHTML = escHtml(credit);
                editImgCredit.style.display = '';
            } else {
                editImgCredit.style.display = 'none';
            }
        }
        editImgSetState('has');
        setImgChip(url);
    }

    function editImgReset(imageUrl, unsplashUrl, unsplashCredit) {
        activeEditImageUrl    = imageUrl || '';
        activeEditImageCredit = '';
        lastAiPrompt          = '';
        lastAiImageUrl        = '';

        if (!editImgBlock) { return; }

        if (imageUrl && imageUrl !== '') {
            var credit = '';
            if (unsplashUrl && unsplashUrl !== '' && unsplashCredit && unsplashCredit !== '') {
                credit = unsplashCredit;
            }
            editImgShowHas(imageUrl, credit);
        } else {
            editImgSetState('none');
            setImgChip('');
        }
    }

    // --------------------------------------------------
    // Upload — file inputs (none state + replace state)
    // --------------------------------------------------
    if (editImgFileInput) {
        editImgFileInput.addEventListener('change', function () {
            var file = editImgFileInput.files[0];
            if (!file) { return; }
            doImageUpload(file, null);
        });
    }

    if (editImgFileInputReplace) {
        editImgFileInputReplace.addEventListener('change', function () {
            var file = editImgFileInputReplace.files[0];
            if (!file) { return; }
            doImageUpload(file, null);
        });
    }

    // --------------------------------------------------
    // Remove image
    // --------------------------------------------------
    if (editImgRemove) {
        editImgRemove.addEventListener('click', function () {
            activeEditImageUrl    = '';
            activeEditImageCredit = '';
            if (editImgPreview)  { editImgPreview.src = ''; }
            editImgSetState('none');
            setImgChip('');
        });
    }

    // --------------------------------------------------
    // Unsplash flow
    // --------------------------------------------------
    function editImgOpenUnsplash() {
        editImgSetState('unsplash');
        if (editImgUnsplashGrid)  { editImgUnsplashGrid.style.display = 'none'; editImgUnsplashGrid.innerHTML = ''; }
        if (editImgUnsplashStatus){ editImgUnsplashStatus.style.display = 'none'; editImgUnsplashStatus.textContent = ''; }
        if (editImgUnsplashInput) { editImgUnsplashInput.value = ''; editImgUnsplashInput.focus(); }
    }

    if (editImgUnsplashBtn)    { editImgUnsplashBtn.addEventListener('click',    editImgOpenUnsplash); }
    if (editImgUnsplashReplBtn){ editImgUnsplashReplBtn.addEventListener('click', editImgOpenUnsplash); }

    if (editImgUnsplashCancel) {
        editImgUnsplashCancel.addEventListener('click', function () {
            editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
        });
    }

    function editImgDoUnsplashSearch() {
        var kw = editImgUnsplashInput ? editImgUnsplashInput.value.trim() : '';
        if (kw === '') { return; }

        if (editImgUnsplashStatus) {
            editImgUnsplashStatus.textContent = 'Searching…';
            editImgUnsplashStatus.style.display = '';
        }
        if (editImgUnsplashGrid) { editImgUnsplashGrid.style.display = 'none'; editImgUnsplashGrid.innerHTML = ''; }

        var fd = new FormData();
        fd.append('action', 'amai_panel_unsplash_search');
        fd.append('_wpnonce', activeSaveNonce);
        fd.append('post_id', activePostId);
        fd.append('keywords', kw);

        fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
            method: 'POST', credentials: 'same-origin', body: fd,
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (!data || !data.success || !data.data || !data.data.photos || !data.data.photos.length) {
                if (editImgUnsplashStatus) { editImgUnsplashStatus.textContent = 'No photos found. Try different keywords.'; }
                return;
            }
            if (editImgUnsplashStatus) { editImgUnsplashStatus.style.display = 'none'; }
            editImgRenderUnsplashGrid(data.data.photos);
        })
        .catch(function () {
            if (editImgUnsplashStatus) { editImgUnsplashStatus.textContent = 'Search failed. Try again.'; }
        });
    }

    if (editImgUnsplashSearchBtn) {
        editImgUnsplashSearchBtn.addEventListener('click', editImgDoUnsplashSearch);
    }

    if (editImgUnsplashInput) {
        editImgUnsplashInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); editImgDoUnsplashSearch(); }
        });
    }

    function editImgRenderUnsplashGrid(photos) {
        if (!editImgUnsplashGrid) { return; }
        editImgUnsplashGrid.innerHTML = '';
        photos.forEach(function (photo) {
            var item = document.createElement('div');
            item.className = 'amai-edit-img-unsplash-item';
            item.innerHTML =
                '<img src="' + escHtml(photo.thumb_url || photo.url) + '" alt="" loading="lazy"/>' +
                '<div class="amai-edit-img-unsplash-credit-overlay">' + escHtml(photo.photographer_name || '') + '</div>';
            item.addEventListener('click', function () {
                editImgSelectUnsplash(photo);
            });
            editImgUnsplashGrid.appendChild(item);
        });
        editImgUnsplashGrid.style.display = '';
    }

    function editImgSelectUnsplash(photo) {
        // Track download per Unsplash guidelines
        if (photo.download_location) {
            var tfd = new FormData();
            tfd.append('action', 'amai_manual_unsplash_track');
            tfd.append('_wpnonce', activeSaveNonce);
            tfd.append('download_location', photo.download_location);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', { method: 'POST', body: tfd })
                .catch(function () {});
        }

        // Download to media library via upload endpoint, using the full-size URL
        editImgSetState('uploading');

        var fd = new FormData();
        fd.append('action', 'amai_panel_unsplash_search');
        fd.append('_wpnonce', activeSaveNonce);
        fd.append('post_id', activePostId);
        fd.append('keywords', '__download__');

        // Use image proxy: fetch the full URL as a blob then upload
        var fullUrl = photo.full_url || photo.url;
        var credit  = photo.photographer_name ? (photo.photographer_name + '|' + (photo.photographer_url || '')) : '';

        fetch(fullUrl)
            .then(function (r) { return r.blob(); })
            .then(function (blob) {
                var ext = 'jpg';
                if (blob.type === 'image/png') { ext = 'png'; }
                var formFile = new File([blob], 'unsplash-' + Date.now() + '.' + ext, { type: blob.type });
                var ufd = new FormData();
                ufd.append('action', 'amai_fb_image_upload');
                ufd.append('_wpnonce', activeUploadNonce);
                ufd.append('post_id', activePostId);
                ufd.append('image', formFile);
                return fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST', credentials: 'same-origin', body: ufd,
                });
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success && data.data && data.data.url) {
                    activeEditImageUrl    = data.data.url;
                    activeEditImageCredit = credit;
                    editImgShowHas(data.data.url, credit !== '' ? ('Photo by ' + (photo.photographer_name || '')) : '');
                } else {
                    editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
                }
            })
            .catch(function () {
                editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
            });
    }

    // --------------------------------------------------
    // AI generate flow
    // --------------------------------------------------
    function editImgOpenAiPrompt() {
        editImgSetState('ai-prompt');
        if (editImgAiTextarea) {
            if (lastAiPrompt !== '') {
                // Restore previous prompt — user already went through the flow
                editImgAiTextarea.value = lastAiPrompt;
                editImgAiTextarea.focus();
                return;
            }
            // First open — ask the AI to suggest a prompt based on the post content
            editImgAiTextarea.value = '';
            editImgAiTextarea.placeholder = 'Generating suggestion…';
            editImgAiTextarea.disabled = true;
            var fd = new FormData();
            fd.append('action',    'amai_panel_suggest_image_prompt');
            fd.append('_wpnonce', activeSaveNonce);
            fd.append('post_id',  activePostId);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                editImgAiTextarea.disabled = false;
                editImgAiTextarea.placeholder = 'e.g. Cozy small business owner at a desk, warm lighting, minimal background';
                if (data && data.success && data.data && data.data.prompt) {
                    editImgAiTextarea.value = data.data.prompt;
                }
                editImgAiTextarea.focus();
            })
            .catch(function () {
                editImgAiTextarea.disabled = false;
                editImgAiTextarea.placeholder = 'e.g. Cozy small business owner at a desk, warm lighting, minimal background';
                editImgAiTextarea.focus();
            });
        }
    }

    if (editImgAiBtn)     { editImgAiBtn.addEventListener('click',     editImgOpenAiPrompt); }
    if (editImgAiReplBtn) { editImgAiReplBtn.addEventListener('click', editImgOpenAiPrompt); }

    if (editImgAiCancel) {
        editImgAiCancel.addEventListener('click', function () {
            editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
        });
    }

    function editImgDoGenerate() {
        var prompt = editImgAiTextarea ? editImgAiTextarea.value.trim() : '';
        if (prompt === '') { return; }
        lastAiPrompt = prompt;
        editImgSetState('ai-generating');

        var fd = new FormData();
        fd.append('action', 'amai_panel_generate_image');
        fd.append('_wpnonce', activeSaveNonce);
        fd.append('post_id', activePostId);
        fd.append('prompt', prompt);

        fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
            method: 'POST', credentials: 'same-origin', body: fd,
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (data && data.success && data.data && data.data.url) {
                lastAiImageUrl = data.data.url;
                if (editImgAiPreviewImg) { editImgAiPreviewImg.src = data.data.url; }
                editImgSetState('ai-preview');
            } else {
                var msg = (data && data.data && data.data.message) ? data.data.message : 'Generation failed. Try again.';
                if (editImgAiErrorMsg) { editImgAiErrorMsg.textContent = msg; }
                editImgSetState('ai-error');
            }
        })
        .catch(function () {
            if (editImgAiErrorMsg) { editImgAiErrorMsg.textContent = 'Network error. Try again.'; }
            editImgSetState('ai-error');
        });
    }

    if (editImgAiGenerate) {
        editImgAiGenerate.addEventListener('click', editImgDoGenerate);
    }

    if (editImgAiTextarea) {
        editImgAiTextarea.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); editImgDoGenerate(); }
        });
    }

    if (editImgAiDiscard) {
        editImgAiDiscard.addEventListener('click', function () {
            lastAiImageUrl = '';
            editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
        });
    }

    if (editImgAiAccept) {
        editImgAiAccept.addEventListener('click', function () {
            if (!lastAiImageUrl) { return; }
            activeEditImageUrl    = lastAiImageUrl;
            activeEditImageCredit = '';
            editImgShowHas(lastAiImageUrl, '');
            lastAiImageUrl = '';
        });
    }

    if (editImgAiRetry) {
        editImgAiRetry.addEventListener('click', function () {
            editImgSetState('ai-prompt');
            if (editImgAiTextarea && lastAiPrompt !== '') { editImgAiTextarea.value = lastAiPrompt; }
        });
    }

    if (editImgAiErrorCancel) {
        editImgAiErrorCancel.addEventListener('click', function () {
            editImgSetState(activeEditImageUrl !== '' ? 'has' : 'none');
        });
    }

    // --------------------------------------------------
    // doSave reads activeEditImageUrl directly — no wrapper needed.


    // --------------------------------------------------
    // Regenerate week button on generation failure notice
    // --------------------------------------------------
    var regenBtn = document.querySelector('.amai-regen-week-btn');
    if (regenBtn) {
        regenBtn.addEventListener('click', function () {
            var btn     = this;
            var nonce   = btn.getAttribute('data-nonce') || '';
            var channel = btn.getAttribute('data-channel') || 'facebook';
            btn.disabled    = true;
            btn.textContent = 'Regenerating...';
            var fd = new FormData();
            fd.append('action',   'amai_regenerate_week');
            fd.append('_wpnonce', nonce);
            fd.append('channel',  channel);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method:      'POST',
                credentials: 'same-origin',
                body:        fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success) {
                    var notice = document.getElementById('amai-gen-failed-notice');
                    if (notice) { notice.remove(); }
                    window.location.reload();
                } else {
                    btn.disabled    = false;
                    btn.textContent = 'Try again';
                    alert('Regeneration failed. Please try again in a moment.');
                }
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = 'Try again';
                alert('Regeneration failed. Please try again in a moment.');
            });
        });
    }
}());