/**
 * Top Countries Chart Module
 * 
 * Handles the "Top Countries by Number of Attacks" chart display
 * 
 * @package VMPFence
 * @since 2.2.0
 */

(function($) {
    'use strict';
    
    // Module state
    let currentPeriod = '7d';
    let isLoading = false;
    
    /**
     * Get flag emoji for country code
     */
    function getCountryFlag(countryCode) {
        if (!countryCode || countryCode.length !== 2) {
            return '🌍';
        }
        
        const codePoints = countryCode
            .toUpperCase()
            .split('')
            .map(char => 127397 + char.charCodeAt());
        
        return String.fromCodePoint(...codePoints);
    }
    
    /**
     * Format number with commas
     */
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    
    /**
     * Escape HTML to prevent XSS
     */
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    /**
     * Render the countries table
     */
    function renderCountriesTable(countries) {
        const container = $('.vmpfence-top-countries-content');
        
        if (!countries || countries.length === 0) {
            container.html(
                '<div style="text-align: center; padding: 40px 20px; color: #999; font-style: italic;">' +
                'No blocks have been recorded' +
                '</div>'
            );
            return;
        }
        
        let html = '<table style="width: 100%; border-collapse: collapse;">';
        
        countries.forEach(function(country, index) {
            const flag = getCountryFlag(country.country_code);
            const countryName = escapeHtml(country.country_name || country.country_code);
            const attackCount = parseInt(country.attack_count) || 0;
            
            html += '<tr style="border-bottom: 1px solid #f0f0f0;">';
            html += '<td style="padding: 12px 15px; width: 40px; text-align: center; font-size: 24px;">' + flag + '</td>';
            html += '<td style="padding: 12px 15px; font-weight: 500; color: #333;">' + countryName + '</td>';
            html += '<td style="padding: 12px 15px; text-align: right; font-weight: 600; color: #d32f2f;">' + formatNumber(attackCount) + ' attacks</td>';
            html += '</tr>';
        });
        
        html += '</table>';
        
        container.html(html);
    }
    
    /**
     * Load top countries data
     */
    function loadTopCountries(period) {
        if (isLoading) {
            return;
        }
        
        isLoading = true;
        period = period || currentPeriod;
        
        const container = $('.vmpfence-top-countries-content');
        container.html(
            '<div style="text-align: center; padding: 40px 20px; color: #999;">' +
            '<span class="spinner is-active" style="float: none; margin: 0 auto;"></span>' +
            '</div>'
        );
        
        $.ajax({
            url: vmpfenceTopCountries.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_top_countries',
                nonce: vmpfenceTopCountries.nonce,
                period: period
            },
            success: function(response) {
                if (response.success && response.data) {
                    renderCountriesTable(response.data.countries);
                    currentPeriod = period;
                } else {
                    container.html(
                        '<div style="text-align: center; padding: 40px 20px; color: #d32f2f;">' +
                        'Error loading country data' +
                        '</div>'
                    );
                }
            },
            error: function() {
                container.html(
                    '<div style="text-align: center; padding: 40px 20px; color: #d32f2f;">' +
                    'Failed to load country data' +
                    '</div>'
                );
            },
            complete: function() {
                isLoading = false;
            }
        });
    }
    
    /**
     * Initialize on document ready
     */
    $(document).ready(function() {
        // Check if localized script data exists
        if (typeof vmpfenceTopCountries === 'undefined') {
            console.error('VMPFence Top Countries: Script not properly localized');
            return;
        }
        
        // Check if the top countries card exists
        if ($('.vmpfence-top-countries-card').length === 0) {
            return;
        }
        
        // Load initial data
        loadTopCountries('7d');
        
        // Handle filter tab clicks (if they exist)
        $('.vmpfence-top-countries-card').on('click', '.vmpfence-filter-tab', function() {
            const $tab = $(this);
            const period = $tab.data('period');
            
            if (!period || period === currentPeriod) {
                return;
            }
            
            // Update active state
            $tab.siblings().removeClass('active');
            $tab.addClass('active');
            
            // Load data for new period
            loadTopCountries(period);
        });
        
        // Auto-refresh every 60 seconds
        setInterval(function() {
            loadTopCountries(currentPeriod);
        }, 60000);
    });
    
})(jQuery);
