/**
 * Top IPs Blocked Chart Module
 * Handles display and filtering of most blocked IP addresses
 * 
 * @package VMPFence
 * @since 2.1.0
 */

(function($) {
    'use strict';
    
    // Namespace to avoid conflicts
    window.VMPFenceTopIPsChart = {
        
        // Configuration
        config: {
            defaultPeriod: '24h',
            maxIPs: 10,
            containerSelector: '.vmpfence-top-ips-card',
            contentSelector: '.top-ips-content'
        },
        
        // Current state
        currentPeriod: '24h',
        isLoading: false,
        
        /**
         * Initialize the module
         */
        init: function() {
            // Only init if the chart container exists on the page
            if ($(this.config.containerSelector).length === 0) {
                return;
            }
            
            this.bindEvents();
            this.loadInitialData();
        },
        
        /**
         * Bind event handlers
         */
        bindEvents: function() {
            var self = this;
            
            // Handle filter tab clicks within the Top IPs card only
            $(this.config.containerSelector).on('click', '.vmpfence-filter-tab', function(e) {
                e.preventDefault();
                self.handleFilterClick($(this));
            });
        },
        
        /**
         * Load initial data
         */
        loadInitialData: function() {
            this.loadData(this.config.defaultPeriod);
        },
        
        /**
         * Handle filter tab clicks
         */
        handleFilterClick: function($tab) {
            if (this.isLoading) {
                return; // Prevent multiple simultaneous requests
            }
            
            var period = this.getPeriodFromTab($tab);
            
            // Update active state
            $(this.config.containerSelector).find('.vmpfence-filter-tab').removeClass('active');
            $tab.addClass('active');
            
            // Load data for selected period
            this.loadData(period);
        },
        
        /**
         * Get period from tab button text
         */
        getPeriodFromTab: function($tab) {
            var text = $tab.text().trim();
            
            if (text.includes('24 Hours') || text.includes('24 hours')) {
                return '24h';
            } else if (text.includes('7 Days') || text.includes('7 days')) {
                return '7d';
            } else if (text.includes('30 Days') || text.includes('30 days')) {
                return '30d';
            }
            
            return '24h'; // Default
        },
        
        /**
         * Load data via AJAX
         */
        loadData: function(period) {
            var self = this;
            
            if (!window.vmpfenceTopIPs) {
                this.showError('Configuration error: vmpfenceTopIPs not defined');
                return;
            }
            
            this.currentPeriod = period;
            this.isLoading = true;
            this.showLoading();
            
            $.ajax({
                url: vmpfenceTopIPs.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_top_blocked_ips',
                    period: period,
                    nonce: vmpfenceTopIPs.nonce
                },
                success: function(response) {
                    self.isLoading = false;
                    
                    if (response.success && response.data && response.data.ips) {
                        self.render(response.data.ips);
                    } else {
                        var errorMsg = response.data && response.data.message 
                            ? response.data.message 
                            : 'Failed to load data';
                        self.showError(errorMsg);
                    }
                },
                error: function(xhr, status, error) {
                    self.isLoading = false;
                    self.showError('Failed to load data. Please try again.');
                    
                    if (window.console && console.error) {
                        console.error('Top IPs AJAX Error:', status, error);
                    }
                }
            });
        },
        
        /**
         * Render the chart/table
         */
        render: function(ips) {
            var $content = $(this.config.containerSelector).find(this.config.contentSelector);
            
            if (!ips || ips.length === 0) {
                $content.html('<div class="empty-state">No blocks have been recorded</div>');
                return;
            }
            
            var html = '<table class="top-ips-table">';
            html += '<thead>';
            html += '<tr>';
            html += '<th>IP Address</th>';
            html += '<th style="text-align: center;">Country</th>';
            html += '<th style="text-align: center;">Blocks</th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            
            for (var i = 0; i < ips.length; i++) {
                var ip = ips[i];
                
                // Skip if IP address is null or empty
                if (!ip.ip_address) {
                    continue;
                }
                
                html += '<tr>';
                html += '<td class="ip-address">' + this.escapeHtml(ip.ip_address) + '</td>';
                html += '<td style="text-align: center;">';
                
                if (ip.countryCode && ip.countryCode !== '') {
                    html += this.escapeHtml(ip.countryCode);
                } else {
                    html += '<span style="color: #999;">--</span>';
                }
                
                html += '</td>';
                html += '<td class="block-count" style="text-align: center;">' + parseInt(ip.block_count || 0, 10) + '</td>';
                html += '</tr>';
            }
            
            html += '</tbody>';
            html += '</table>';
            
            $content.html(html);
        },
        
        /**
         * Show loading state
         */
        showLoading: function() {
            var $content = $(this.config.containerSelector).find(this.config.contentSelector);
            $content.html('<div style="text-align: center; padding: 40px 20px;"><span class="spinner is-active" style="float: none; margin: 0 auto;"></span></div>');
        },
        
        /**
         * Show error state
         */
        showError: function(message) {
            var $content = $(this.config.containerSelector).find(this.config.contentSelector);
            $content.html('<div style="color: #dc3545; text-align: center; padding: 40px 20px; font-size: 13px;">' + this.escapeHtml(message) + '</div>');
        },
        
        /**
         * Escape HTML to prevent XSS
         */
        escapeHtml: function(text) {
            if (!text) return '';
            
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            
            return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    };
    
    // Auto-initialize when DOM is ready
    $(document).ready(function() {
        VMPFenceTopIPsChart.init();
    });
    
})(jQuery);
