/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /assets/js/amai-content-freshness.js
   Description: Content Health dashboard JS — refresh AJAX handler
   Last Edited: 2026-04-26
   ================================================== */

(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        initRefreshButtons();
        initRescanBtn();
        initStaleToggle();
    });

    function initRefreshButtons() {
        var wrap = document.getElementById('amai-content-health-wrap');
        if (!wrap) { return; }

        wrap.addEventListener('click', function (e) {
            var btn = e.target.closest('.amai-ch-refresh-btn');
            if (!btn) { return; }
            handleRefresh(btn);
        });
    }

    function handleRefresh(btn) {
        var postId  = btn.getAttribute('data-post-id') || '';
        var ajaxurl = window.amaiContentHealth ? window.amaiContentHealth.ajaxurl : window.ajaxurl;
        var nonce   = window.amaiContentHealth ? window.amaiContentHealth.nonce : '';

        if (!postId) { return; }

        var row     = btn.closest('.amai-ch-row');
        var original = btn.textContent;

        btn.disabled    = true;
        btn.textContent = 'Refreshing...';

        // Remove any existing status line
        var existing = row ? row.querySelector('.amai-ch-row-status') : null;
        if (existing) { existing.remove(); }

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

        fetch(ajaxurl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString(),
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            btn.disabled    = false;
            btn.textContent = original;

            var status = document.createElement('div');
            status.className = 'amai-ch-row-status';

            if (data.success) {
                status.classList.add('amai-ch-row-status--success');
                status.textContent = 'Refreshed - content updated.';
                btn.textContent = 'Refresh again';
            } else {
                status.classList.add('amai-ch-row-status--error');
                status.textContent = (data.data && data.data.message) ? data.data.message : 'Refresh failed. Try again.';
            }

            if (row) {
                var titleCol = row.querySelector('.amai-ch-col--title');
                if (titleCol) {
                    titleCol.appendChild(status);
                }
            }
        })
        .catch(function () {
            btn.disabled    = false;
            btn.textContent = original;

            var status = document.createElement('div');
            status.className = 'amai-ch-row-status amai-ch-row-status--error';
            status.textContent = 'Request failed. Please try again.';

            if (row) {
                var titleCol = row.querySelector('.amai-ch-col--title');
                if (titleCol) { titleCol.appendChild(status); }
            }
        });
    }

    function initRescanBtn() {
        var btn    = document.getElementById('amai-ch-rescan-btn');
        var status = document.getElementById('amai-ch-rescan-status');
        if (!btn) { return; }
        btn.addEventListener('click', function () {
            var ajaxurl = window.amaiContentHealth ? window.amaiContentHealth.ajaxurl : window.ajaxurl;
            var nonce   = window.amaiContentHealth ? window.amaiContentHealth.nonce : '';
            btn.disabled    = true;
            btn.textContent = 'Analyzing...';
            if (status) { status.textContent = ''; status.className = 'amai-ch-rescan-status'; }
            var body = new URLSearchParams();
            body.append('action',  'amai_content_health_rescan');
            body.append('nonce',   nonce);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled    = false;
                btn.textContent = 'Re-analyze all posts';
                if (data.success) {
                    if (status) {
                        status.textContent = 'Done - reload the page to see updated scores.';
                        status.classList.add('amai-ch-rescan-status--success');
                    }
                } else {
                    if (status) {
                        status.textContent = 'Analysis failed. Please try again.';
                        status.classList.add('amai-ch-rescan-status--error');
                    }
                }
            })
            .catch(function () {
                btn.disabled    = false;
                btn.textContent = 'Re-analyze all posts';
                if (status) {
                    status.textContent = 'Request failed.';
                    status.classList.add('amai-ch-rescan-status--error');
                }
            });
        });
    }

    function initStaleToggle() {
        var header  = document.getElementById('amai-ch-stale-header');
        var body    = document.getElementById('amai-ch-stale-body');
        var chevron = document.getElementById('amai-ch-stale-chevron');
        if (!header || !body) { return; }
        header.addEventListener('click', function () {
            var hidden = body.style.display === 'none';
            body.style.display = hidden ? '' : 'none';
            if (chevron) { chevron.classList.toggle('amai-ch-section-chevron--collapsed', !hidden); }
        });
    }

}());