/**
 * Country Selector - Interactive Country Dropdown with Search
 * 
 * @package VMPFence
 * @since 2.2.0
 */

(function($) {
    'use strict';

    let selectedCountries = [];
    let allCountries = [];

    /**
     * Initialize country selector
     */
    function initCountrySelector() {
        // Load countries from JSON
        var countriesUrl = vmpfence_ajax.plugin_url + 'admin/data/countries.json';
        
        $.getJSON(countriesUrl, function(data) {
            allCountries = data;
            renderCountryOptions(allCountries);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error('Failed to load countries data');
            console.error('URL:', countriesUrl);
            console.error('Status:', textStatus);
            console.error('Error:', errorThrown);
            
            // Show error in dropdown
            $('#vmpfence-country-options').html(
                '<div style="padding: 20px; text-align: center; color: #dc3232;">' +
                'Failed to load countries. Please refresh the page.' +
                '</div>'
            );
        });

        // Search functionality
        $('#vmpfence-country-search').on('input', function() {
            const searchTerm = $(this).val().toLowerCase();
            const filtered = allCountries.filter(country => 
                country.name.toLowerCase().includes(searchTerm) ||
                country.code.toLowerCase().includes(searchTerm)
            );
            renderCountryOptions(filtered);
        });

        // Country selection
        $(document).on('click', '.vmpfence-country-option', function() {
            const code = $(this).data('code');
            const name = $(this).data('name');
            const flag = $(this).data('flag');
            
            addCountryTag(code, name, flag);
        });

        // Form submission
        $('#vmpfence-block-countries-form').on('submit', handleFormSubmit);

        // Load blocked countries table ONLY if country section is visible
        // This prevents unnecessary AJAX call when IP tab is active (default)
        if ($('.vmpfence-blocked-countries-section').is(':visible')) {
            loadBlockedCountriesTable();
        } else {
            // Listen for custom event to load table when country tab is activated
            $(document).on('vmpfence:load-countries-table', function() {
                loadBlockedCountriesTable();
            });
        }
    }

    /**
     * Render country options in dropdown
     */
    function renderCountryOptions(countries) {
        const $list = $('#vmpfence-country-options');
        $list.empty();

        if (countries.length === 0) {
            $list.html('<div class="vmpfence-no-results">No countries found</div>');
            return;
        }

        countries.forEach(country => {
            // Skip already selected countries
            if (selectedCountries.includes(country.code)) {
                return;
            }

            const $option = $('<div>')
                .addClass('vmpfence-country-option')
                .attr('data-code', country.code)
                .attr('data-name', country.name)
                .attr('data-flag', country.flag)
                .html(`
                    <span class="vmpfence-country-flag">${country.flag}</span>
                    <span class="vmpfence-country-name">${country.name}</span>
                    <span class="vmpfence-country-code">${country.code}</span>
                `);

            $list.append($option);
        });
    }

    /**
     * Add country tag
     */
    function addCountryTag(code, name, flag) {
        if (selectedCountries.includes(code)) {
            return; // Already selected
        }

        selectedCountries.push(code);

        const $tag = $('<div>')
            .addClass('vmpfence-country-tag')
            .attr('data-code', code)
            .html(`
                <span class="vmpfence-tag-flag">${flag}</span>
                <span class="vmpfence-tag-name">${name}</span>
                <span class="vmpfence-tag-code">${code}</span>
                <button type="button" class="vmpfence-tag-remove" aria-label="Remove ${name}">×</button>
            `);

        $('#vmpfence-selected-countries').append($tag);

        // Update form hidden input
        updateHiddenInput();

        // Refresh dropdown to hide selected country
        const searchTerm = $('#vmpfence-country-search').val().toLowerCase();
        const filtered = allCountries.filter(country => 
            (country.name.toLowerCase().includes(searchTerm) ||
             country.code.toLowerCase().includes(searchTerm)) &&
            !selectedCountries.includes(country.code)
        );
        renderCountryOptions(filtered);

        // Clear search
        $('#vmpfence-country-search').val('').focus();
    }

    /**
     * Remove country tag
     */
    $(document).on('click', '.vmpfence-tag-remove', function() {
        const code = $(this).closest('.vmpfence-country-tag').data('code');
        removeCountryTag(code);
    });

    function removeCountryTag(code) {
        selectedCountries = selectedCountries.filter(c => c !== code);
        $(`.vmpfence-country-tag[data-code="${code}"]`).remove();
        updateHiddenInput();
        
        // Refresh dropdown
        const searchTerm = $('#vmpfence-country-search').val().toLowerCase();
        const filtered = allCountries.filter(country => 
            (country.name.toLowerCase().includes(searchTerm) ||
             country.code.toLowerCase().includes(searchTerm)) &&
            !selectedCountries.includes(country.code)
        );
        renderCountryOptions(filtered);
    }

    /**
     * Update hidden form input
     */
    function updateHiddenInput() {
        $('#vmpfence-countries-input').val(selectedCountries.join(','));
    }

    /**
     * Handle form submission
     */
    function handleFormSubmit(e) {
        e.preventDefault();

        // Ensure toast notification system is initialized
        if (typeof VMPFenceNotifications !== 'undefined' && typeof VMPFenceNotifications.init === 'function') {
            VMPFenceNotifications.init();
        }

        if (selectedCountries.length === 0) {
            VMPFenceNotifications.showError('Please select at least one country to block');
            return;
        }

        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        const formData = {
            action: 'vmpfence_block_countries',
            nonce: vmpfence_ajax.nonce,
            countries: selectedCountries,
            block_login: $('#vmpfence-block-login').is(':checked') ? 1 : 0,
            block_site: $('#vmpfence-block-site').is(':checked') ? 1 : 0,
            reason: $('#vmpfence-block-reason').val() || ''
        };

        // Disable button
        $btn.prop('disabled', true).text('Blocking...');

        $.post(vmpfence_ajax.ajax_url, formData)
            .done(function(response) {
                if (response.success) {
                    VMPFenceNotifications.showSuccess(response.data.message || 'Countries blocked successfully!', 4000);
                    
                    // Clear form
                    selectedCountries = [];
                    $('#vmpfence-selected-countries').empty();
                    $('#vmpfence-block-reason').val('');
                    updateHiddenInput();
                    renderCountryOptions(allCountries);
                    
                    // Reload table
                    loadBlockedCountriesTable();
                } else {
                    VMPFenceNotifications.showError(response.data.message || 'Failed to block countries');
                }
            })
            .fail(function() {
                VMPFenceNotifications.showError('Network error. Please try again.');
            })
            .always(function() {
                $btn.prop('disabled', false).text('Block Selected Countries');
            });
    }

    /**
     * Load and display blocked countries table
     */
    function loadBlockedCountriesTable() {
        // Ensure toast notification system is initialized
        if (typeof VMPFenceNotifications !== 'undefined' && typeof VMPFenceNotifications.init === 'function') {
            VMPFenceNotifications.init();
        }
        
        const $section = $('.vmpfence-blocked-countries-section');
        const $body = $('#vmpfence-blocked-countries-body');

        // Show loading
        $body.html('<tr><td colspan="8" style="text-align:center;padding:40px;"><div class="vmpfence-spinner"></div><div>Loading...</div></td></tr>');

        $.post(vmpfence_ajax.ajax_url, {
            action: 'vmpfence_get_blocked_countries',
            nonce: vmpfence_ajax.nonce
        })
        .done(function(response) {
            if (response.success && response.data.countries) {
                if (response.data.countries.length === 0) {
                    $('#vmpfence-countries-count').text('(Showing 0 of 0)');
                    $body.html('<tr><td colspan="8" class="vmpfence-countries-empty"><div style="margin-bottom:16px;font-size:16px;font-weight:600;color:#191970;">No countries blocked</div><div class="vmpfence-empty-hint">Block countries to protect your site from specific regions</div></td></tr>');
                } else {
                    renderBlockedCountriesTable(response.data.countries);
                }
            } else {
                $('#vmpfence-countries-count').text('(Error)');
                $body.html('<tr><td colspan="8" style="text-align:center;color:#dc3232;">Failed to load blocked countries</td></tr>');
            }
        })
        .fail(function() {
            $('#vmpfence-countries-count').text('(Error)');
            $body.html('<tr><td colspan="8" style="text-align:center;color:#dc3232;">Network error</td></tr>');
        });
    }

    /**
     * Render blocked countries in table
     */
    function renderBlockedCountriesTable(countries) {
        const $tbody = $('#vmpfence-blocked-countries-body');
        $tbody.empty();

        // Update count badge
        const total = countries.length;
        $('#vmpfence-countries-count').text(`(Showing ${total} of ${total})`);

        countries.forEach(country => {
            const blockingBadges = [];
            if (country.block_login == 1) {
                blockingBadges.push('<span class="vmpfence-badge vmpfence-badge-login">Login</span>');
            }
            if (country.block_site == 1) {
                blockingBadges.push('<span class="vmpfence-badge vmpfence-badge-site">Entire Site</span>');
            }

            // Format expires date
            let expiresText = '<span class="vmpfence-expires-permanent">Permanent</span>';
            if (country.blocked_until && country.blocked_until > 0) {
                expiresText = formatBlockedDate(country.blocked_until);
            }

            // Format reason (truncate if too long)
            let reasonText = country.reason || 'No reason provided';
            if (reasonText.length > 100) {
                reasonText = reasonText.substring(0, 97) + '...';
            }

            // Format source
            let sourceText = country.source || 'manual';
            let sourceClass = `vmpfence-source-badge vmpfence-source-${sourceText.toLowerCase()}`;

            const $row = $('<tr>').html(`
                <td class="vmpfence-country-flag">${country.flag}</td>
                <td>
                    <span class="vmpfence-country-name">${country.country_name}</span>
                    <span class="vmpfence-country-code">${country.country_code}</span>
                </td>
                <td><div class="vmpfence-blocking-badges">${blockingBadges.join('')}</div></td>
                <td title="${country.reason || ''}">${reasonText}</td>
                <td><div class="vmpfence-blocked-date">${formatBlockedDate(country.blocked_at)}</div></td>
                <td><div class="vmpfence-expires-date">${expiresText}</div></td>
                <td><span class="${sourceClass}">${sourceText}</span></td>
                <td>
                    <button type="button" 
                            class="vmpfence-btn-unblock-country" 
                            data-code="${country.country_code}"
                            data-name="${country.country_name}">
                        Unblock
                    </button>
                </td>
            `);

            $tbody.append($row);
        });

        attachUnblockHandlers();
        initializeCountriesSearch();
        initializeCountriesFilters();
    }

    /**
     * Format blocked date for display
     */
    function formatBlockedDate(timestamp) {
        const date = new Date(timestamp * 1000);
        const now = new Date();
        const diffMs = now - date;
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffDays === 0) {
            return 'Today';
        } else if (diffDays === 1) {
            return 'Yesterday';
        } else if (diffDays < 7) {
            return `${diffDays} days ago`;
        } else {
            return date.toLocaleDateString();
        }
    }

    /**
     * Attach unblock handlers
     */
    function attachUnblockHandlers() {
        $('.vmpfence-btn-unblock-country').off('click').on('click', function() {
            const $btn = $(this);
            const code = $btn.data('code');
            const name = $btn.data('name');

            // Sanitize name for XSS prevention
            const safeName = $('<div>').text(name).html();
            const safeCode = $('<div>').text(code).html();

            VMPFenceNotifications.showConfirmModal({
                title: 'Unblock Country',
                message: 'Are you sure you want to unblock ' + safeName + ' (' + safeCode + ')?',
                confirmText: 'Yes, Unblock',
                cancelText: 'Cancel'
            }).then(function(confirmed) {
                if (!confirmed) return;
                unblockCountry(code, $btn);
            });
        });
    }

    /**
     * Unblock a country via AJAX
     */
    function unblockCountry(countryCode, $btn) {
        $btn.prop('disabled', true).text('Unblocking...');

        $.post(vmpfence_ajax.ajax_url, {
            action: 'vmpfence_unblock_country',
            nonce: vmpfence_ajax.nonce,
            country_code: countryCode
        })
        .done(function(response) {
            if (response.success) {
                VMPFenceNotifications.showSuccess(response.data.message || 'Country unblocked successfully!', 4000);
                
                // Remove row with fade effect
                $btn.closest('tr').fadeOut(300, function() {
                    $(this).remove();
                    
                    // Update count
                    const remaining = $('#vmpfence-blocked-countries-body tr:visible').length;
                    $('#vmpfence-countries-count').text(`(Showing ${remaining} of ${remaining})`);
                    
                    // Check if table is empty
                    if ($('#vmpfence-blocked-countries-body tr').length === 0) {
                        loadBlockedCountriesTable();
                    }
                });
            } else {
                VMPFenceNotifications.showError(response.data.message || 'Failed to unblock country');
                $btn.prop('disabled', false).text('Unblock');
            }
        })
        .fail(function() {
            VMPFenceNotifications.showError('Network error while unblocking country');
            $btn.prop('disabled', false).text('Unblock');
        });
    }

    /**
     * Initialize countries search functionality
     */
    function initializeCountriesSearch() {
        $('#vmpfence-countries-search').off('input').on('input', function() {
            const searchTerm = $(this).val().toLowerCase();
            
            $('#vmpfence-blocked-countries-body tr').each(function() {
                const $row = $(this);
                const country = $row.find('.vmpfence-country-name').text().toLowerCase();
                const code = $row.find('.vmpfence-country-code').text().toLowerCase();
                const reason = $row.find('td').eq(3).text().toLowerCase();
                
                const matches = country.includes(searchTerm) || 
                               code.includes(searchTerm) || 
                               reason.includes(searchTerm);
                
                $row.toggle(matches);
            });
            
            // Update count
            const visible = $('#vmpfence-blocked-countries-body tr:visible').length;
            const total = $('#vmpfence-blocked-countries-body tr').length;
            $('#vmpfence-countries-count').text(`(Showing ${visible} of ${total})`);
        });
    }

    /**
     * Initialize countries filter functionality
     */
    function initializeCountriesFilters() {
        $('.vmpfence-filter-btn').off('click').on('click', function() {
            const $btn = $(this);
            const filter = $btn.data('filter');
            
            // Update active state
            $('.vmpfence-filter-btn').removeClass('vmpfence-filter-active');
            $btn.addClass('vmpfence-filter-active');
            
            // Apply filter
            $('#vmpfence-blocked-countries-body tr').each(function() {
                const $row = $(this);
                const hasLogin = $row.find('.vmpfence-badge-login').length > 0;
                const hasSite = $row.find('.vmpfence-badge-site').length > 0;
                
                let show = true;
                if (filter === 'login') {
                    show = hasLogin;
                } else if (filter === 'site') {
                    show = hasSite;
                }
                
                $row.toggle(show);
            });
            
            // Update count
            const visible = $('#vmpfence-blocked-countries-body tr:visible').length;
            const total = $('#vmpfence-blocked-countries-body tr').length;
            $('#vmpfence-countries-count').text(`(Showing ${visible} of ${total})`);
        });
    }

    // Initialize on document ready
    $(document).ready(function() {
        // Initialize toast notification system
        if (typeof VMPFenceNotifications !== 'undefined') {
            VMPFenceNotifications.init();
        }
        
        // Only initialize if country selector exists
        if ($('#vmpfence-country-selector').length > 0) {
            initCountrySelector();
        }
    });

})(jQuery);
