/**
 * Cart Recovery — Admin UI JS
 *
 * Wires:
 *   - Preview iframe (AJAX compose via Niwa_AI_Cart_Recovery_Mailer::preview).
 *   - Test-send button (admin email).
 *   - Run tick now (dev trigger).
 *   - Add/remove suppression entries.
 *   - Metrics Chart.js line chart.
 */
(function ($) {
    'use strict';

    if (typeof NiwaAiCR === 'undefined') {
        return;
    }

    function ajaxPost(action, payload) {
        return $.post(NiwaAiCR.ajaxUrl, Object.assign({
            action: action,
            nonce: NiwaAiCR.nonce
        }, payload || {}));
    }

    function setStatus($el, msg, tone) {
        if (!$el.length) return;
        $el.text(msg).removeClass('notice-success notice-error').css('color', tone === 'error' ? '#b32d2e' : '#00734c');
    }

    /* --------- Preview --------- */
    var $previewStatus = $('#niwa-ai-cr-preview-status');
    var $previewFrame  = $('#niwa-ai-cr-preview-frame');
    var $previewMeta   = $('#niwa-ai-cr-preview-meta');

    $('#niwa-ai-cr-preview-generate').on('click', function () {
        var rowId = $('#niwa-ai-cr-preview-row').val();
        var stage = $('#niwa-ai-cr-preview-stage').val();
        setStatus($previewStatus, '…', 'info');

        ajaxPost('niwa_ai_cr_preview', { row_id: rowId, stage: stage }).then(function (resp) {
            if (!resp || !resp.success) {
                setStatus($previewStatus, (resp && resp.data && resp.data.message) || NiwaAiCR.i18n.previewError, 'error');
                return;
            }
            var data = resp.data;
            $previewMeta.html(
                '<strong>' + $('<div/>').text(data.subject).html() + '</strong>' +
                ' <span style="color:#888;">· ' + (data.is_fallback ? 'fallback template' : 'AI composed') +
                ' · ' + (data.from_cache ? 'cache hit' : 'fresh') + '</span>'
            );
            var frame = $previewFrame.get(0);
            if (frame && frame.contentWindow) {
                frame.contentWindow.document.open();
                frame.contentWindow.document.write(data.html);
                frame.contentWindow.document.close();
            }
            setStatus($previewStatus, 'OK', 'info');
        }).fail(function () {
            setStatus($previewStatus, NiwaAiCR.i18n.previewError, 'error');
        });
    });

    /* --------- Test send --------- */
    $('#niwa-ai-cr-test-send').on('click', function () {
        var rowId = $('#niwa-ai-cr-preview-row').val();
        var stage = $('#niwa-ai-cr-preview-stage').val();
        setStatus($previewStatus, '…', 'info');

        ajaxPost('niwa_ai_cr_test_send', { row_id: rowId, stage: stage }).then(function (resp) {
            if (resp && resp.success) {
                setStatus($previewStatus, NiwaAiCR.i18n.testSent + ' → ' + resp.data.to, 'info');
            } else {
                setStatus($previewStatus, (resp && resp.data && resp.data.message) || NiwaAiCR.i18n.testFailed, 'error');
            }
        }).fail(function () {
            setStatus($previewStatus, NiwaAiCR.i18n.testFailed, 'error');
        });
    });

    /* --------- Run tick now (General tab dev tool) --------- */
    function buildTickSummary(data) {
        var msg = NiwaAiCR.i18n.tickDone;
        if (!data) {
            return msg;
        }

        var parts = [];
        var pending = data.pending || {};
		parts.push('pending: ' +
			(pending.with_contact_before || 0) + '+' + (pending.shadow_before || 0) + ' (with contact+shadow) → ' +
			(pending.with_contact_after || 0) + '+' + (pending.shadow_after || 0));

        if (data.shadow_row_upgraded && data.shadow_row_upgraded > 0) {
            parts.push('auto-linked row #' + data.shadow_row_upgraded);
        }
        if (data.bulk_linked && data.bulk_linked > 0) {
            parts.push('force-linked ' + data.bulk_linked + ' shadow row(s)');
        }

        return msg + ' — ' + parts.join(' · ');
    }

    function runTick(forceLinkAll) {
        var $out = $('#niwa-ai-cr-run-tick-result');
        setStatus($out, '…', 'info');
        ajaxPost('niwa_ai_cr_run_tick_now', { force_link_all: forceLinkAll ? '1' : '0' }).then(function (resp) {
            if (resp && resp.success) {
                setStatus($out, buildTickSummary(resp.data), 'info');
            } else {
                setStatus($out, (resp && resp.data && resp.data.message) || 'error', 'error');
            }
        }).fail(function () {
            setStatus($out, 'error', 'error');
        });
    }

    $('#niwa-ai-cr-run-tick').on('click', function () { runTick(false); });
    $('#niwa-ai-cr-run-tick-force').on('click', function () {
        var confirmMsg = NiwaAiCR.i18n.confirmForceLink || 'This attaches your admin email to EVERY pending shadow row. Continue?';
        if (window.confirm(confirmMsg)) {
            runTick(true);
        }
    });

    /* --------- Suppression add/remove --------- */
    var $suppMsg = $('#niwa-ai-cr-suppress-msg');

    $('#niwa-ai-cr-add-suppress').on('click', function () {
        var email = ($('#niwa-ai-cr-new-suppress').val() || '').trim();
        if (!email) return;
        setStatus($suppMsg, '…', 'info');
        ajaxPost('niwa_ai_cr_add_suppression', { email: email }).then(function (resp) {
            if (resp && resp.success) {
                setStatus($suppMsg, NiwaAiCR.i18n.suppressAdded, 'info');
                setTimeout(function () { window.location.reload(); }, 600);
            } else {
                setStatus($suppMsg, (resp && resp.data && resp.data.message) || 'error', 'error');
            }
        }).fail(function () {
            setStatus($suppMsg, 'error', 'error');
        });
    });

    $(document).on('click', '.niwa-ai-cr-remove-suppress', function () {
        var email = $(this).data('email');
        if (!email || !window.confirm(NiwaAiCR.i18n.confirmRemove)) return;
        var $btn = $(this);
        ajaxPost('niwa_ai_cr_remove_suppression', { email: email }).then(function (resp) {
            if (resp && resp.success) {
                $btn.closest('tr').fadeOut(200, function () { $(this).remove(); });
            } else {
                alert((resp && resp.data && resp.data.message) || 'error');
            }
        }).fail(function () {
            alert('error');
        });
    });

    /* --------- Metrics chart --------- */
    var seriesEl = document.getElementById('niwa-ai-cr-metrics-series');
    var canvas   = document.getElementById('niwa-ai-cr-metrics-chart');
    if (seriesEl && canvas && typeof Chart !== 'undefined') {
        try {
            var series = JSON.parse(seriesEl.textContent || '[]');
            new Chart(canvas.getContext('2d'), {
                type: 'line',
                data: {
                    labels: series.map(function (b) { return b.date; }),
                    datasets: [
                        {
                            label: 'Sent',
                            data: series.map(function (b) { return b.sent; }),
                            borderColor: '#2271b1',
                            backgroundColor: 'rgba(34,113,177,0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: 'Recovered',
                            data: series.map(function (b) { return b.recovered; }),
                            borderColor: '#00734c',
                            backgroundColor: 'rgba(0,115,76,0.1)',
                            tension: 0.3,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    interaction: { mode: 'index', intersect: false },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
                }
            });
        } catch (e) {
            /* swallow */
        }
    }
})(jQuery);
