/**
 * CapiFlow — Admin Scripts.
 *
 * AJAX handlers for: Test Connection, Send Purchase (metabox), Debug Console.
 * JS object: capiFLowAdmin (note capital F + L — matches wp_localize_script key).
 *
 * @package CapiFlow
 */
/* global capiFLowAdmin */
(function ($) {
    'use strict';

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

    var nonce   = capiFLowAdmin.nonce;
    var ajaxUrl = capiFLowAdmin.ajaxUrl;

    // ── Test Connection ──────────────────────────────────────────────────────
    $(document).on('click', '.capiflow-test-connection', function () {
        var $btn    = $(this);
        var $result = $('#capiflow-test-result');

        var pixelId     = $('#capiflow_pixel_id').val() || '';
        var accessToken = $('#capiflow_access_token').val() || '';

        if (!pixelId.trim() && !capiFLowAdmin.hasSavedPixel) {
            $result.html('<span style="color:#dc2626;">❌ Please enter a Pixel ID first</span>');
            return;
        }

        if (!accessToken.trim() && !capiFLowAdmin.hasSavedToken) {
            $result.html('<span style="color:#dc2626;">❌ Please enter an Access Token first</span>');
            return;
        }

        $btn.prop('disabled', true).text(capiFLowAdmin.i18n.testing);
        $result.html('');

        var postData = {
            action: 'capiflow_test_connection',
            nonce: nonce,
        };

        if (pixelId.trim())     { postData.pixel_id     = pixelId.trim(); }
        if (accessToken.trim()) { postData.access_token = accessToken.trim(); }

        $.post(ajaxUrl, postData)
            .done(function (res) {
                if (res.success && res.data.success) {
                    $result.empty().append(
                        $('<span>', { style: 'color:#16a34a;' }).text('✅ ' + (res.data.message || 'Connected'))
                    );
                } else {
                    var msg = (res.data && res.data.message) ? res.data.message : 'Connection failed';
                    $result.empty().append(
                        $('<span>', { style: 'color:#dc2626;' }).text('❌ ' + msg)
                    );
                }
            })
            .fail(function () {
                $result.html('<span style="color:#dc2626;">❌ Request failed. Check console.</span>');
            })
            .always(function () {
                $btn.prop('disabled', false).text('🔗 Test Connection');
            });
    });

    // ── Manual Send Purchase (Order Metabox) ─────────────────────────────────
    $(document).on('click', '.capiflow-send-purchase', function () {
        var $btn     = $(this);
        var $result  = $btn.siblings('.capiflow-send-result');
        var orderId  = $btn.data('order-id');
        var btnNonce = $btn.data('nonce') || nonce;

        if (!orderId) { return; }

        $btn.prop('disabled', true).text('⏳ Sending...');
        $result.text('');

        $.post(ajaxUrl, {
            action: 'capiflow_send_purchase',
            nonce: btnNonce,
            order_id: orderId,
        })
            .done(function (res) {
                if (res.success) {
                    $btn.text('✅ Queued!');
                    $result.css('color', '#16a34a').text(res.data.message || 'Event queued.');
                    setTimeout(function () { location.reload(); }, 1500);
                } else {
                    var msg = (res.data && res.data.message) ? res.data.message : 'Send failed';
                    $btn.prop('disabled', false).text('🔄 Re-send Purchase');
                    $result.css('color', '#dc2626').text('❌ ' + msg);
                }
            })
            .fail(function () {
                $btn.prop('disabled', false).text('🔄 Re-send Purchase');
                $result.css('color', '#dc2626').text('❌ Request failed');
            });
    });

    // ── Debug Console: Load Queue Events ────────────────────────────────────
    function loadQueueData() {
        var eventFilter  = $('#capiflow-filter-event').val()  || '';
        var statusFilter = $('#capiflow-filter-status').val() || '';

        $.post(ajaxUrl, {
            action: 'capiflow_get_queue_data',
            nonce: nonce,
            event_name: eventFilter,
            status: statusFilter,
        })
            .done(function (res) {
                if (!res.success || !res.data.events) { return; }

                var $tbody = $('#capiflow-queue-tbody');
                $tbody.empty();

                if (res.data.events.length === 0) {
                    $tbody.html('<tr><td colspan="7" style="text-align:center;padding:20px;color:#9ca3af;">No events found</td></tr>');
                    return;
                }

                var statusIcon = { pending: '⏳', processing: '⚙', sent: '✅', failed: '❌' };

                res.data.events.forEach(function (ev) {
                    var row = '<tr>' +
                        '<td><strong>' + escHtml(ev.event_name) + '</strong></td>' +
                        '<td><code style="font-size:10px;">' + escHtml((ev.event_id || '').substring(0, 24)) + '...</code></td>' +
                        '<td>' + escHtml(String(ev.wc_order_id || '—')) + '</td>' +
                        '<td>' + (statusIcon[ev.status] || '') + ' ' + escHtml(ev.status) + '</td>' +
                        '<td>' + escHtml(String(ev.http_code || '—')) + '</td>' +
                        '<td>' + escHtml(String(ev.retry_count || '0')) + '</td>' +
                        '<td style="font-size:11px;color:#6b7280;">' + escHtml(ev.created_at) + '</td>' +
                        '</tr>';
                    $tbody.append(row);
                });
            });
    }

    // ── Debug Console: Load Logs ─────────────────────────────────────────────
    function loadLogData() {
        $.post(ajaxUrl, {
            action: 'capiflow_get_log_data',
            nonce: nonce,
        })
            .done(function (res) {
                if (!res.success || !res.data.entries) { return; }

                var $tbody = $('#capiflow-logs-tbody');
                $tbody.empty();

                if (res.data.entries.length === 0) {
                    $tbody.html('<tr><td colspan="6" style="text-align:center;padding:20px;color:#9ca3af;">No log entries found</td></tr>');
                    return;
                }

                var levelColor = { error: '#dc2626', warning: '#f59e0b', info: '#16a34a', debug: '#6b7280' };

                res.data.entries.forEach(function (entry) {
                    var row = '<tr>' +
                        '<td style="font-size:11px;color:#9ca3af;">' + escHtml(entry.ts || '') + '</td>' +
                        '<td><span style="color:' + (levelColor[entry.level] || '#333') + ';font-weight:700;">' + escHtml((entry.level || '').toUpperCase()) + '</span></td>' +
                        '<td>' + escHtml(entry.event || '') + '</td>' +
                        '<td><code style="font-size:10px;">' + escHtml((entry.id || '').substring(0, 24)) + '</code></td>' +
                        '<td>' + escHtml(String(entry.http || '—')) + '</td>' +
                        '<td style="font-size:11px;max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + escHtml(entry.response || '') + '</td>' +
                        '</tr>';
                    $tbody.append(row);
                });
            });
    }

    // ── Debug tab switching ──────────────────────────────────────────────────
    $(document).on('click', '.capiflow-debug-tab', function () {
        var tab = $(this).data('tab');
        $('.capiflow-debug-tab').removeClass('active');
        $(this).addClass('active');
        $('.capiflow-debug-panel').hide();
        $('#capiflow-debug-' + tab).show();

        if (tab === 'queue') { loadQueueData(); }
        if (tab === 'logs')  { loadLogData();   }
    });

    $(document).on('click', '.capiflow-refresh-debug', function () {
        var activeTab = $('.capiflow-debug-tab.active').data('tab');
        if (activeTab === 'queue') { loadQueueData(); }
        if (activeTab === 'logs')  { loadLogData();   }
    });

    // Auto-load when on debug console page.
    if ($('.capiflow-debug-console').length) {
        loadQueueData();
    }

    // ── Utility: safe HTML escape ────────────────────────────────────────────
    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    // ── Row border coloring (Order List) ─────────────────────────────────────
    // Reads data-capi-status from Order_Columns Event Status column.
    // Uses JS (not PHP) because render_column() only controls <td>, not <tr>.
    // Risk-based coloring is handled by Pro's own column JS.
    (function () {
        document.querySelectorAll('.capiflow-event-status').forEach(function (el) {
            var capi = el.dataset.capiStatus;
            var row  = el.closest('tr');
            if (!row) return;

            if (capi === 'failed') {
                row.classList.add('capiflow-row-danger');
            } else if (capi === 'queued') {
                row.classList.add('capiflow-row-caution');
            } else if (capi === 'sent') {
                row.classList.add('capiflow-row-safe');
            } else {
                row.classList.add('capiflow-row-neutral');
            }
        });
    })();

    // ── Dismissible CTA / Notice handler ─────────────────────────────────────
    // Handles: .capiflow-dismiss on widget CTA and setup success notice.
    // Sends AJAX to save user_meta so dismiss persists per-user.
    $(document).on('click', '.capiflow-dismiss', function () {
        var $btn    = $(this);
        var action  = $btn.data('action');
        var $parent = $btn.closest('.capiflow-widget-cta, .capiflow-setup-success, .notice');

        if ($parent.length) {
            $parent.slideUp(200);
        }

        if (action && typeof capiFLowAdmin !== 'undefined') {
            $.post(ajaxUrl, { action: action, nonce: nonce });
        }
    });

    // ── Environment Mode Toggle (Test Event Code row visibility) ───────────
    // Migrated from settings-page.php inline script for WP.org compliance.
    (function () {
        var prodRadio = document.getElementById('capiflow_env_production');
        var testRadio = document.getElementById('capiflow_env_test');
        var codeRow   = document.getElementById('capiflow-test-code-row');
        if (!prodRadio || !testRadio || !codeRow) return;
        function toggleRow() {
            codeRow.style.display = testRadio.checked ? '' : 'none';
        }
        prodRadio.addEventListener('change', toggleRow);
        testRadio.addEventListener('change', toggleRow);
    })();

})(jQuery);
