/**
 * Guard Dog Access Control Page JavaScript
 *
 * @package GuardDog
 * @since 1.8.47
 */

(function($) {
    'use strict';

    // Initialize when document is ready
    $(document).ready(function() {
        GuardDogAccessControl.init();
    });

    const GuardDogAccessControl = {
        
        /**
         * Initialize the access control functionality
         */
        init: function() {
            this.initUserInputs();
            this.initWhitelistMirrors();
            this.initIpWhitelistManager();
            this.initFormValidation();
            this.initSecurityWarnings();
            this.initResponsiveBehavior();
            this.initQuickActions();
            this.initIpBlacklistManager();
            this.initCountryBlacklistManager();
        },

        /**
         * Keep mirrored whitelist fields in sync across tab-specific forms.
         */
        initWhitelistMirrors: function() {
            const $allowedIps = $('#guard-dog-ip-whitelist-hidden');
            const $siteWideWhitelist = $('#guard-dog-site-wide-ip-whitelist');

            if (!$allowedIps.length || !$siteWideWhitelist.length) {
                return;
            }

            const syncWhitelist = function() {
                $siteWideWhitelist.val($allowedIps.val());
            };

            $allowedIps.on('input change', syncWhitelist);
            $('.guard-dog-site-wide-form').on('submit', syncWhitelist);
            syncWhitelist();
        },

        /**
         * Initialize user input functionality for blacklist and whitelist
         */
        initUserInputs: function() {
            // Blacklist user input
            this.initUserInput(
                '#guard-dog-username-blacklist-input',
                '#guard-dog-add-blacklist-user',
                '#guard-dog-username-blacklist-suggestions',
                '#guard-dog-username-blacklist-tags',
                '#guard-dog-username-blacklist-hidden'
            );

            // Whitelist user input
            this.initUserInput(
                '#guard-dog-username-whitelist-input',
                '#guard-dog-add-whitelist-user',
                '#guard-dog-username-whitelist-suggestions',
                '#guard-dog-username-whitelist-tags',
                '#guard-dog-username-whitelist-hidden'
            );
        },

        /**
         * Initialize a user input field with suggestions and tag management
         */
        initUserInput: function(inputSelector, buttonSelector, suggestionsSelector, tagsSelector, hiddenSelector) {
            const $input = $(inputSelector);
            const $button = $(buttonSelector);
            const $suggestions = $(suggestionsSelector);
            const $tags = $(tagsSelector);
            const $hidden = $(hiddenSelector);
            
            let currentUsers = this.parseUserList($hidden.val());
            
            // Load existing users as tags
            this.renderUserTags($tags, currentUsers, hiddenSelector);

            // Handle input changes for suggestions
            $input.on('input', function() {
                const query = $(this).val().trim();
                if (query.length >= 2) {
                    GuardDogAccessControl.showUserSuggestions(query, $suggestions, $input);
                } else {
                    $suggestions.removeClass('show');
                }
            });

            // Handle suggestion clicks
            $suggestions.on('click', '.suggestion-item', function() {
                const username = $(this).text();
                $input.val('');
                $suggestions.removeClass('show');
                
                if (!currentUsers.includes(username)) {
                    currentUsers.push(username);
                    GuardDogAccessControl.updateUserTags($tags, currentUsers, hiddenSelector);
                    GuardDogAccessControl.updateHiddenField($hidden, currentUsers);
                }
            });

            // Handle add button clicks
            $button.on('click', function() {
                const username = $input.val().trim();
                if (username && !currentUsers.includes(username)) {
                    currentUsers.push(username);
                    GuardDogAccessControl.updateUserTags($tags, currentUsers, hiddenSelector);
                    GuardDogAccessControl.updateHiddenField($hidden, currentUsers);
                    $input.val('');
                    $suggestions.removeClass('show');
                }
            });

            // Handle enter key
            $input.on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $button.click();
                }
            });

            // Handle tag removal
            $tags.on('click', '.remove-tag', function() {
                const username = $(this).siblings('span').text();
                currentUsers = currentUsers.filter(user => user !== username);
                GuardDogAccessControl.updateUserTags($tags, currentUsers, hiddenSelector);
                GuardDogAccessControl.updateHiddenField($hidden, currentUsers);
            });

            // Close suggestions when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest(inputSelector + ', ' + suggestionsSelector).length) {
                    $suggestions.removeClass('show');
                }
            });
        },

        /**
         * Show user suggestions based on input
         */
        showUserSuggestions: function(query, $suggestions, $input) {
            // Check if AJAX data is available
            if (typeof guard_dog_ajax === 'undefined' || !guard_dog_ajax.nonce) {
                return;
            }

            // Get current users to exclude from suggestions
            const currentUsers = this.parseUserList($('#guard-dog-username-blacklist-hidden').val())
                .concat(this.parseUserList($('#guard-dog-username-whitelist-hidden').val()));

            // AJAX request to get user suggestions
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'guard_dog_get_user_suggestions',
                    query: query,
                    nonce: guard_dog_ajax.nonce
                },
                success: function(response) {
                    if (response.success && response.data.length > 0) {
                        const suggestions = response.data.filter(user => 
                            !currentUsers.includes(user.user_login)
                        );
                        
                        if (suggestions.length > 0) {
                            GuardDogAccessControl.renderSuggestions($suggestions, suggestions);
                            $suggestions.addClass('show');
                        } else {
                            $suggestions.removeClass('show');
                        }
                    } else {
                        $suggestions.removeClass('show');
                    }
                },
                error: function() {
                    $suggestions.removeClass('show');
                }
            });
        },

        /**
         * Render suggestions dropdown
         */
        renderSuggestions: function($suggestions, users) {
            $suggestions.empty();
            
            users.forEach(function(user) {
                const $item = $('<div class="suggestion-item">' + user.user_login + '</div>');
                $suggestions.append($item);
            });
        },

        /**
         * Parse comma-separated user list
         */
        parseUserList: function(userString) {
            if (!userString) return [];
            return userString.split(',').map(user => user.trim()).filter(user => user.length > 0);
        },

        /**
         * Update user tags display
         */
        updateUserTags: function($tags, users, hiddenSelector) {
            $tags.empty();
            
            users.forEach(function(username) {
                const $tag = $(`
                    <div class="guard-dog-user-tag">
                        <span>${username}</span>
                        <button type="button" class="remove-tag" aria-label="Remove ${username}">×</button>
                    </div>
                `);
                $tags.append($tag);
            });
        },

        /**
         * Update hidden field with user list
         */
        updateHiddenField: function($hidden, users) {
            $hidden.val(users.join(', '));
        },

        /**
         * Render existing user tags on page load
         */
        renderUserTags: function($tags, users, hiddenSelector) {
            this.updateUserTags($tags, users, hiddenSelector);
        },

        /**
         * Initialize form validation
         */
        initFormValidation: function() {
            const $form = $('.guard-dog-ip-management-form, .guard-dog-site-wide-form');
            
            $form.on('submit', function(e) {
                const $blockedIps = $('textarea[name="guard_dog_ip_blacklist"]');
                const $allowedIps = $('#guard-dog-ip-whitelist-hidden');
                
                // Validate IP addresses
                const blockedIps = $blockedIps.length ? $blockedIps.val().trim() : '';
                const allowedIps = $allowedIps.length ? $allowedIps.val().trim() : '';
                
                let hasErrors = false;
                
                // Clear previous errors
                $('.guard-dog-error').remove();
                $('.guard-dog-input-error').removeClass('guard-dog-input-error');
                
                // Validate blocked IPs
                if (blockedIps) {
                    const invalidIps = GuardDogAccessControl.validateIpList(blockedIps);
                    if (invalidIps.length > 0) {
                        GuardDogAccessControl.showFieldError($blockedIps, 
                            'Invalid IP addresses: ' + invalidIps.join(', '));
                        hasErrors = true;
                    }
                }
                
                // Validate allowed IPs
                if (allowedIps) {
                    const invalidIps = GuardDogAccessControl.validateIpList(allowedIps);
                    if (invalidIps.length > 0) {
                        GuardDogAccessControl.showFieldError($allowedIps, 
                            'Invalid IP addresses: ' + invalidIps.join(', '));
                        hasErrors = true;
                    }
                }
                
                if (hasErrors) {
                    e.preventDefault();
                    return false;
                }
            });
        },

        /**
         * Validate IP address list
         */
        validateIpList: function(ipList) {
            const ips = ipList.split('\n')
                .map(ip => GuardDogAccessControl.extractIpFromWhitelistLine(ip.trim()))
                .filter(ip => ip.length > 0);
            const invalidIps = [];
            
            ips.forEach(function(ip) {
                if (!GuardDogAccessControl.isValidIp(ip)) {
                    invalidIps.push(ip);
                }
            });
            
            return invalidIps;
        },

        /**
         * Extract the IP/CIDR portion from a whitelist line that may include a note.
         */
        extractIpFromWhitelistLine: function(line) {
            if (!line) {
                return '';
            }

            if (line.indexOf('|') !== -1) {
                return line.split('|')[0].trim();
            }

            if (line.indexOf('\t') !== -1) {
                return line.split('\t')[0].trim();
            }

            if (/\s+#\s+/.test(line)) {
                return line.split(/\s+#\s+/)[0].trim();
            }

            return line.trim();
        },

        /**
         * Check if IP address is valid (supports IPv4, IPv6, and CIDR notation)
         */
        isValidIp: function(ip) {
            // IPv4 validation regex (supports CIDR notation)
            const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/([0-9]|[1-2][0-9]|3[0-2]))?$/;
            
            // IPv6 validation regex (supports CIDR notation)
            const ipv6Regex = /^(?:(?:[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}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(?:\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/;
            
            return ipv4Regex.test(ip) || ipv6Regex.test(ip);
        },

        /**
         * Show field error
         */
        showFieldError: function($field, message) {
            $field.addClass('guard-dog-input-error');
            $field.after('<div class="guard-dog-error">' + message + '</div>');
        },

        /**
         * Initialize security warnings
         */
        initSecurityWarnings: function() {
            const $blockedIps = $('textarea[name="guard_dog_ip_blacklist"]');
            
            // Show warning if user is about to block their own IP
            $blockedIps.on('input', function() {
                const currentIp = guard_dog_ajax.current_ip;
                const blockedIps = $(this).val().split('\n').map(ip => ip.trim());
                
                if (blockedIps.includes(currentIp)) {
                    GuardDogAccessControl.showSecurityWarning(
                        'Warning: You are about to block your current IP address (' + currentIp + '). ' +
                        'This may lock you out of the admin area.'
                    );
                }
            });
        },

        /**
         * Show security warning
         */
        showSecurityWarning: function(message) {
            // Remove existing warnings
            $('.guard-dog-security-warning').remove();
            
            const $warning = $(`
                <div class="guard-dog-security-warning notice notice-warning">
                    <p><strong>⚠️ Security Warning:</strong> ${message}</p>
                </div>
            `);
            
            $('.guard-dog-form-section').prepend($warning);
        },

        /**
         * Initialize responsive behavior
         */
        initResponsiveBehavior: function() {
            // Handle mobile view adjustments
            $(window).on('resize', function() {
                if ($(window).width() <= 768) {
                    $('.guard-dog-user-input-wrapper').addClass('mobile-layout');
                } else {
                    $('.guard-dog-user-input-wrapper').removeClass('mobile-layout');
                }
            });
            
            // Trigger initial check
            $(window).trigger('resize');
        },

        /**
         * Initialize quick actions
         */
        initQuickActions: function() {
            $('.guard-dog-quick-action').on('click', function(e) {
                e.preventDefault();
                const action = $(this).text().trim();
                
                switch(action) {
                    case 'Add My IP to Whitelist':
                        GuardDogAccessControl.whitelistCurrentIp();
                        break;
                }
            });
        },

        /**
         * Whitelist current IP
         */
        whitelistCurrentIp: function() {
            // Check if AJAX data is available
            if (typeof guard_dog_ajax === 'undefined' || !guard_dog_ajax.current_ip) {
                alert('Unable to determine your current IP address. Please add it manually.');
                return;
            }

            const currentIp = guard_dog_ajax.current_ip;
            const $allowedIps = $('#guard-dog-ip-whitelist-hidden');

            if ($allowedIps.length) {
                const entries = this.getWhitelistEntries();
                const existing = entries.some(entry => entry.ip === currentIp);

                if (!existing) {
                    entries.push({
                        ip: currentIp,
                        note: 'Current IP'
                    });
                    this.setWhitelistEntries(entries);
                }
            } else {
                const $legacyAllowedIps = $('textarea[name="guard_dog_ip_whitelist"]');
                const currentIps = $legacyAllowedIps.val().trim();

                if (currentIps && !currentIps.includes(currentIp)) {
                    $legacyAllowedIps.val(currentIps + '\n' + currentIp).trigger('change');
                } else if (!currentIps) {
                    $legacyAllowedIps.val(currentIp).trigger('change');
                }
            }
            
            alert('Your current IP (' + currentIp + ') has been added to the whitelist.');
        },

        /**
         * Initialize IP whitelist manager with notes.
         */
        initIpWhitelistManager: function() {
            const $manager = $('.guard-dog-ip-whitelist-manager');

            if (!$manager.length) {
                return;
            }

            this.renderWhitelistTable(this.getWhitelistEntries());

            $('#guard-dog-add-whitelist-ip-button').on('click', function(e) {
                e.preventDefault();

                const $message = $('#guard-dog-add-whitelist-ip-message');
                const $ipInput = $('#guard-dog-new-whitelist-ip-address');
                const $noteInput = $('#guard-dog-new-whitelist-ip-note');
                const ipAddress = $ipInput.val().trim();
                const note = $noteInput.val().trim();

                $message.empty();

                if (!ipAddress) {
                    $message.html('<span class="guard-dog-message-error">Please enter an IP address.</span>');
                    return;
                }

                if (!GuardDogAccessControl.isValidIp(ipAddress)) {
                    $message.html('<span class="guard-dog-message-error">Invalid IP address format.</span>');
                    return;
                }

                const entries = GuardDogAccessControl.getWhitelistEntries();

                if (entries.some(entry => entry.ip === ipAddress)) {
                    $message.html('<span class="guard-dog-message-error">This IP address is already in the whitelist.</span>');
                    return;
                }

                entries.push({
                    ip: ipAddress,
                    note: note
                });

                GuardDogAccessControl.setWhitelistEntries(entries);
                $ipInput.val('');
                $noteInput.val('');
                $message.html('<span class="guard-dog-message-success">IP address added. Save IP Settings to persist the whitelist.</span>');
            });

            $(document).on('click', '.guard-dog-remove-whitelist-ip', function(e) {
                e.preventDefault();

                const $button = $(this);
                const ipAddress = $button.data('ip');
                const $message = $('#guard-dog-add-whitelist-ip-message');

                if (!confirm('Are you sure you want to remove ' + ipAddress + ' from the whitelist?')) {
                    return;
                }

                if (typeof guard_dog_admin === 'undefined' || !guard_dog_admin.nonce) {
                    alert('Security nonce not available. Please refresh the page and try again.');
                    return;
                }

                $button.prop('disabled', true).text('Removing...');
                $message.html('<span class="guard-dog-message-info">Removing IP from whitelist...</span>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_remove_ip_from_whitelist',
                        ip_address: ipAddress,
                        nonce: guard_dog_admin.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            const entries = GuardDogAccessControl.getWhitelistEntries()
                                .filter(entry => entry.ip !== ipAddress);

                            GuardDogAccessControl.setWhitelistEntries(entries);
                            $message.html('<span class="guard-dog-message-success">' + response.data.message + '</span>');
                        } else {
                            alert(response.data && response.data.message ? response.data.message : 'Failed to remove IP address.');
                            $button.prop('disabled', false).text('Remove');
                            $message.empty();
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                        $button.prop('disabled', false).text('Remove');
                        $message.empty();
                    }
                });
            });
        },

        /**
         * Get structured whitelist entries from the hidden field.
         */
        getWhitelistEntries: function() {
            const $hidden = $('#guard-dog-ip-whitelist-hidden');

            if (!$hidden.length || !$hidden.val()) {
                return [];
            }

            return $hidden.val().split('\n').map(function(line) {
                const parts = GuardDogAccessControl.parseWhitelistLine(line);
                return parts.ip ? parts : null;
            }).filter(Boolean);
        },

        /**
         * Persist structured whitelist entries back to the hidden field and table.
         */
        setWhitelistEntries: function(entries) {
            const serialized = this.serializeWhitelistEntries(entries);

            $('#guard-dog-ip-whitelist-hidden').val(serialized).trigger('change');
            $('#guard-dog-site-wide-ip-whitelist').val(serialized);
            this.renderWhitelistTable(entries);
        },

        /**
         * Parse one stored whitelist line.
         */
        parseWhitelistLine: function(line) {
            const rawLine = (line || '').trim();

            if (!rawLine) {
                return {
                    ip: '',
                    note: ''
                };
            }

            let ip = rawLine;
            let note = '';

            if (rawLine.indexOf('|') !== -1) {
                const parts = rawLine.split('|');
                ip = parts.shift().trim();
                note = parts.join('|').trim();
            } else if (rawLine.indexOf('\t') !== -1) {
                const parts = rawLine.split('\t');
                ip = parts.shift().trim();
                note = parts.join('\t').trim();
            } else if (/\s+#\s+/.test(rawLine)) {
                const parts = rawLine.split(/\s+#\s+/);
                ip = parts.shift().trim();
                note = parts.join(' # ').trim();
            }

            return {
                ip: ip,
                note: note
            };
        },

        /**
         * Serialize whitelist entries to the Settings API field format.
         */
        serializeWhitelistEntries: function(entries) {
            const seen = {};

            return entries.map(function(entry) {
                const ip = (entry.ip || '').trim();
                const note = (entry.note || '').trim().replace(/\s*\|\s*/g, ' ');

                if (!ip || seen[ip]) {
                    return '';
                }

                seen[ip] = true;

                return note ? ip + ' | ' + note : ip;
            }).filter(Boolean).join('\n');
        },

        /**
         * Render the whitelist table without shifting the surrounding form.
         */
        renderWhitelistTable: function(entries) {
            const $table = $('#guard-dog-ip-whitelist-table');
            const $tbody = $table.find('tbody');
            const $empty = $('.guard-dog-ip-whitelist-table-wrapper .guard-dog-list-empty');

            if (!$table.length || !$tbody.length) {
                return;
            }

            $tbody.empty();

            if (!entries.length) {
                $table.hide();
                $empty.prop('hidden', false);
                return;
            }

            $table.show();
            $empty.prop('hidden', true);

            entries.forEach(function(entry) {
                const $row = $('<tr></tr>')
                    .attr('data-ip', entry.ip)
                    .attr('data-note', entry.note || '');
                const $ipCell = $('<td></td>').append($('<code></code>').text(entry.ip));
                const $noteCell = $('<td></td>');
                const $actionsCell = $('<td></td>');

                if (entry.note) {
                    $noteCell.text(entry.note);
                } else {
                    $noteCell.append($('<span class="guard-dog-muted-text"></span>').text('No note'));
                }

                $actionsCell.append(
                    $('<button type="button" class="button button-small guard-dog-remove-whitelist-ip">Remove</button>')
                        .attr('data-ip', entry.ip)
                );

                $row.append($ipCell, $noteCell, $actionsCell);
                $tbody.append($row);
            });
        },

        /**
         * Initialize IP blacklist manager (for structured blacklist with expiration)
         */
        initIpBlacklistManager: function() {
            const $addButton = $('#guard-dog-add-ip-button');
            const $removeButtons = $('.guard-dog-remove-ip');
            const $message = $('#guard-dog-add-ip-message');

            // Handle add IP button
            $addButton.on('click', function(e) {
                e.preventDefault();
                const $button = $(this);
                const ipAddress = $('#guard-dog-new-ip-address').val().trim();
                const expirationDays = parseInt($('#guard-dog-new-ip-expiration').val(), 10) || 0;
                const reason = $('#guard-dog-new-ip-reason').val().trim();

                if (!ipAddress) {
                    $message.html('<span style="color: #d63638;">Please enter an IP address.</span>');
                    return;
                }

                // Validate IP
                if (!GuardDogAccessControl.isValidIp(ipAddress)) {
                    $message.html('<span style="color: #d63638;">Invalid IP address format.</span>');
                    return;
                }

                // Disable button and show loading
                $button.prop('disabled', true).text('Adding...');
                $message.html('<span style="color: #2271b1;">Adding IP to blacklist...</span>');

                // AJAX request to add IP
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_add_ip_to_blacklist',
                        ip_address: ipAddress,
                        expiration_days: expirationDays,
                        reason: reason,
                        source: 'manual',
                        nonce: typeof guard_dog_admin !== 'undefined' ? guard_dog_admin.nonce : ''
                    },
                    success: function(response) {
                        if (response.success) {
                            $message.html('<span style="color: #00a32a;">' + response.data.message + '</span>');
                            // Clear form
                            $('#guard-dog-new-ip-address').val('');
                            $('#guard-dog-new-ip-expiration').val('30');
                            $('#guard-dog-new-ip-reason').val('');
                            // Reload page after 1 second to show updated list
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            $message.html('<span style="color: #d63638;">' + (response.data && response.data.message ? response.data.message : 'Failed to add IP address.') + '</span>');
                            $button.prop('disabled', false).text('Add IP to Blacklist');
                        }
                    },
                    error: function() {
                        $message.html('<span style="color: #d63638;">An error occurred. Please try again.</span>');
                        $button.prop('disabled', false).text('Add IP to Blacklist');
                    }
                });
            });

            // Handle remove IP buttons
            $removeButtons.on('click', function(e) {
                e.preventDefault();
                const $button = $(this);
                const ipAddress = $button.data('ip');

                if (!confirm('Are you sure you want to remove ' + ipAddress + ' from the blacklist?')) {
                    return;
                }

                // Disable button and show loading
                $button.prop('disabled', true).text('Removing...');

                // AJAX request to remove IP
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_remove_ip_from_blacklist',
                        ip_address: ipAddress,
                        nonce: typeof guard_dog_admin !== 'undefined' ? guard_dog_admin.nonce : ''
                    },
                    success: function(response) {
                        if (response.success) {
                            // Remove row from table
                            $button.closest('tr').fadeOut(300, function() {
                                $(this).remove();
                                // If no more rows, show empty message
                                if ($('#guard-dog-ip-blacklist-table tbody tr').length === 0) {
                                    $('.guard-dog-ip-blacklist-table-wrapper').html('<p>No IP addresses are currently blacklisted.</p>');
                                }
                            });
                        } else {
                            alert(response.data && response.data.message ? response.data.message : 'Failed to remove IP address.');
                            $button.prop('disabled', false).text('Remove');
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                        $button.prop('disabled', false).text('Remove');
                    }
                });
            });
        },

        /**
         * Initialize country blacklist manager (for structured blacklist with expiration)
         */
        initCountryBlacklistManager: function() {
            const $addButton = $('#guard-dog-add-country-button');
            const $message = $('#guard-dog-add-country-message');
            const $countryInput = $('#guard-dog-new-country-code');
            const $countryCodeHidden = $('#guard-dog-new-country-code-value');
            const $suggestions = $('#guard-dog-country-suggestions');
            
            // Get countries data from JSON script tag
            let countriesData = [];
            const $countriesScript = $('#guard-dog-countries-data');
            if ($countriesScript.length) {
                try {
                    countriesData = JSON.parse($countriesScript.html());
                } catch (e) {
                    console.error('Failed to parse countries data:', e);
                }
            }

            let selectedCountry = null;
            let highlightedIndex = -1;

            // Search countries function
            function searchCountries(query) {
                if (!query || query.length < 1) {
                    return [];
                }
                
                const searchLower = query.toLowerCase().trim();
                const results = [];
                
                // Search through country names and codes
                countriesData.forEach(function(country) {
                    const nameLower = country.name.toLowerCase();
                    const codeLower = country.code.toLowerCase();
                    
                    // Check if query matches country name (partial match) or code (exact match)
                    if (nameLower.includes(searchLower) || codeLower === searchLower) {
                        // Calculate relevance score (exact name match > starts with > contains)
                        let score = 0;
                        if (nameLower === searchLower) {
                            score = 100; // Exact match
                        } else if (nameLower.startsWith(searchLower)) {
                            score = 50; // Starts with
                        } else {
                            score = 25; // Contains
                        }
                        
                        results.push({
                            ...country,
                            score: score
                        });
                    }
                });
                
                // Sort by relevance score (highest first)
                results.sort(function(a, b) {
                    return b.score - a.score;
                });
                
                return results.slice(0, 10); // Limit to 10 results
            }

            // Render suggestions
            function renderSuggestions(results) {
                $suggestions.empty();
                
                if (results.length === 0) {
                    $suggestions.append('<div class="guard-dog-country-suggestions-empty">No countries found</div>');
                    $suggestions.show();
                    return;
                }
                
                results.forEach(function(country, index) {
                    const $item = $('<div class="guard-dog-country-suggestion-item" data-index="' + index + '" data-code="' + country.code + '">' +
                        '<span class="country-flag">' + country.flag + '</span>' +
                        '<span class="country-name">' + country.name + '</span>' +
                        '<span class="country-code">' + country.code + '</span>' +
                        '</div>');
                    
                    $item.on('click', function() {
                        selectCountry(country);
                    });
                    
                    $item.on('mouseenter', function() {
                        highlightedIndex = index;
                        updateHighlight();
                    });
                    
                    $suggestions.append($item);
                });
                
                highlightedIndex = 0;
                updateHighlight();
                $suggestions.show();
            }

            // Update highlighted item
            function updateHighlight() {
                $suggestions.find('.guard-dog-country-suggestion-item').removeClass('highlighted');
                $suggestions.find('.guard-dog-country-suggestion-item[data-index="' + highlightedIndex + '"]').addClass('highlighted');
            }

            // Select a country
            function selectCountry(country) {
                selectedCountry = country;
                $countryInput.val(country.name);
                $countryCodeHidden.val(country.code);
                $suggestions.hide();
                highlightedIndex = -1;
            }

            // Handle input changes
            $countryInput.on('input', function() {
                const query = $(this).val();
                selectedCountry = null;
                $countryCodeHidden.val('');
                
                if (query.length < 1) {
                    $suggestions.hide();
                    return;
                }
                
                const results = searchCountries(query);
                renderSuggestions(results);
            });

            // Handle keyboard navigation
            $countryInput.on('keydown', function(e) {
                if (!$suggestions.is(':visible')) {
                    return;
                }
                
                const $items = $suggestions.find('.guard-dog-country-suggestion-item');
                const totalItems = $items.length;
                
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    highlightedIndex = (highlightedIndex + 1) % totalItems;
                    updateHighlight();
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    highlightedIndex = highlightedIndex <= 0 ? totalItems - 1 : highlightedIndex - 1;
                    updateHighlight();
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    const $highlighted = $suggestions.find('.guard-dog-country-suggestion-item.highlighted');
                    if ($highlighted.length) {
                        const code = $highlighted.data('code');
                        const country = countriesData.find(c => c.code === code);
                        if (country) {
                            selectCountry(country);
                        }
                    } else if (selectedCountry) {
                        // If already selected, submit form
                        $addButton.click();
                    }
                } else if (e.key === 'Escape') {
                    $suggestions.hide();
                    highlightedIndex = -1;
                }
            });

            // Hide suggestions when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('#guard-dog-new-country-code, #guard-dog-country-suggestions').length) {
                    $suggestions.hide();
                }
            });

            // Handle add country button
            $addButton.on('click', function(e) {
                e.preventDefault();
                const $button = $(this);
                
                // Get country code from hidden field (set when country is selected)
                let countryCode = $countryCodeHidden.val().trim().toUpperCase();
                
                // If no code in hidden field, try to find it from input
                if (!countryCode) {
                    const inputValue = $countryInput.val().trim();
                    
                    // Try exact name match first
                    const exactMatch = countriesData.find(function(country) {
                        return country.name.toLowerCase() === inputValue.toLowerCase();
                    });
                    
                    if (exactMatch) {
                        countryCode = exactMatch.code;
                        selectedCountry = exactMatch;
                    } else {
                        // Try partial match
                        const partialMatch = countriesData.find(function(country) {
                            return country.name.toLowerCase().includes(inputValue.toLowerCase()) ||
                                   inputValue.toLowerCase().includes(country.name.toLowerCase());
                        });
                        
                        if (partialMatch) {
                            countryCode = partialMatch.code;
                            selectedCountry = partialMatch;
                        } else if (inputValue.length === 2 && /^[A-Z]{2}$/i.test(inputValue)) {
                            // Try as country code
                            const codeMatch = countriesData.find(function(country) {
                                return country.code.toUpperCase() === inputValue.toUpperCase();
                            });
                            if (codeMatch) {
                                countryCode = codeMatch.code;
                                selectedCountry = codeMatch;
                            }
                        }
                    }
                }
                
                const expirationDays = parseInt($('#guard-dog-new-country-expiration').val(), 10) || 0;
                const reason = $('#guard-dog-new-country-reason').val().trim();

                if (!countryCode) {
                    $message.html('<span style="color: #d63638;">Please select a country from the dropdown suggestions.</span>');
                    return;
                }

                // Validate country code (ISO 3166-1 alpha-2)
                if (countryCode.length !== 2 || !/^[A-Z]{2}$/.test(countryCode)) {
                    $message.html('<span style="color: #d63638;">Invalid country code. Please select a country from the suggestions.</span>');
                    return;
                }

                // Disable button and show loading
                $button.prop('disabled', true).text('Adding...');
                $message.html('<span style="color: #2271b1;">Adding country to blacklist...</span>');

                // AJAX request to add country
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_add_country_to_blacklist',
                        country_code: countryCode,
                        expiration_days: expirationDays,
                        reason: reason,
                        source: 'manual',
                        nonce: typeof guard_dog_admin !== 'undefined' ? guard_dog_admin.nonce : ''
                    },
                    success: function(response) {
                        if (response.success) {
                            $message.html('<span style="color: #00a32a;">' + response.data.message + '</span>');
                            // Clear form
                            $countryInput.val('');
                            $countryCodeHidden.val('');
                            selectedCountry = null;
                            $suggestions.hide();
                            $('#guard-dog-new-country-expiration').val('30');
                            $('#guard-dog-new-country-reason').val('');
                            // Reload page after 1 second to show updated list
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            $message.html('<span style="color: #d63638;">' + (response.data && response.data.message ? response.data.message : 'Failed to add country to blacklist.') + '</span>');
                            $button.prop('disabled', false).text('Add Country to Blacklist');
                        }
                    },
                    error: function() {
                        $message.html('<span style="color: #d63638;">An error occurred. Please try again.</span>');
                        $button.prop('disabled', false).text('Add Country to Blacklist');
                    }
                });
            });

            // Handle remove country buttons (use event delegation to handle dynamically added buttons)
            $(document).on('click', '.guard-dog-remove-country', function(e) {
                e.preventDefault();
                e.stopPropagation(); // Prevent event bubbling
                
                const $button = $(this);
                const countryCode = $button.data('country');

                // Validate country code
                if (!countryCode || countryCode.length !== 2) {
                    alert('Invalid country code. Please refresh the page and try again.');
                    return;
                }

                if (!confirm('Are you sure you want to remove ' + countryCode + ' from the blacklist?')) {
                    return;
                }

                // Disable button and show loading
                const $row = $button.closest('tr');
                $button.prop('disabled', true).text('Removing...');
                
                // Disable all remove buttons to prevent multiple clicks
                $('.guard-dog-remove-country').prop('disabled', true);

                // AJAX request to remove country
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_remove_country_from_blacklist',
                        country_code: countryCode,
                        nonce: typeof guard_dog_admin !== 'undefined' ? guard_dog_admin.nonce : ''
                    },
                    success: function(response) {
                        if (response.success) {
                            // Remove only the specific row
                            $row.fadeOut(300, function() {
                                $(this).remove();
                                // Re-enable remaining buttons
                                $('.guard-dog-remove-country').prop('disabled', false);
                                // If no more rows, show empty message
                                if ($('#guard-dog-country-blacklist-table tbody tr').length === 0) {
                                    $('.guard-dog-country-blacklist-table-wrapper').html('<p>No countries are currently blacklisted.</p>');
                                }
                            });
                        } else {
                            alert(response.data && response.data.message ? response.data.message : 'Failed to remove country from blacklist.');
                            $('.guard-dog-remove-country').prop('disabled', false);
                            $button.prop('disabled', false).text('Remove');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Remove country error:', error);
                        alert('An error occurred. Please try again.');
                        $('.guard-dog-remove-country').prop('disabled', false);
                        $button.prop('disabled', false).text('Remove');
                    }
                });
            });
        },

    };

})(jQuery); 
