/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /assets/js/amai-settings.js
   Description: Settings page interactions — email testing, ping, cache flush
   Last Edited: 2026-04-14
   ================================================== */

(function () {
    'use strict';

    var ajaxUrl   = (typeof amaiSettings !== 'undefined') ? amaiSettings.ajaxUrl  : '';
    var nonce     = (typeof amaiSettings !== 'undefined') ? amaiSettings.nonce    : '';

    function showToast(message, type) {
        var toast = document.getElementById('amai-settings-toast');
        if (!toast) { return; }
        toast.textContent = message;
        toast.className   = 'amai-toast amai-toast--' + (type || 'success');
        toast.style.display = 'block';
        clearTimeout(toast._timer);
        toast._timer = setTimeout(function () {
            toast.style.display = 'none';
        }, 4000);
    }

    function setLoading(btn, loading) {
        if (!btn) { return; }
        btn.disabled = loading;
        var labelEl = btn.querySelector('.amai-etpl-smart-btn__label');
        if (labelEl) {
            if (loading) {
                btn.dataset.originalText = labelEl.textContent;
                labelEl.textContent = 'Working...';
            } else {
                labelEl.textContent = btn.dataset.originalText || labelEl.textContent;
            }
        } else {
            if (loading) {
                btn.dataset.originalText = btn.textContent;
                btn.textContent = 'Working...';
            } else {
                btn.textContent = btn.dataset.originalText || btn.textContent;
            }
        }
    }

    function ajax(action, extra, callback) {
        var data = 'action=' + encodeURIComponent(action)
                 + '&_ajax_nonce=' + encodeURIComponent(nonce);
        var keys = Object.keys(extra);
        for (var i = 0; i < keys.length; i++) {
            data += '&' + encodeURIComponent(keys[i]) + '=' + encodeURIComponent(extra[keys[i]]);
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', ajaxUrl);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function () {
            var resp = {};
            try { resp = JSON.parse(xhr.responseText); } catch (e) {}
            callback(resp);
        };
        xhr.onerror = function () {
            callback({ success: false, data: { message: 'Request failed.' } });
        };
        xhr.send(data);
    }

    // --------------------------------------------------
    // Email test buttons -- smart dog-ear edit zone
    // --------------------------------------------------
    var emailBtns = document.querySelectorAll('.amai-test-email-btn');
    emailBtns.forEach(function (btn) {
        btn.addEventListener('mousemove', function (e) {
            var r = btn.getBoundingClientRect();
            var x = e.clientX - r.left;
            var y = e.clientY - r.top;
            var inZone = x > r.width * 0.62 && y > r.height * 0.38;
            if (inZone) {
                btn.classList.add('amai-etpl-smart-btn--edit-zone');
            } else {
                btn.classList.remove('amai-etpl-smart-btn--edit-zone');
            }
        });
        btn.addEventListener('mouseleave', function () {
            btn.classList.remove('amai-etpl-smart-btn--edit-zone');
        });
        btn.addEventListener('click', function () {
            if (btn.classList.contains('amai-etpl-smart-btn--edit-zone')) {
                var editType = btn.dataset.editType;
                if (editType) { etplOpen(String(editType)); }
                btn.classList.remove('amai-etpl-smart-btn--edit-zone');
                return;
            }
            var type = btn.dataset.type;
            setLoading(btn, true);
            ajax('amai_send_test_email', { email_type: type }, function (resp) {
                setLoading(btn, false);
                if (resp.success) {
                    showToast(resp.data.message, 'success');
                } else {
                    showToast(resp.data.message || 'Failed to send.', 'error');
                }
            });
        });
    });

    // --------------------------------------------------
    // Ping Core API
    // --------------------------------------------------
    var pingBtn    = document.getElementById('amai-ping-core-btn');
    var pingResult = document.getElementById('amai-ping-result');

    if (pingBtn) {
        pingBtn.addEventListener('click', function () {
            setLoading(pingBtn, true);
            if (pingResult) {
                pingResult.textContent = '';
                pingResult.className   = 'amai-sysinfo__ping-result';
            }
            ajax('amai_ping_core', {}, function (resp) {
                setLoading(pingBtn, false);
                if (!pingResult) { return; }
                if (resp.success) {
                    pingResult.textContent = resp.data.message;
                    pingResult.className   = 'amai-sysinfo__ping-result amai-sysinfo__ping-result--good';
                } else {
                    pingResult.textContent = resp.data.message || 'Unreachable.';
                    pingResult.className   = 'amai-sysinfo__ping-result amai-sysinfo__ping-result--bad';
                }
            });
        });
    }

    // --------------------------------------------------
    // Flush cache
    // --------------------------------------------------
    var flushBtn = document.getElementById('amai-flush-cache-btn');
    if (flushBtn) {
        flushBtn.addEventListener('click', function () {
            setLoading(flushBtn, true);
            ajax('amai_flush_cache', {}, function (resp) {
                setLoading(flushBtn, false);
                if (resp.success) {
                    showToast(resp.data.message, 'success');
                } else {
                    showToast(resp.data.message || 'Failed.', 'error');
                }
            });
        });
    }

    // --------------------------------------------------
    // Comments -- WordPress/WooCommerce toggle
    // --------------------------------------------------
    var wpCommentsSeg = document.getElementById('amai-wp-comments-seg');
    if (wpCommentsSeg) {
        var wpCommentsNonce = wpCommentsSeg.dataset.nonce || '';
        wpCommentsSeg.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-approval-seg-btn');
            if (!btn) { return; }
            var enabled = btn.dataset.enabled;
            if (enabled === undefined) { return; }
            wpCommentsSeg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                b.classList.toggle('active', b.dataset.enabled === enabled);
            });
            var data = 'action=amai_save_wp_comments_enabled'
                     + '&_ajax_nonce=' + encodeURIComponent(wpCommentsNonce)
                     + '&enabled=' + encodeURIComponent(enabled);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxUrl);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                var resp = {};
                try { resp = JSON.parse(xhr.responseText); } catch (ex) {}
                if (resp.success) {
                    showToast(enabled === '1' ? 'WordPress comments enabled.' : 'WordPress comments disabled.', 'success');
                } else {
                    showToast('Failed to save.', 'error');
                }
            };
            xhr.send(data);
        });
    }
    // --------------------------------------------------
    // Competitor Radar -- add page
    // --------------------------------------------------
    var competitorAddBtn = document.getElementById('amai-competitor-add-btn');
    var competitorUrl    = document.getElementById('amai-competitor-url');
    var competitorMsg    = document.getElementById('amai-competitor-msg');

    function setCompetitorMsg(msg, ok) {
        if (!competitorMsg) { return; }
        competitorMsg.textContent = msg;
        competitorMsg.style.color = ok ? '#22c55e' : '#ef4444';
    }

    if (competitorAddBtn) {
        competitorAddBtn.addEventListener('click', function () {
            var url = competitorUrl ? competitorUrl.value.trim() : '';
            if (!url) { setCompetitorMsg('Enter a Facebook page URL.', false); return; }
            setLoading(competitorAddBtn, true);
            setCompetitorMsg('', true);
            ajax('amai_competitor_add', { page_url: url }, function (resp) {
                setLoading(competitorAddBtn, false);
                if (resp.success) {
                    setCompetitorMsg(resp.data.message, true);
                    if (competitorUrl) { competitorUrl.value = ''; }
                    setTimeout(function () { location.reload(); }, 1200);
                } else {
                    setCompetitorMsg(resp.data.message || 'Failed.', false);
                }
            });
        });
    }

    // --------------------------------------------------
    // Blog approval mode toggle
    // --------------------------------------------------
    var blogApprovalSeg = document.getElementById('amai-blog-approval-seg');
    if (blogApprovalSeg) {
        var blogApprovalNonce = (typeof amaiSettings !== 'undefined') ? amaiSettings.blogApprovalNonce : '';
        blogApprovalSeg.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-approval-seg-btn');
            if (!btn) { return; }
            var mode = btn.dataset.mode;
            if (!mode) { return; }
            blogApprovalSeg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                b.classList.toggle('active', b.dataset.mode === mode);
            });
            var hint = document.getElementById('amai-blog-approval-hint');
            if (hint) {
                hint.textContent = mode === 'autopilot'
                    ? 'We\'ll write and publish automatically. You\'ll get an email when it\'s live.'
                    : 'We\'ll write a draft and notify you. You publish when you\'re ready.';
            }
            var data = 'action=amai_save_blog_approval_mode'
                     + '&_ajax_nonce=' + encodeURIComponent(blogApprovalNonce)
                     + '&mode=' + encodeURIComponent(mode);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxUrl);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                var resp = {};
                try { resp = JSON.parse(xhr.responseText); } catch (ex) {}
                if (resp.success) {
                    showToast(mode === 'autopilot' ? 'Autopilot enabled.' : 'Review mode enabled.', 'success');
                } else {
                    showToast('Failed to save.', 'error');
                }
            };
            xhr.send(data);
        });
    }

    var blogImageSeg = document.getElementById('amai-blog-image-seg');
    if (blogImageSeg) {
        var blogImageNonce = (typeof amaiSettings !== 'undefined') ? amaiSettings.blogImageSourceNonce : '';
        blogImageSeg.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-approval-seg-btn');
            if (!btn) { return; }
            var source = btn.dataset.source;
            if (!source) { return; }
            blogImageSeg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                b.classList.toggle('active', b.dataset.source === source);
            });
            var hint = document.getElementById('amai-blog-image-hint');
            if (hint) {
                hint.textContent = source === 'ai'
                    ? 'AI generates a unique image for each post. Falls back to Unsplash if no image provider is active.'
                    : 'Unsplash finds a relevant photo for each post automatically.';
            }
            var data = 'action=amai_save_blog_image_source'
                     + '&_ajax_nonce=' + encodeURIComponent(blogImageNonce)
                     + '&source=' + encodeURIComponent(source);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxUrl);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                var resp = {};
                try { resp = JSON.parse(xhr.responseText); } catch (ex) {}
                if (resp.success) {
                    showToast(source === 'ai' ? 'AI image generation enabled.' : 'Unsplash enabled.', 'success');
                } else {
                    showToast('Failed to save.', 'error');
                }
            };
            xhr.send(data);
        });
    }

    // --------------------------------------------------
    // Competitor Radar -- remove page
    // --------------------------------------------------
    var competitorList = document.getElementById('amai-competitor-list');
    if (competitorList) {
        competitorList.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-competitor-remove-btn');
            if (!btn) { return; }
            var row = btn.closest('.amai-competitor-row');
            if (!row) { return; }
            var id = row.dataset.id;
            if (!id) { return; }
            setLoading(btn, true);
            ajax('amai_competitor_remove', { competitor_id: id }, function (resp) {
                setLoading(btn, false);
                if (resp.success) {
                    row.remove();
                    showToast('Competitor removed.', 'success');
                } else {
                    showToast(resp.data.message || 'Failed.', 'error');
                }
            });
        });
    }

    // --------------------------------------------------
    // Save SMS provider credentials (Twilio, Plivo, Vonage)
    // --------------------------------------------------
    const saveTwilioBtn = document.getElementById('amai-save-twilio-btn');
    if (saveTwilioBtn) {
        saveTwilioBtn.addEventListener('click', function () {
            var data = {};
            document.querySelectorAll('[data-sms-key]').forEach(function (el) {
                data[el.getAttribute('data-sms-key')] = (el.value || '').trim();
            });
            var missing = Object.values(data).some(function (v) { return v === ''; });
            if (missing) {
                showToast('All fields are required.', 'error');
                return;
            }
            setLoading(saveTwilioBtn, true);
            ajax('amai_save_twilio_credentials', data, function (resp) {
                setLoading(saveTwilioBtn, false);
                if (resp.success) {
                    showToast(resp.data.message, 'success');
                } else {
                    showToast(resp.data.message || 'Failed to save.', 'error');
                }
            });
        });
    }

        // --------------------------------------------------
    // Save nudge thresholds
    // --------------------------------------------------
    var saveNudgeBtn = document.getElementById('amai-save-nudge-thresholds-btn');
    const saveDiscountBtn = document.getElementById('amai-save-recovery-discount-btn');
    if (saveDiscountBtn) {
        saveDiscountBtn.addEventListener('click', function () {
            const enabled = document.getElementById('amai-recovery-discount-enabled').checked ? '1' : '0';
            const pct     = parseInt(document.getElementById('amai-recovery-discount-pct').value, 10);
            const days    = parseInt(document.getElementById('amai-recovery-discount-days').value, 10);
            if (isNaN(pct) || pct < 1 || pct > 100) {
                showToast('Discount must be between 1 and 100.', 'error');
                return;
            }
            if (isNaN(days) || days < 1 || days > 30) {
                showToast('Expiry must be between 1 and 30 days.', 'error');
                return;
            }
            setLoading(saveDiscountBtn, true);
            ajax('amai_save_recovery_discount', { enabled: enabled, discount_pct: pct, discount_days: days }, function (resp) {
                setLoading(saveDiscountBtn, false);
                if (resp.success) {
                    showToast(resp.data.message, 'success');
                } else {
                    showToast(resp.data.message || 'Failed to save.', 'error');
                }
            });
        });
    }

        if (saveNudgeBtn) {
        saveNudgeBtn.addEventListener('click', function () {
            var h1 = document.getElementById('amai-nudge-1-hours');
            var h2 = document.getElementById('amai-nudge-2-hours');
            var h3 = document.getElementById('amai-nudge-3-hours');
            var v1 = h1 ? parseInt(h1.value, 10) : 0;
            var v2 = h2 ? parseInt(h2.value, 10) : 0;
            var v3 = h3 ? parseInt(h3.value, 10) : 0;
            if (!v1 || v1 < 1 || v1 > 720 || !v2 || v2 < 1 || v2 > 720 || !v3 || v3 < 1 || v3 > 720) {
                showToast('Each delay must be between 1 and 720 hours.', 'error');
                return;
            }
            setLoading(saveNudgeBtn, true);
            ajax('amai_save_nudge_thresholds', {
                nudge_1_hours: String(v1),
                nudge_2_hours: String(v2),
                nudge_3_hours: String(v3)
            }, function (resp) {
                setLoading(saveNudgeBtn, false);
                if (resp.success) {
                    showToast(resp.data.message, 'success');
                } else {
                    showToast(resp.data.message || 'Failed to save.', 'error');
                }
            });
        });
    }



    // -- Plugin release --
    function setReleaseMsg(el, type, text) {
        if (!el) { return; }
        el.textContent = text;
        el.className = 'amai-rel-msg amai-rel-msg--' + type;
    }

    function autoGenerateChangelog(version, onDone) {
        var logTa  = document.getElementById('amai-release-changelog');
        var msgEl  = document.getElementById('amai-release-msg');
        var apiKey = (typeof amaiSettings !== 'undefined' && amaiSettings.claudeApiKey) ? amaiSettings.claudeApiKey : '';
        if (!apiKey || !logTa) { if (onDone) { onDone(); } return; }
        setReleaseMsg(msgEl, 'info', 'Generating release notes...');
        var fd = new FormData();
        fd.append('action', 'amai_get_handoffs_since');
        fd.append('_ajax_nonce', amaiSettings.handoffNonce);
        fd.append('since', amaiSettings.lastReleaseDate || '');
        fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
        .then(function(r) { return r.json(); })
        .then(function(resp) {
            if (!resp || !resp.success || !resp.data.entries || !resp.data.entries.length) {
                if (onDone) { onDone(); }
                return;
            }
            var combined = resp.data.entries.join('\n\n---\n\n');
            return fetch('https://api.anthropic.com/v1/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': apiKey,
                    'anthropic-version': '2023-06-01',
                    'anthropic-dangerous-direct-browser-access': 'true'
                },
                body: JSON.stringify({
                    model: 'claude-sonnet-4-20250514',
                    max_tokens: 1024,
                    messages: [{
                        role: 'user',
                        content: 'You are writing release notes for a WordPress plugin called AutoMarketer AI.'
                            + ' Your audience is small business owners - not developers.'
                            + ' Write 3-8 plain-English bullet points summarising what is new or fixed.'
                            + ' Focus only on user-facing improvements. Skip internal refactors and anything technical.'
                            + ' Use plain language. No jargon. No markdown. No headers. Start each line with a hyphen.'
                            + ' Here are the session notes:\n\n' + combined
                    }]
                })
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.content && data.content[0] && data.content[0].text) {
                    logTa.value = data.content[0].text.trim();
                    if (version) {
                        var sfd = new FormData();
                        sfd.append('action', 'amai_save_release_changelog');
                        sfd.append('_ajax_nonce', amaiSettings.saveChangelogNonce);
                        sfd.append('version', version);
                        sfd.append('changelog', logTa.value);
                        fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: sfd })
                        .then(function() { if (onDone) { onDone(); } })
                        .catch(function() { if (onDone) { onDone(); } });
                    } else {
                        if (onDone) { onDone(); }
                    }
                } else {
                    if (onDone) { onDone(); }
                }
            });
        })
        .catch(function() { if (onDone) { onDone(); } });
    }

    // Suggest buttons
    document.querySelectorAll('.amai-rel-suggest-btn').forEach(function(b) {
        b.addEventListener('click', function() {
            var inp = document.getElementById('amai-release-version');
            if (inp) { inp.value = b.dataset.ver; inp.focus(); }
        });
    });

    // Create release
    var relBtn = document.getElementById('amai-create-release-btn');
    var relMsg = document.getElementById('amai-release-msg');
    var relInp = document.getElementById('amai-release-version');
    var relLog = document.getElementById('amai-release-changelog');
    if (relBtn) {
        relBtn.addEventListener('click', function() {
            var version = relInp ? relInp.value.trim() : '';
            if (version === '') { setReleaseMsg(relMsg, 'error', 'Enter a version number.'); return; }
            if (!/^\d+\.\d+\.\d+$/.test(version)) { setReleaseMsg(relMsg, 'error', 'Use x.y.z format (e.g. 1.0.1).'); return; }
            relBtn.disabled = true;
            relBtn.textContent = 'Creating...';
            setReleaseMsg(relMsg, 'info', 'Building ZIP - this may take a few seconds...');
            var fd = new FormData();
            fd.append('action', 'amai_create_release');
            fd.append('_ajax_nonce', relBtn.dataset.nonce);
            fd.append('version', version);
            fd.append('changelog', relLog ? relLog.value.trim() : '');
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                relBtn.disabled = false;
                relBtn.textContent = 'Create package';
                if (data && data.success) {
                    setReleaseMsg(relMsg, 'success', data.data.message);
                    if (relInp) { relInp.value = ''; }
                    if (relLog) { relLog.value = ''; }
                    autoGenerateChangelog(version, function() {
                        setTimeout(function() { window.location.reload(); }, 400);
                    });
                } else {
                    var errMsg = (data && data.data && data.data.message) ? data.data.message : 'Failed. Try again.';
                    setReleaseMsg(relMsg, 'error', errMsg);
                }
            })
            .catch(function() {
                relBtn.disabled = false;
                relBtn.textContent = 'Create package';
                setReleaseMsg(relMsg, 'error', 'Network error. Try again.');
            });
        });
        if (relInp) {
            relInp.addEventListener('keydown', function(e) { if (e.key === 'Enter') { relBtn.click(); } });
        }
    }

    // Make current
    document.querySelectorAll('.amai-rel-make-current-btn').forEach(function(b) {
        b.addEventListener('click', function() {
            if (!confirm('Set ' + b.dataset.zip + ' as the current release? Clients will download this version.')) { return; }
            b.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_make_current_release');
            fd.append('_ajax_nonce', b.dataset.nonce);
            fd.append('zip', b.dataset.zip);
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.success) { window.location.reload(); }
                else { b.disabled = false; alert((data && data.data && data.data.message) ? data.data.message : 'Failed.'); }
            }).catch(function() { b.disabled = false; alert('Network error.'); });
        });
    });

    // Delete release
    document.querySelectorAll('.amai-rel-delete-btn').forEach(function(b) {
        b.addEventListener('click', function() {
            if (!confirm('Delete ' + b.dataset.zip + '? This cannot be undone.')) { return; }
            b.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_delete_release');
            fd.append('_ajax_nonce', b.dataset.nonce);
            fd.append('zip', b.dataset.zip);
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.success) {
                    var row = b.closest('tr');
                    if (row) {
                        var logRow = row.nextElementSibling;
                        if (logRow && logRow.classList.contains('amai-rel-log-row')) { logRow.remove(); }
                        row.remove();
                    }
                } else {
                    b.disabled = false;
                    alert((data && data.data && data.data.message) ? data.data.message : 'Failed.');
                }
            }).catch(function() { b.disabled = false; alert('Network error.'); });
        });
    });

    // Save changelog inline
    document.querySelectorAll('.amai-rel-log-save-btn').forEach(function(b) {
        b.addEventListener('click', function() {
            var ver   = b.dataset.ver;
            var row   = b.closest('.amai-rel-log-inner');
            var ta    = row ? row.querySelector('.amai-rel-log-textarea') : null;
            var saved = row ? row.querySelector('.amai-rel-log-saved') : null;
            if (!ta) { return; }
            b.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_save_release_changelog');
            fd.append('_ajax_nonce', ta.dataset.nonce);
            fd.append('version', ver);
            fd.append('changelog', ta.value.trim());
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                b.disabled = false;
                if (data && data.success) {
                    if (saved) { saved.style.display = 'inline'; setTimeout(function() { saved.style.display = 'none'; }, 2000); }
                } else {
                    alert((data && data.data && data.data.message) ? data.data.message : 'Failed.');
                }
            }).catch(function() { b.disabled = false; alert('Network error.'); });
        });
    });


    // Legal page tab switching and save
    document.querySelectorAll('.amai-legal-tab').forEach(function(tab) {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.amai-legal-tab').forEach(function(t) {
                t.classList.remove('amai-legal-tab--active');
            });
            document.querySelectorAll('.amai-legal-editor').forEach(function(e) {
                e.classList.add('amai-legal-editor--hidden');
            });
            tab.classList.add('amai-legal-tab--active');
            var editor = document.getElementById('amai-legal-' + tab.dataset.tab);
            if (editor) { editor.classList.remove('amai-legal-editor--hidden'); }
        });
    });

    document.querySelectorAll('.amai-legal-save-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var page      = btn.dataset.page;
            var editorId  = btn.dataset.editor;
            var saved     = document.getElementById('amai-legal-' + page + '-saved');
            var editorContent = '';
            if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
                editorContent = tinymce.get(editorId).getContent();
            } else {
                var ta = document.getElementById(editorId);
                editorContent = ta ? ta.value : '';
            }
            btn.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_save_legal_content');
            fd.append('_ajax_nonce', amaiSettings.nonce);
            fd.append('page', page);
            fd.append('content', editorContent);
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                btn.disabled = false;
                if (data && data.success) {
                    if (saved) { saved.textContent = 'Saved.'; saved.style.display = 'inline'; setTimeout(function() { saved.style.display = 'none'; }, 2500); }
                } else {
                    alert((data && data.data && data.data.message) ? data.data.message : 'Failed to save.');
                }
            }).catch(function() { btn.disabled = false; alert('Network error.'); });
        });
    });

    // --------------------------------------------------
    // Legal page AI generator
    // --------------------------------------------------
    document.querySelectorAll('.amai-legal-generate-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var page     = btn.dataset.page;
            var editorId = btn.dataset.editor;
            var toneGroup = document.querySelector('.amai-legal-tone-group[data-page="' + page + '"]');
            var toneBtn  = toneGroup ? toneGroup.querySelector('.amai-legal-tone-btn--active') : null;
            var tone     = toneBtn ? toneBtn.dataset.tone : 'professional';
            var statusEl = document.getElementById('amai-legal-' + page + '-generate-status');
            if (statusEl) { statusEl.textContent = 'Generating...'; statusEl.style.color = '#A8A29E'; }
            btn.disabled = true;
            var fd = new FormData();
            fd.append('action', 'amai_generate_legal_content');
            fd.append('_ajax_nonce', amaiSettings.legalGenerateNonce);
            fd.append('page', page);
            fd.append('tone', tone);
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                btn.disabled = false;
                if (data && data.success) {
                    if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
                        tinymce.get(editorId).setContent(data.data.content);
                    } else {
                        var ta = document.getElementById(editorId);
                        if (ta) { ta.value = data.data.content; }
                    }
                    if (statusEl) { statusEl.textContent = 'Done - review and save when ready.'; statusEl.style.color = '#22c55e'; setTimeout(function() { statusEl.textContent = ''; }, 5000); }
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Generation failed. Try again.';
                    if (statusEl) { statusEl.textContent = msg; statusEl.style.color = '#ef4444'; }
                }
            })
            .catch(function() {
                btn.disabled = false;
                if (statusEl) { statusEl.textContent = 'Network error. Try again.'; statusEl.style.color = '#ef4444'; }
            });
        });
    });

    // --------------------------------------------------
    // Downgrade to free plan
    // --------------------------------------------------
    var downgradeBtn       = document.getElementById('amai-downgrade-btn');
    var downgradeConfirm   = document.getElementById('amai-downgrade-confirm');
    var downgradeInput     = document.getElementById('amai-downgrade-input');
    var downgradeSubmitBtn = document.getElementById('amai-downgrade-submit-btn');
    var downgradeCancelBtn = document.getElementById('amai-downgrade-cancel-btn');
    var downgradeMsg       = document.getElementById('amai-downgrade-msg');

    if (downgradeBtn) {
        downgradeBtn.addEventListener('click', function() {
            downgradeBtn.style.display = 'none';
            if (downgradeConfirm) { downgradeConfirm.style.display = 'block'; }
            if (downgradeInput) { downgradeInput.focus(); }
        });
    }
    if (downgradeCancelBtn) {
        downgradeCancelBtn.addEventListener('click', function() {
            if (downgradeConfirm) { downgradeConfirm.style.display = 'none'; }
            if (downgradeBtn) { downgradeBtn.style.display = ''; }
            if (downgradeInput) { downgradeInput.value = ''; }
            if (downgradeMsg) { downgradeMsg.textContent = ''; }
        });
    }
    if (downgradeSubmitBtn) {
        downgradeSubmitBtn.addEventListener('click', function() {
            var val = downgradeInput ? downgradeInput.value.trim() : '';
            if (val !== 'Switch to Free') {
                if (downgradeMsg) { downgradeMsg.textContent = 'Type exactly: Switch to Free'; downgradeMsg.style.color = '#ef4444'; }
                return;
            }
            setLoading(downgradeSubmitBtn, true);
            if (downgradeMsg) { downgradeMsg.textContent = ''; }
            var fd = new FormData();
            fd.append('action', 'amai_downgrade_to_free');
            fd.append('_ajax_nonce', nonce);
            fd.append('confirm', val);
            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                setLoading(downgradeSubmitBtn, false);
                if (data && data.success) {
                    if (downgradeMsg) { downgradeMsg.textContent = data.data.message; downgradeMsg.style.color = '#22c55e'; }
                    setTimeout(function() { window.location.reload(); }, 1200);
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Something went wrong. Try again.';
                    if (downgradeMsg) { downgradeMsg.textContent = msg; downgradeMsg.style.color = '#ef4444'; }
                }
            })
            .catch(function() {
                setLoading(downgradeSubmitBtn, false);
                if (downgradeMsg) { downgradeMsg.textContent = 'Network error. Try again.'; downgradeMsg.style.color = '#ef4444'; }
            });
        });
    }

    // Tone picker -- single select per group
    document.querySelectorAll('.amai-legal-tone-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var group = btn.closest('.amai-legal-tone-group');
            if (!group) { return; }
            group.querySelectorAll('.amai-legal-tone-btn').forEach(function(b) {
                b.classList.remove('amai-legal-tone-btn--active');
            });
            btn.classList.add('amai-legal-tone-btn--active');
        });
    });

    // Legal editor collapse toggle
    document.querySelectorAll('.amai-legal-toggle-btn').forEach(function(btn) {
        var targetId = btn.dataset.target;
        var editor   = document.getElementById(targetId);
        if (!editor) { return; }
        if (localStorage.getItem('amai_legal_collapsed_' + targetId) === '1') {
            editor.classList.add('amai-legal-editor--collapsed');
            btn.textContent = 'Show editor';
        }
        btn.addEventListener('click', function() {
            var collapsed = editor.classList.toggle('amai-legal-editor--collapsed');
            btn.textContent = collapsed ? 'Show editor' : 'Hide editor';
            localStorage.setItem('amai_legal_collapsed_' + targetId, collapsed ? '1' : '0');
        });
    });

    // Legal URL fields save
    var saveUrlsBtn  = document.getElementById('amai-save-legal-urls-btn');
    var urlSavedSpan = document.getElementById('amai-legal-url-saved');
    if (saveUrlsBtn) {
        saveUrlsBtn.addEventListener('click', function() {
            var privacyUrl = (document.getElementById('amai_legal_privacy_url') || {}).value || '';
            var termsUrl   = (document.getElementById('amai_legal_terms_url')   || {}).value || '';
            setLoading(saveUrlsBtn, true);
            if (urlSavedSpan) { urlSavedSpan.textContent = ''; }
            var fd = new FormData();
            fd.append('action',      'amai_save_legal_urls');
            fd.append('_ajax_nonce', amaiSettings.nonce);
            fd.append('privacy_url', privacyUrl);
            fd.append('terms_url',   termsUrl);
            fetch(amaiSettings.ajaxUrl, { method: 'POST', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                setLoading(saveUrlsBtn, false);
                if (data && data.success) {
                    if (urlSavedSpan) { urlSavedSpan.textContent = 'Saved.'; }
                    setTimeout(function() { if (urlSavedSpan) { urlSavedSpan.textContent = ''; } }, 3000);
                    // Collapse editor for any policy that now has a URL
                    [['amai_legal_privacy_url', 'amai-legal-privacy'], ['amai_legal_terms_url', 'amai-legal-terms']].forEach(function(pair) {
                        var input  = document.getElementById(pair[0]);
                        var editor = document.getElementById(pair[1]);
                        var btn    = editor ? editor.querySelector('.amai-legal-toggle-btn') : null;
                        if (input && editor && input.value.trim() !== '') {
                            editor.classList.add('amai-legal-editor--collapsed');
                            if (btn) { btn.textContent = 'Show editor'; }
                        }
                    });
                } else {
                    if (urlSavedSpan) { urlSavedSpan.textContent = 'Save failed. Try again.'; }
                }
            })
            .catch(function() {
                setLoading(saveUrlsBtn, false);
                if (urlSavedSpan) { urlSavedSpan.textContent = 'Network error. Try again.'; }
            });
        });
    }


    // ── On-Post Comment Form settings save ──────────────────────────────────
    var cfSaveBtn = document.getElementById('amai-cf-save-btn');
    if (cfSaveBtn) {
        cfSaveBtn.addEventListener('click', function () {
            var postsEnabled    = document.getElementById('amai-cf-posts-enabled');
            var productsEnabled = document.getElementById('amai-cf-products-enabled');
            var rateLimit       = document.getElementById('amai-cf-rate-limit');
            var modePosts       = document.getElementById('amai-cf-mode-posts');
            var modeProducts    = document.getElementById('amai-cf-mode-products');
            var profanityWords  = document.getElementById('amai-cf-profanity-words');
            var htAlertsEnabled = document.getElementById('amai-ht-alerts-enabled');
            var rvAlertsEnabled = document.getElementById('amai-rv-alerts-enabled');
            var htThreshold     = document.getElementById('amai-ht-threshold');
            var htWindow        = document.getElementById('amai-ht-window');
            var saveMsg         = document.getElementById('amai-cf-save-msg');

            var fd = new FormData();
            fd.append('action',          'amai_save_comment_form_settings');
            fd.append('_ajax_nonce',     (typeof amaiSettings !== 'undefined') ? amaiSettings.commentFormNonce : '');
            fd.append('posts_enabled',    postsEnabled    && postsEnabled.checked    ? '1' : '0');
            fd.append('products_enabled', productsEnabled && productsEnabled.checked ? '1' : '0');
            fd.append('rate_limit',       rateLimit       ? rateLimit.value          : '10');
            fd.append('reply_mode_posts',    modePosts    ? modePosts.value    : 'manual');
            fd.append('reply_mode_products', modeProducts ? modeProducts.value : 'manual');
            fd.append('profanity_words',  profanityWords  ? profanityWords.value     : '');
            fd.append('ht_alerts_enabled', htAlertsEnabled && htAlertsEnabled.checked ? '1' : '0');
            fd.append('rv_alerts_enabled', rvAlertsEnabled && rvAlertsEnabled.checked ? '1' : '0');
            fd.append('ht_threshold',      htThreshold ? htThreshold.value : '5');
            fd.append('ht_window',         htWindow    ? htWindow.value    : '2');

            cfSaveBtn.disabled = true;
            if (saveMsg) { saveMsg.textContent = 'Saving...'; }

            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
                .then(function (r) { return r.json(); })
                .then(function (json) {
                    cfSaveBtn.disabled = false;
                    if (saveMsg) {
                        saveMsg.textContent = json.success ? 'Saved.' : (json.data && json.data.message ? json.data.message : 'Save failed.');
                        setTimeout(function () { if (saveMsg) saveMsg.textContent = ''; }, 3000);
                    }
                })
                .catch(function () {
                    cfSaveBtn.disabled = false;
                    if (saveMsg) { saveMsg.textContent = 'Network error. Try again.'; }
                });
        });
    }


    // ── Email Template Modal ──────────────────────────────────────────────

    function etplGetNonce() {
        return (typeof amaiSettings !== 'undefined') ? amaiSettings.nonce : '';
    }
    function etplGetAjaxUrl() {
        return (typeof amaiSettings !== 'undefined') ? amaiSettings.ajaxUrl : (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
    }

    var etplEditorId = 'amai_etpl_body';

    function etplOpen(type) {
        var backdrop = document.getElementById('amai-etpl-modal-backdrop');
        if (!backdrop) { return; }
        backdrop.style.display = 'flex';
        backdrop.setAttribute('aria-hidden', 'false');
        var msgEl = document.getElementById('amai-etpl-save-msg');
        if (msgEl) { msgEl.textContent = ''; }
        var tokensEl = document.getElementById('amai-etpl-tokens');
        if (tokensEl) { tokensEl.innerHTML = ''; }
        var subjectEl = document.getElementById('amai-etpl-subject');
        if (subjectEl) { subjectEl.value = ''; }
        var typeEl = document.getElementById('amai-etpl-type');
        if (typeEl) { typeEl.value = type; }
        if (typeof tinymce !== 'undefined' && tinymce.get(etplEditorId)) {
            tinymce.get(etplEditorId).setContent('');
        }
        jQuery.ajax({
            url: etplGetAjaxUrl(),
            method: 'POST',
            data: {
                action: 'amai_load_email_template',
                _ajax_nonce: etplGetNonce(),
                tpl_type: type
            },
            success: function(res) {
                if (!res || !res.success) { return; }
                var d = res.data;
                var titleEl = document.getElementById('amai-etpl-modal-title');
                if (titleEl) { titleEl.textContent = 'Edit: ' + d.label; }
                if (subjectEl) { subjectEl.value = d.subject || ''; }
                if (tokensEl) {
                    tokensEl.innerHTML = '';
                    (d.tokens || []).forEach(function(tok) {
                        var chip = document.createElement('button');
                        chip.type = 'button';
                        chip.className = 'amai-etpl-token-chip';
                        chip.textContent = tok;
                        chip.addEventListener('click', function() { etplInsertToken(tok); });
                        tokensEl.appendChild(chip);
                    });
                    (d.dynamic_tokens || []).forEach(function(tok) {
                        var chip = document.createElement('button');
                        chip.type = 'button';
                        chip.className = 'amai-etpl-token-chip amai-etpl-token-chip--dynamic';
                        chip.textContent = tok;
                        chip.title = 'Dynamic block -- filled in automatically at send time';
                        chip.addEventListener('click', function() { etplInsertToken(tok); });
                        tokensEl.appendChild(chip);
                    });
                }
                var notice = document.getElementById('amai-etpl-dynamic-notice');
                if (notice) {
                    notice.style.display = (d.dynamic_tokens && d.dynamic_tokens.length > 0) ? 'block' : 'none';
                }
                var body = d.body || '';
                if (!body) {
                    body = '<p>Hi {{first_name}},</p><p></p><p>- The AutoMarketer AI Team</p>';
                }
                setTimeout(function() {
                    if (typeof tinymce !== 'undefined' && tinymce.get(etplEditorId)) {
                        tinymce.get(etplEditorId).setContent(body);
                    } else {
                        var ta = document.getElementById(etplEditorId);
                        if (ta) { ta.value = body; }
                    }
                }, 150);
            }
        });
    }

    function etplInsertToken(token) {
        if (typeof tinymce !== 'undefined' && tinymce.get(etplEditorId)) {
            tinymce.get(etplEditorId).insertContent(token);
        } else {
            var ta = document.getElementById(etplEditorId);
            if (!ta) { return; }
            var start = ta.selectionStart;
            var end   = ta.selectionEnd;
            ta.value  = ta.value.substring(0, start) + token + ta.value.substring(end);
            ta.selectionStart = ta.selectionEnd = start + token.length;
            ta.focus();
        }
    }

    function etplClose() {
        document.querySelectorAll('.amai-etpl-smart-btn--edit-zone').forEach(function(b) { b.classList.remove('amai-etpl-smart-btn--edit-zone'); });
        var backdrop = document.getElementById('amai-etpl-modal-backdrop');
        if (backdrop) {
            backdrop.style.display = 'none';
            backdrop.setAttribute('aria-hidden', 'true');
        }
    }

    function etplGetBody() {
        if (typeof tinymce !== 'undefined' && tinymce.get(etplEditorId)) {
            return tinymce.get(etplEditorId).getContent();
        }
        var ta = document.getElementById(etplEditorId);
        return ta ? ta.value : '';
    }

    // Event delegation for edit links -- works regardless of DOM timing
    jQuery(document).on('click', '.amai-etpl-edit-link', function(e) {
        e.preventDefault();
        var type = jQuery(this).data('type');
        if (type) { etplOpen(String(type)); }
    });

    // DOM-ready bindings for modal buttons
    jQuery(function() {
        var closeBtn   = document.getElementById('amai-etpl-modal-close');
        var backdrop   = document.getElementById('amai-etpl-modal-backdrop');
        var saveBtn    = document.getElementById('amai-etpl-save-btn');
        var resetBtn   = document.getElementById('amai-etpl-reset-btn');

        if (closeBtn) { closeBtn.addEventListener('click', etplClose); }

        if (backdrop) {
            backdrop.addEventListener('click', function(e) {
                if (e.target === this) { etplClose(); }
            });
        }

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') { etplClose(); }
        });

        if (saveBtn) {
            saveBtn.addEventListener('click', function() {
                var type    = document.getElementById('amai-etpl-type') ? document.getElementById('amai-etpl-type').value : '';
                var subject = document.getElementById('amai-etpl-subject') ? document.getElementById('amai-etpl-subject').value.trim() : '';
                var body    = etplGetBody();
                var msgEl   = document.getElementById('amai-etpl-save-msg');
                if (!type || !subject || !body) {
                    if (msgEl) { msgEl.textContent = 'Subject and body are required.'; msgEl.className = 'amai-etpl-save-msg amai-etpl-save-msg--error'; }
                    return;
                }
                jQuery.ajax({
                    url: etplGetAjaxUrl(),
                    method: 'POST',
                    data: {
                        action: 'amai_save_email_template',
                        _ajax_nonce: etplGetNonce(),
                        tpl_type: type,
                        tpl_subject: subject,
                        tpl_body: body
                    },
                    success: function(res) {
                        if (res && res.success) {
                            if (msgEl) { msgEl.textContent = 'Saved.'; msgEl.className = 'amai-etpl-save-msg'; }
                            jQuery('.amai-etpl-edit-link[data-type="' + type + '"]').each(function() {
                                var nameEl = jQuery(this).closest('.amai-etpl-row__info').find('.amai-etpl-row__name')[0];
                                if (nameEl && !nameEl.querySelector('.amai-etpl-custom-badge')) {
                                    var badge = document.createElement('span');
                                    badge.className = 'amai-etpl-custom-badge';
                                    badge.textContent = 'Customized';
                                    nameEl.appendChild(badge);
                                }
                                var dot = this.querySelector('.amai-etpl-custom-dot');
                                if (!dot) {
                                    var d2 = document.createElement('span');
                                    d2.className = 'amai-etpl-custom-dot';
                                    this.appendChild(d2);
                                }
                            });
                            setTimeout(function() {
                                if (msgEl) { msgEl.textContent = ''; }
                                etplClose();
                            }, 1200);
                        } else {
                            if (msgEl) { msgEl.textContent = (res && res.data && res.data.message) ? res.data.message : 'Save failed.'; msgEl.className = 'amai-etpl-save-msg amai-etpl-save-msg--error'; }
                        }
                    }
                });
            });
        }

        if (resetBtn) {
            resetBtn.addEventListener('click', function() {
                var type  = document.getElementById('amai-etpl-type') ? document.getElementById('amai-etpl-type').value : '';
                var msgEl = document.getElementById('amai-etpl-save-msg');
                if (!type) { return; }
                if (!confirm('Reset this template to the built-in default? Your customizations will be lost.')) { return; }
                jQuery.ajax({
                    url: etplGetAjaxUrl(),
                    method: 'POST',
                    data: {
                        action: 'amai_reset_email_template',
                        _ajax_nonce: etplGetNonce(),
                        tpl_type: type
                    },
                    success: function(res) {
                        if (res && res.success) {
                            if (msgEl) { msgEl.textContent = 'Reset to default.'; msgEl.className = 'amai-etpl-save-msg'; }
                            jQuery('.amai-etpl-edit-link[data-type="' + type + '"]').each(function() {
                                var nameEl = jQuery(this).closest('.amai-etpl-row__info').find('.amai-etpl-row__name')[0];
                                if (nameEl) { var badge = nameEl.querySelector('.amai-etpl-custom-badge'); if (badge) { badge.remove(); } }
                                var dot = this.querySelector('.amai-etpl-custom-dot');
                                if (dot) { dot.remove(); }
                            });
                            setTimeout(function() {
                                if (msgEl) { msgEl.textContent = ''; }
                                etplClose();
                            }, 1200);
                        } else {
                            if (msgEl) { msgEl.textContent = 'Reset failed.'; msgEl.className = 'amai-etpl-save-msg amai-etpl-save-msg--error'; }
                        }
                    }
                });
            });
        }
    });


    // --------------------------------------------------
    // Settings panel navigation
    // --------------------------------------------------
    (function () {
        var navItems = document.querySelectorAll('.amai-spanel__nav-item');
        var pages    = document.querySelectorAll('.amai-spanel__page');
        if (!navItems.length) { return; }
        navItems.forEach(function (item) {
            item.addEventListener('click', function () {
                var target = item.dataset.page;
                navItems.forEach(function (n) { n.classList.remove('amai-spanel__nav-item--active'); });
                item.classList.add('amai-spanel__nav-item--active');
                var current = document.querySelector('.amai-spanel__page--active');
                var next    = document.querySelector('.amai-spanel__page[data-page="' + target + '"]');
                if (!next || next === current) { return; }
                if (current) {
                    current.classList.remove('amai-spanel__page--active');
                    current.style.display = 'none';
                }
                next.classList.add('amai-spanel__page--entering');
                next.style.display = 'block';
                requestAnimationFrame(function () {
                    requestAnimationFrame(function () {
                        next.classList.remove('amai-spanel__page--entering');
                        next.classList.add('amai-spanel__page--active');
                    });
                });
            });
        });
        // Show default active page on load
        var defaultNav = document.querySelector('.amai-spanel__nav-item--active');
        if (defaultNav) {
            var defaultPage = document.querySelector('.amai-spanel__page[data-page="' + defaultNav.dataset.page + '"]');
            if (defaultPage) {
                defaultPage.style.display = 'block';
                defaultPage.classList.add('amai-spanel__page--active');
            }
        }
    }());

}());