/**
 * Webhook Health Monitor JavaScript
 * Handles Chart.js initialization, AJAX retry actions, and event filtering.
 */
(function ($) {
    'use strict';

    var webhookChart = null;

    /**
     * Show an inline notice above the actions bar.
     */
    function showNotice(message, type) {
        var cssClass = type === 'error' ? 'notice-error' : 'notice-success';
        var $notice = $('<div class="notice ' + cssClass + ' is-dismissible" role="alert" style="margin:10px 0;"><p></p></div>');
        $notice.find('p').text(message);
        $('.strp-webhook-actions').before($notice);
        setTimeout(function () { $notice.fadeOut(400, function () { $(this).remove(); }); }, 5000);
    }

    /**
     * Initialize the stacked bar chart using Chart.js.
     */
    function initChart() {
        var canvas = document.getElementById('strp-webhook-chart');
        if (!canvas || typeof Chart === 'undefined' || typeof strp_sub_webhook_chart_data === 'undefined') {
            return;
        }

        var ctx = canvas.getContext('2d');
        var data = strp_sub_webhook_chart_data;

        if (webhookChart) { webhookChart.destroy(); }
        webhookChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.labels,
                datasets: [
                    {
                        label: strp_sub_webhook_monitor_params.i18n_successful || 'Successful',
                        data: data.success,
                        backgroundColor: 'rgba(0, 163, 42, 0.7)',
                        borderColor: 'rgba(0, 163, 42, 1)',
                        borderWidth: 1,
                        borderRadius: 3
                    },
                    {
                        label: strp_sub_webhook_monitor_params.i18n_failed || 'Failed',
                        data: data.failed,
                        backgroundColor: 'rgba(214, 54, 56, 0.7)',
                        borderColor: 'rgba(214, 54, 56, 1)',
                        borderWidth: 1,
                        borderRadius: 3
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        stacked: true,
                        grid: {
                            display: false
                        },
                        ticks: {
                            maxRotation: 45,
                            font: {
                                size: 11
                            }
                        }
                    },
                    y: {
                        stacked: true,
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1,
                            font: {
                                size: 11
                            }
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end',
                        labels: {
                            usePointStyle: true,
                            pointStyle: 'circle',
                            padding: 16,
                            font: {
                                size: 13
                            }
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(30, 41, 59, 0.9)',
                        titleFont: {
                            size: 13
                        },
                        bodyFont: {
                            size: 12
                        },
                        padding: 12,
                        cornerRadius: 8
                    }
                }
            }
        });
    }

    /**
     * Handle "Retry All Now" button click.
     */
    function bindRetryAll() {
        $('#strp-webhook-retry-all').on('click', function () {
            var $btn = $(this);

            if ($btn.hasClass('strp-btn--loading')) {
                return;
            }

            $btn.addClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_processing || 'Processing...');

            $.post(strp_sub_webhook_monitor_params.ajax_url, {
                action: 'strp_sub_retry_all_webhooks',
                nonce: strp_sub_webhook_monitor_params.nonce
            }, function (response) {
                if (response.success) {
                    location.reload();
                } else {
                    showNotice(response.data && response.data.message ? response.data.message : strp_sub_webhook_monitor_params.i18n_error, 'error');
                    $btn.removeClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_retry_all || 'Retry All Now');
                }
            }).fail(function () {
                showNotice(strp_sub_webhook_monitor_params.i18n_error || 'An error occurred. Please try again.', 'error');
                $btn.removeClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_retry_all || 'Retry All Now');
            });
        });
    }

    /**
     * Handle "Clear Resolved" button click.
     */
    function bindClearResolved() {
        $('#strp-webhook-clear-resolved').on('click', function () {
            var $btn = $(this);

            if ($btn.hasClass('strp-btn--loading')) {
                return;
            }

            if (!confirm(strp_sub_webhook_monitor_params.i18n_confirm_clear || 'Are you sure you want to clear all resolved failures?')) {
                return;
            }

            $btn.addClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_clearing || 'Clearing...');

            $.post(strp_sub_webhook_monitor_params.ajax_url, {
                action: 'strp_sub_clear_resolved_webhooks',
                nonce: strp_sub_webhook_monitor_params.nonce
            }, function (response) {
                if (response.success) {
                    location.reload();
                } else {
                    showNotice(response.data && response.data.message ? response.data.message : strp_sub_webhook_monitor_params.i18n_error, 'error');
                    $btn.removeClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_clear_resolved || 'Clear Resolved');
                }
            }).fail(function () {
                showNotice(strp_sub_webhook_monitor_params.i18n_error || 'An error occurred. Please try again.', 'error');
                $btn.removeClass('strp-btn--loading').text(strp_sub_webhook_monitor_params.i18n_clear_resolved || 'Clear Resolved');
            });
        });
    }

    /**
     * Handle event type filter dropdown change.
     */
    function bindEventFilter() {
        $('#strp-webhook-event-type-filter').on('change', function () {
            var eventType = $(this).val();
            var $tbody = $('#strp-webhook-events-tbody');

            $tbody.css('opacity', '0.5');

            $.post(strp_sub_webhook_monitor_params.ajax_url, {
                action: 'strp_sub_filter_events',
                nonce: strp_sub_webhook_monitor_params.nonce,
                event_type: eventType
            }, function (response) {
                $tbody.css('opacity', '1');
                // Server-rendered HTML from strp_sub_filter_events with esc_html() on all dynamic values.
                // Trust chain: PHP render_event_rows() → esc_html/esc_attr on each field → JSON response.
                if (response.success && response.data.html) {
                    $tbody.html(response.data.html);
                }
            }).fail(function () {
                $tbody.css('opacity', '1');
            });
        });
    }

    /**
     * Initialize everything on DOM ready.
     */
    $(document).ready(function () {
        initChart();
        bindRetryAll();
        bindClearResolved();
        bindEventFilter();
    });

})(jQuery);
