// ==================================================
// Nuclear Fancy Pants Edition™
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/assets/js/amai-comments.js
// Description: Comment inbox interactions -- reply, AI draft, ignore, settings save - NUCLEAR+++
// Last Edited: 2026-05-15
// ==================================================

(function () {
    'use strict';

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

    // ── Modal ──────────────────────────────────────────────────────────────

    var modal    = document.getElementById('amai-reply-settings-modal');
    var openBtn  = document.getElementById('amai-open-reply-settings');
    var closeBtn = document.getElementById('amai-close-reply-settings');
    var backdrop = document.getElementById('amai-reply-settings-backdrop');

    function openModal() {
        if (!modal) return;
        modal.style.display = '';
    }

    function closeModal() {
        if (!modal) return;
        modal.style.display = 'none';
    }

    if (openBtn) {
        openBtn.addEventListener('click', openModal);
    }
    if (closeBtn) {
        closeBtn.addEventListener('click', closeModal);
    }
    if (backdrop) {
        backdrop.addEventListener('click', closeModal);
    }

    var cancelBtn = document.getElementById('amai-cancel-reply-settings');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', closeModal);
    }
    // ── Tone change hint ───────────────────────────────────────────────────

    var toneSelects = document.querySelectorAll('.amai-reply-tone-select');
    toneSelects.forEach(function (sel) {
        sel.addEventListener('change', function () {
            var ch   = sel.getAttribute('data-channel');
            var def  = sel.getAttribute('data-default');
            var hint = document.getElementById('tone-hint-' + ch);
            if (!hint) return;
            hint.style.display = sel.value !== def ? '' : 'none';
        });
    });

    // ── Save settings ──────────────────────────────────────────────────────

    var saveBtn    = document.getElementById('amai-save-reply-settings');
    var savedMsg   = document.getElementById('amai-settings-saved-msg');

    if (saveBtn) {
        saveBtn.addEventListener('click', function () {
            var modes = {};
            var tones = {};

            document.querySelectorAll('.amai-reply-mode-select').forEach(function (sel) {
                modes[sel.getAttribute('data-channel')] = sel.value;
            });
            document.querySelectorAll('.amai-reply-tone-select').forEach(function (sel) {
                tones[sel.getAttribute('data-channel')] = sel.value;
            });

            saveBtn.disabled = true;
            saveBtn.textContent = 'Saving...';

            var body = new URLSearchParams();
            body.append('action', 'amai_save_comment_settings');
            body.append('nonce', nonce);
            body.append('modes', JSON.stringify(modes));
            body.append('tones', JSON.stringify(tones));

            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save Settings';
                if (data && data.success) {
                    closeModal();
                    if (savedMsg) {
                        savedMsg.style.display = '';
                        setTimeout(function () { savedMsg.style.display = 'none'; }, 2500);
                    }
                } else {
                    alert('Could not save settings. Please try again.');
                }
            })
            .catch(function () {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save Settings';
                alert('Network error. Please try again.');
            });
        });
    }

    // ── Reply toggle (manual reply box) ───────────────────────────────────

    document.querySelectorAll('.amai-comment-reply-toggle').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id    = btn.getAttribute('data-id');
            var block = document.getElementById('manual-reply-' + id);
            if (!block) return;
            var isVisible = block.style.display !== 'none';
            block.style.display = isVisible ? 'none' : '';
            if (!isVisible) {
                var ta = document.getElementById('reply-text-' + id);
                if (ta) ta.focus();
            }
        });
    });

    // ── Cancel reply ──────────────────────────────────────────────────────

    document.querySelectorAll('.amai-comment-cancel-reply').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id    = btn.getAttribute('data-id');
            var block = document.getElementById('manual-reply-' + id);
            if (block) block.style.display = 'none';
        });
    });

    // ── Generate AI draft (manual mode) ───────────────────────────────────

    document.querySelectorAll('.amai-comment-ai-draft-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = btn.getAttribute('data-id');
            btn.disabled = true;
            btn.textContent = 'Generating...';

            var body = new URLSearchParams();
            body.append('action', 'amai_generate_comment_draft');
            body.append('nonce', nonce);
            body.append('comment_id', id);

            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 = 'Generate AI Draft';

                if (data && data.success && data.data && data.data.draft) {
                    var block = document.getElementById('manual-reply-' + id);
                    if (block) block.style.display = '';
                    var ta = document.getElementById('reply-text-' + id);
                    if (ta) {
                        ta.value = data.data.draft;
                        ta.focus();
                    }
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'AI generation failed. Please try again.';
                    alert(msg);
                }
            })
            .catch(function () {
                btn.disabled = false;
                btn.textContent = 'Generate AI Draft';
                alert('Network error. Please try again.');
            });
        });
    });

    // ── Send reply ─────────────────────────────────────────────────────────

    document.querySelectorAll('.amai-comment-send-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id   = btn.getAttribute('data-id');
            var ta   = document.getElementById('reply-text-' + id);
            var text = ta ? ta.value.trim() : '';

            if (!text) {
                alert('Please enter a reply before sending.');
                return;
            }

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

            var body = new URLSearchParams();
            body.append('action', 'amai_send_comment_reply');
            body.append('nonce', nonce);
            body.append('comment_id', id);
            body.append('reply_text', text);

            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success) {
                    markRowReplied(id, text);
                } else {
                    btn.disabled = false;
                    btn.textContent = 'Send Reply';
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Could not send reply. Please try again.';
                    alert(msg);
                }
            })
            .catch(function () {
                btn.disabled = false;
                btn.textContent = 'Send Reply';
                alert('Network error. Please try again.');
            });
        });
    });

    // ── Ignore ─────────────────────────────────────────────────────────────

    document.querySelectorAll('.amai-comment-ignore-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = btn.getAttribute('data-id');

            var body = new URLSearchParams();
            body.append('action', 'amai_ignore_comment');
            body.append('nonce', nonce);
            body.append('comment_id', id);

            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success) {
                    markRowIgnored(id);
                }
            })
            .catch(function () {});
        });
    });

    // ── DOM helpers ────────────────────────────────────────────────────────

    function markRowReplied(id, replyText) {
        var row = document.querySelector('.amai-comment-row[data-id="' + id + '"]');
        if (!row) return;

        row.classList.remove('unread');
        row.setAttribute('data-status', 'replied');

        var pill = row.querySelector('.amai-comment-status-pill');
        if (pill) {
            pill.className = 'amai-comment-status-pill amai-comment-status-pill--replied';
            pill.textContent = 'Replied';
        }

        var unreadDot = row.querySelector('.amai-comment-unread-dot');
        if (unreadDot) unreadDot.remove();

        var actionsBlock = row.querySelector('.amai-comment-actions');
        var draftBlock   = row.querySelector('.amai-comment-draft-block');
        if (actionsBlock) actionsBlock.remove();
        if (draftBlock)   draftBlock.remove();

        var contentEl = row.querySelector('.amai-comment-row-body');
        if (contentEl) {
            var sentDiv = document.createElement('div');
            sentDiv.className = 'amai-comment-sent-reply';
            sentDiv.innerHTML = '<span class="amai-comment-sent-label">Your reply:</span>' +
                escapeHtml(replyText);
            contentEl.appendChild(sentDiv);
        }
    }

    function markRowIgnored(id) {
        var row = document.querySelector('.amai-comment-row[data-id="' + id + '"]');
        if (!row) return;

        row.classList.remove('unread');
        row.setAttribute('data-status', 'ignored');

        var pill = row.querySelector('.amai-comment-status-pill');
        if (pill) {
            pill.className = 'amai-comment-status-pill amai-comment-status-pill--ignored';
            pill.textContent = 'Ignored';
        }

        var unreadDot = row.querySelector('.amai-comment-unread-dot');
        if (unreadDot) unreadDot.remove();

        var actionsBlock = row.querySelector('.amai-comment-actions');
        var draftBlock   = row.querySelector('.amai-comment-draft-block');
        if (actionsBlock) actionsBlock.remove();
        if (draftBlock)   draftBlock.remove();
    }

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

}());