/**
 * BotFend Anti-Bot Firewall Blocklist Page JavaScript
 *
 * Handles bulk actions, context dropdowns (3-dot menu), modals for details,
 * and action buttons (View Logs, Unblock, Make Permanent)
 *
 * @since 4.6.0
 */

(function($) {
    'use strict';

    /**
     * Initialize all blocklist page functionality
     */
    function initBotFendBlocklist() {
        initNotices();
        initBulkActions();
        initDetailsDropdowns();
        initFactorsModal();
        initQuickBlockForm();
        initAutoFocusPrevention();
    }

    /**
     * Notice Auto-Dismiss
     */
    function initNotices() {
        // Auto-hide notices after 5 seconds
        setTimeout(function() {
            $('.botfend-notice').fadeOut('slow', function() {
                $(this).remove();
            });
        }, 5000);

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

    /**
     * Bulk Actions - Select all, update button state, submit
     */
    function initBulkActions() {
        // Select all checkbox
        $('#select-all-logs').on('change', function() {
            $('.log-checkbox').prop('checked', $(this).is(':checked'));
            updateBulkActionBar();
        });

        // Individual checkboxes
        $(document).on('change', '.log-checkbox', function() {
            updateBulkActionBar();
        });

        // Update bulk action bar visibility
        function updateBulkActionBar() {
            var checkedCount = $('.log-checkbox:checked').length;
            if (checkedCount > 0) {
                $('#botfend-bulk-action-bar').show();
                $('#botfend-selected-count').text(checkedCount);
            } else {
                $('#botfend-bulk-action-bar').hide();
            }
        }

        // Apply bulk action (unblock selected)
        $('#botfend-apply-bulk-action').on('click', function(e) {
            e.preventDefault();

            var checkedCount = $('.log-checkbox:checked').length;
            if (checkedCount === 0) {
                alert(botfendBlocklist.selectItems);
                return;
            }

            if (confirm(botfendBlocklist.confirmUnblock)) {
                $('#clearing-progress h3').text(botfendBlocklist.processing);
                $('#clearing-progress').fadeIn(200);
                $('#botfend-blocklist-form').submit();
            }
        });

        // Cancel/clear selection
        $('#botfend-cancel-bulk-action').on('click', function() {
            $('.log-checkbox').prop('checked', false);
            $('#select-all-logs').prop('checked', false);
            updateBulkActionBar();
        });

        // Initial update
        updateBulkActionBar();
    }

    /**
     * Details Dropdowns (3-dot menu) - Toggle content visibility
     */
    function initDetailsDropdowns() {
        // Toggle dropdown on button click
        $(document).on('click', '.botfend-details-toggle', function(e) {
            e.stopPropagation();
            var $button = $(this);
            var $content = $button.next('.botfend-details-content');
            var isExpanded = $button.attr('aria-expanded') === 'true';

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

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

        // Close dropdowns when clicking outside
        $(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 Modal - Parse JSON and Show detection details in formatted UI
     * Triggered by "View Details" button inside dropdown
     */
    function initFactorsModal() {
        // Open modal on View Details button click
        $(document).on('click', '.botfend-factors-button', function(e) {
            e.preventDefault();
            
            var factors = $(this).data('factors');
            
            // Handle cases where data is parsed automatically vs raw string
            if (typeof factors === 'string') {
                try {
                    factors = JSON.parse(factors);
                } catch (err) {
                    console.error('BotFend: Error parsing factors JSON', err);
                    factors = [];
                }
            }
            
            var $content = $('#botfend-factors-content');
            $content.empty(); // Clear the modal content
            
            // Build the HTML UI
            if (factors && factors.length > 0) {
                var html = '<ul class="botfend-factors-list">';
                
                factors.forEach(function(factor) {
                    // Determine color based on severity
                    var severityClass = 'severity-' + (factor.severity ? factor.severity : 'info');
                    
                    // Format the text
                    var type = factor.type ? factor.type.replace(/_/g, ' ') : 'Event';
                    var scoreHtml = factor.score ? '<span class="factor-score">+' + factor.score + ' Score</span>' : '';
                    var timeHtml = factor.timestamp ? '<span class="factor-time">' + factor.timestamp + '</span>' : '';
                    var description = factor.description ? factor.description : 'No description provided.';
                    
                    // Construct the card
                    html += '<li class="botfend-factor-item ' + severityClass + '">';
                    html += '  <div class="factor-header">';
                    html += '    <strong class="factor-type">' + type + '</strong>';
                    html += '    ' + timeHtml;
                    html += '  </div>';
                    html += '  <div class="factor-description">' + description + '</div>';
                    html += '  ' + scoreHtml;
                    html += '</li>';
                });
                
                html += '</ul>';
                $content.html(html);
            } else {
                $content.html('<p class="botfend-no-factors">No detailed factors recorded for this event.</p>');
            }
            
            $('#botfend-factors-modal').fadeIn(200);
        });

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

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

    /**
     * Quick Block Form - Manual IP/Range blocking
     */
    function initQuickBlockForm() {
        // Validate IP/CIDR before submit (HTML5 pattern already does basic, but add extra)
        $('.botfend-quick-block-form').on('submit', function(e) {
            var ipInput = $('#manual-ip');
            var ip = ipInput.val().trim();
            if (!ip) {
                alert('Please enter an IP address or CIDR range.');
                e.preventDefault();
                return false;
            }
            // Basic IPv4/IPv6/CIDR validation (additional to HTML5 pattern)
            var ipv4Pattern = /^(\d{1,3}\.){3}\d{1,3}$/;
            var ipv6Pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^([0-9a-fA-F]{1,4}:){1,7}:$|^([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}$/;
            var cidrPattern = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$|^([0-9a-fA-F:]+)\/\d{1,3}$/i;
            if (!ipv4Pattern.test(ip) && !ipv6Pattern.test(ip) && !cidrPattern.test(ip)) {
                alert('Invalid IP address or CIDR range. Please enter a valid IPv4, IPv6, or CIDR (e.g., 192.168.1.0/24).');
                e.preventDefault();
                return false;
            }
            return true;
        });
    }

    /**
     * Prevent autofocus on manual IP input after certain actions
     */
    function initAutoFocusPrevention() {
        // If the prevent_autofocus flag is set (via PHP), skip focusing
        if (typeof botfendBlocklist !== 'undefined' && botfendBlocklist.preventAutofocus === '1') {
            return;
        }
        // Otherwise focus the manual IP input if empty
        if ($('#manual-ip').length && !$('#manual-ip').val()) {
            setTimeout(function() {
                $('#manual-ip').focus();
            }, 100);
        }
    }

    /**
     * Helper: Handle AJAX for make permanent (optional, can also use direct link)
     */
    function initAjaxActions() {
        // Make Permanent via AJAX (optional, if you want to avoid page reload)
        $(document).on('click', '.botfend-make-permanent-ajax', function(e) {
            e.preventDefault();
            var $link = $(this);
            var url = $link.attr('href');
            var ip = $link.data('ip');
            if (!confirm(botfendBlocklist.confirmMakePermanent)) return;

            $.ajax({
                url: url,
                method: 'GET',
                beforeSend: function() {
                    $link.text('...').prop('disabled', true);
                },
                success: function(response) {
                    location.reload();
                },
                error: function() {
                    alert(botfendBlocklist.permanentError);
                    $link.text(botfendBlocklist.makePermanentText).prop('disabled', false);
                }
            });
        });

        // Unblock via AJAX (optional)
        $(document).on('click', '.botfend-unblock-ajax', function(e) {
            e.preventDefault();
            var $link = $(this);
            var url = $link.attr('href');
            if (!confirm(botfendBlocklist.confirmUnblock)) return;

            $.ajax({
                url: url,
                method: 'GET',
                beforeSend: function() {
                    $link.text('...').prop('disabled', true);
                },
                success: function(response) {
                    location.reload();
                },
                error: function() {
                    alert(botfendBlocklist.unblockError);
                    $link.text(botfendBlocklist.unblockText).prop('disabled', false);
                }
            });
        });
    }

    // Initialize when document is ready
    $(document).ready(function() {
        initBotFendBlocklist();
        // Uncomment if you want AJAX actions instead of page reload
        // initAjaxActions();
    });

})(jQuery);