/**
 * SafeBot Defender 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 initSafeBotBlocklist() {
        initNotices();
        initBulkActions();
        initDetailsDropdowns();
        initFactorsModal();
        initQuickBlockForm();
        initAutoFocusPrevention();
    }

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

        // Handle dismiss button clicks
        $('.safebot-notice .notice-dismiss').on('click', function() {
            $(this).closest('.safebot-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) {
                $('#safebot-bulk-action-bar').show();
                $('#safebot-selected-count').text(checkedCount);
            } else {
                $('#safebot-bulk-action-bar').hide();
            }
        }

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

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

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

        // Cancel/clear selection
        $('#safebot-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', '.safebot-details-toggle', function(e) {
            e.stopPropagation();
            var $button = $(this);
            var $content = $button.next('.safebot-details-content');
            var isExpanded = $button.attr('aria-expanded') === 'true';

            // Close all other dropdowns
            $('.safebot-details-toggle').not($button).attr('aria-expanded', 'false');
            $('.safebot-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('.safebot-details-dropdown').length) {
                $('.safebot-details-toggle').attr('aria-expanded', 'false');
                $('.safebot-details-content').fadeOut(150);
            }
        });
    }

    /**
     * Factors Modal - Show detection details in modal
     * Triggered by "View Details" button inside dropdown
     */
    function initFactorsModal() {
        // Open modal on View Details button click
        $(document).on('click', '.safebot-factors-button', function() {
            var factors = $(this).data('factors');
            var formattedJson = JSON.stringify(factors, null, 2);
            var escaped = $('<div>').text(formattedJson).html();
            $('#safebot-factors-content').html('<pre>' + escaped + '</pre>');
            $('#safebot-factors-modal').fadeIn(200);
        });

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

        // Close modal on ESC key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#safebot-factors-modal').is(':visible')) {
                $('#safebot-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)
        $('.safebot-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 safebotBlocklist !== 'undefined' && safebotBlocklist.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)
     * But we keep direct links as fallback; this AJAX version can be used for inline without reload.
     * Not required but nice to have.
     */
    function initAjaxActions() {
        // Make Permanent via AJAX (optional, if you want to avoid page reload)
        $(document).on('click', '.safebot-make-permanent-ajax', function(e) {
            e.preventDefault();
            var $link = $(this);
            var url = $link.attr('href');
            var ip = $link.data('ip');
            if (!confirm(safebotBlocklist.confirmMakePermanent)) return;

            $.ajax({
                url: url,
                method: 'GET',
                beforeSend: function() {
                    $link.text('...').prop('disabled', true);
                },
                success: function(response) {
                    // Reload to show updated status
                    location.reload();
                },
                error: function() {
                    alert(safebotBlocklist.permanentError);
                    $link.text(safebotBlocklist.makePermanentText).prop('disabled', false);
                }
            });
        });

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

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

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

})(jQuery);