/**
 * BotFend Anti-Bot Firewall - Security Logs Handler
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        if (typeof botfendLogs === 'undefined') {
            console.error('BotFend: Required localized data is missing.');
            return;
        }

        var urlParams = new URLSearchParams(window.location.search);
        var isClearing = urlParams.has('clear_logs') || urlParams.has('clear_aggregates');

        if (!isClearing) {
            var config = {
                autoRefresh: botfendLogs.autoRefresh,
                refreshInterval: botfendLogs.refreshInterval
            };
        }

        // ============================================
        // TOAST NOTIFICATION SYSTEM
        // ============================================
        function showToast(message, type) {
            var $toast = $('#botfend-logs-toast');
            
            if (!$toast.length) {
                $toast = $('<div id="botfend-logs-toast" class="botfend-toast"></div>').appendTo('body');
            }
            
            $toast.removeClass('success error warning').addClass(type);
            $toast.html('<span class="dashicons"></span><span class="toast-message">' + message + '</span>');
            $toast.addClass('show');
            
            setTimeout(function() {
                $toast.removeClass('show');
            }, 3000);
        }

        // ============================================
        // REFRESH BUTTON
        // ============================================
        $('.botfend-refresh-logs').on('click', function() {
            var $btn = $(this);
            var originalHtml = $btn.html();

            $btn.prop('disabled', true).html(
                '<span class="dashicons dashicons-update dashicons-update-spin"></span> ' + 
                botfendLogs.refreshingText
            );

            $.ajax({
                url: botfendLogs.ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_refresh_logs',
                    nonce: botfendLogs.refreshNonce
                },
                success: function(response) {
                    if (response.success) {
                        showToast(botfendLogs.refreshSuccess, 'success');
                        setTimeout(function() {
                            location.reload();
                        }, 500);
                    } else {
                        $btn.prop('disabled', false).html(originalHtml);
                        showToast(response.data.message || botfendLogs.refreshFailed, 'error');
                    }
                },
                error: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                    showToast(botfendLogs.refreshFailed, 'error');
                }
            });
        });

        // ============================================
        // ADMIN NOTICES
        // ============================================
        setTimeout(function() {
            $('.botfend-notice').fadeOut('slow', function() { $(this).remove(); });
        }, 5000);

        $('.botfend-notice .notice-dismiss').on('click', function() {
            $(this).closest('.botfend-notice').fadeOut('slow', function() { $(this).remove(); });
        });

        // ============================================
        // BULK ACTIONS
        // ============================================
        $('#select-all-logs').on('change', function() {
            $('.log-checkbox').prop('checked', $(this).is(':checked'));
            updateBulkActionButton();
        });

        $('.log-checkbox').on('change', function() {
            updateBulkActionButton();
        });

        function updateBulkActionButton() {
            var checkedCount = $('.log-checkbox:checked').length;
            $('#bulk-action-button').prop('disabled', checkedCount === 0);
        }

        $('#botfend-logs-form').on('submit', function(e) {
            e.preventDefault();

            var selectedIps = [];
            $('.log-checkbox:checked').each(function() {
                selectedIps.push($(this).val());
            });

            if (selectedIps.length === 0) {
                alert(botfendLogs.i18n.selectItems);
                return;
            }

            var action = $('#bulk-action-selector').val();
            if (!action) {
                alert(botfendLogs.i18n.selectAction);
                return;
            }

            var actionLabels = {
                'block_selected': botfendLogs.i18n.blocking,
                'whitelist_selected': botfendLogs.i18n.whitelisting,
                'delete_selected': botfendLogs.i18n.deleting
            };

            var actionLabel = actionLabels[action] || botfendLogs.i18n.processing;

            if (confirm(botfendLogs.i18n.confirmAction + ' ' + actionLabel.toLowerCase() + ' ' + selectedIps.length + ' ' + botfendLogs.i18n.items)) {
                $('#clearing-progress h3').text(actionLabel + '...');
                $('#clearing-progress').fadeIn(200);

                var formData = new FormData();
                formData.append('selected_ips', JSON.stringify(selectedIps));
                formData.append('bulk_action', action);
                formData.append('apply_bulk_action', '1');
                formData.append('_wpnonce', botfendLogs.nonce);

                fetch(window.location.href, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(function(response) {
                    return response.text();
                })
                .then(function() {
                    $('#clearing-progress').hide();
                    location.reload();
                })
                .catch(function() {
                    $('#clearing-progress').hide();
                    alert(botfendLogs.i18n.errorBulk);
                });
            }
        });

        // ============================================
        // ROW DETAILS DROPDOWN
        // ============================================
        $('.botfend-details-toggle').on('click', function(e) {
            e.stopPropagation();
            var $button = $(this);
            var $content = $button.next('.botfend-details-content');
            var isExpanded = $button.attr('aria-expanded') === 'true';

            $('.botfend-details-toggle').not($button).attr('aria-expanded', 'false');
            $('.botfend-details-content').not($content).fadeOut(150);

            $button.attr('aria-expanded', !isExpanded);
            if (!isExpanded) {
                $content.fadeIn(150);
            } else {
                $content.fadeOut(150);
            }
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.botfend-details-dropdown').length) {
                $('.botfend-details-toggle').attr('aria-expanded', 'false');
                $('.botfend-details-content').fadeOut(150);
            }
        });

        // ============================================
        // FACTORS ANALYSIS MODAL
        // ============================================
        $('.botfend-factors-button').on('click', function() {
            var factors = $(this).data('factors');
            $('#botfend-factors-content').html('<pre>' + $('<div>').text(factors).html() + '</pre>');
            $('#botfend-factors-modal').fadeIn(200);
        });

        $('.botfend-modal-close-icon, .botfend-modal-backdrop').on('click', function() {
            $('#botfend-factors-modal').fadeOut(200);
        });

        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#botfend-factors-modal').is(':visible')) {
                $('#botfend-factors-modal').fadeOut(200);
            }
        });

        // ============================================
        // CLEAR LOGS / AGGREGATES
        // ============================================
        $('#clear-logs-btn').on('click', function(e) {
            e.preventDefault();

            if (confirm(botfendLogs.i18n.confirmClearLogs)) {
                var url = $(this).data('url');
                $('#clearing-progress h3').text(botfendLogs.i18n.clearingLogs);
                $('#clearing-progress').fadeIn(200);

                $.ajax({
                    url: url,
                    method: 'GET',
                    success: function() {
                        window.location.href = botfendLogs.clearSuccessUrl;
                    },
                    error: function() {
                        alert(botfendLogs.i18n.errorClearLogs);
                        $('#clearing-progress').hide();
                    }
                });
            }
        });

        $('#clear-aggregates-btn').on('click', function(e) {
            e.preventDefault();

            if (confirm(botfendLogs.i18n.confirmClearAggregates)) {
                var url = $(this).data('url');
                $('#clearing-progress h3').text(botfendLogs.i18n.clearingAggregates);
                $('#clearing-progress').fadeIn(200);

                $.ajax({
                    url: url,
                    method: 'GET',
                    success: function() {
                        window.location.href = botfendLogs.aggregateClearSuccessUrl;
                    },
                    error: function() {
                        alert(botfendLogs.i18n.errorClearAggregates);
                        $('#clearing-progress').hide();
                    }
                });
            }
        });

        // ============================================
        // AUTO REFRESH
        // ============================================
        if (!isClearing && typeof config !== 'undefined' && config.autoRefresh) {
            setTimeout(function() {
                location.reload();
            }, config.refreshInterval);
        }
    });

})(jQuery);