/**
 * VMPFence Firewall JavaScript
 *
 * @package VMPFence
 * @since 2.0.0
 * @since 2.2.0 - Added Custom Pattern Blocking handlers
 */

jQuery(document).ready(function($) {
    // Handle enable firewall button
    $('#vmpfence-enable-firewall-btn').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();
        
        // Disable button and show loading
        $btn.text('ENABLING...').prop('disabled', true);
        
        // Make AJAX request to enable firewall
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_enable_firewall',
                nonce: vmpfence_firewall.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Reload the page to show updated status
                    window.location.reload();
                } else {
                    VMPFenceNotifications.showError('Error enabling firewall: ' + (response.data.message || 'Unknown error'));
                    $btn.text(originalText).prop('disabled', false);
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error enabling firewall. Please try again.');
                $btn.text(originalText).prop('disabled', false);
            }
        });
    });

    // Handle attack filter buttons with AJAX
    $('.attack-filter-btn').on('click', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var filter = $btn.data('filter');
        
        // Update active state
        $('.attack-filter-btn').removeClass('active');
        $btn.addClass('active');
        
        // Show loading state
        $('#firewall-summary-content').css('opacity', '0.5');
        
        // AJAX request to load filtered data
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_load_firewall_summary',
                filter: filter,
                nonce: vmpfence_firewall.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#firewall-summary-content').html(response.data.html);
                    $('#firewall-summary-content').css('opacity', '1');
                } else {
                    $('#firewall-summary-content').css('opacity', '1');
                    VMPFenceNotifications.showError('Failed to load data: ' + (response.data.message || 'Unknown error'));
                }
            },
            error: function() {
                $('#firewall-summary-content').css('opacity', '1');
                VMPFenceNotifications.showError('Failed to load firewall summary. Please try again.');
            }
        });
    });

    // Handle Block Type Tab Switching with Table Visibility and URL State
    $('.vmpfence-block-tabs .vmpfence-tab').on('click', function() {
        var $tab = $(this);
        var tabName = $tab.data('tab');
        
        // Remove active class from all tabs
        $('.vmpfence-block-tabs .vmpfence-tab').removeClass('vmpfence-tab-active');
        
        // Add active to clicked tab
        $tab.addClass('vmpfence-tab-active');
        
        // Hide all tab content
        $('.vmpfence-tab-content').hide();
        
        // Show selected tab content
        $('#tab-' + tabName).show();
        
        // Show/hide tables based on selected tab
        if (tabName === 'ip-address') {
            $('#vmpfence-ip-table-section').show();
            $('#vmpfence-country-table-section').hide();
            $('#vmpfence-custom-patterns-table-section').hide();
            updateURLParameter('view', 'ip');
            // Clear country search when leaving country view
            $('#vmpfence-countries-search').val('').trigger('input');
        } else if (tabName === 'country') {
            $('#vmpfence-ip-table-section').hide();
            $('#vmpfence-country-table-section').show();
            $('#vmpfence-custom-patterns-table-section').hide();
            updateURLParameter('view', 'country');
            // Lazy load countries table if not already loaded
            if (typeof window.vmpfenceCountriesLoaded === 'undefined') {
                window.vmpfenceCountriesLoaded = true;
                // Trigger country table load (handled by country-selector.js)
                if (typeof loadBlockedCountriesTable === 'function') {
                    loadBlockedCountriesTable();
                } else {
                    // If function not available, trigger custom event
                    $(document).trigger('vmpfence:load-countries-table');
                }
            }
        } else if (tabName === 'custom-pattern') {
            // Show custom patterns table
            $('#vmpfence-ip-table-section').hide();
            $('#vmpfence-country-table-section').hide();
            $('#vmpfence-custom-patterns-table-section').show();
            updateURLParameter('view', 'custom-pattern');
            
            // Lazy load patterns table if not already loaded
            if (typeof window.vmpfencePatternsLoaded === 'undefined') {
                window.vmpfencePatternsLoaded = true;
                if (typeof loadCustomPatternsTable === 'function') {
                    loadCustomPatternsTable();
                }
            }
            
            // Clear country search when leaving country view
            $('#vmpfence-countries-search').val('').trigger('input');
        }
    });
    
    // Helper function to update URL parameter without page reload
    function updateURLParameter(param, value) {
        var url = new URL(window.location);
        url.searchParams.set(param, value);
        window.history.replaceState({}, '', url);
    }
    
    // Cancel button - hide current tab
    $('.vmpfence-cancel-tab').on('click', function() {
        $('.vmpfence-tab-content').hide();
        $('.vmpfence-block-tabs .vmpfence-tab').removeClass('vmpfence-tab-active');
    });
    
    // Initialize tab state on page load based on URL parameter or default to IP
    if ($('.vmpfence-block-tabs .vmpfence-tab').length > 0) {
        const urlParams = new URLSearchParams(window.location.search);
        const currentTab = urlParams.get('tab');
        const viewParam = urlParams.get('view');
        const hasPrefillIp = urlParams.has('prefill_ip');
        
        // Only initialize if on blocking tab AND no prefill_ip (prefill_ip handler will trigger tab)
        if (currentTab === 'blocking' && !hasPrefillIp) {
            var activeTab = 'ip-address'; // Default to IP Address
            
            // Check URL view parameter to restore state
            if (viewParam === 'country') {
                activeTab = 'country';
            } else if (viewParam === 'custom-pattern') {
                activeTab = 'custom-pattern';
            } else if (!viewParam) {
                // No view parameter in URL, add it to match initial state (IP tab is default)
                updateURLParameter('view', 'ip');
            }
            
            // Activate the appropriate tab (this will trigger the click handler above)
            // Only trigger if view parameter exists (meaning user wants to restore state)
            if (viewParam) {
                $('.vmpfence-block-tabs .vmpfence-tab[data-tab="' + activeTab + '"]').trigger('click');
            }
            // If no view parameter, IP tab is already active by default (HTML), so don't trigger click
        }
    }

    // ============================================================================
    // Total Attacks Blocked Chart (Chart.js)
    // ============================================================================
    (function() {
        // Check if chart canvas exists on the page (supports both firewall.php and dashboard.php)
        const chartCanvas = document.getElementById('attackChart') || document.getElementById('attacksChart');
        if (!chartCanvas) {
            return; // Exit if chart element doesn't exist on either page
        }
        
        let currentChart = null;
        let currentView = '24h';
        let isLoading = false;
        
        /**
         * Fetch attack timeline data from server
         */
        function fetchAttackData(period) {
            if (isLoading) return;
            
            // Check if ajaxurl and nonce are available
            if (typeof ajaxurl === 'undefined' || typeof vmpfence_firewall === 'undefined') {
                console.error('WordPress AJAX or nonce not available');
                showChartError('Configuration error - please refresh page');
                return;
            }
            
            isLoading = true;
            
            // Show loading state
            $(chartCanvas).parent().css('opacity', '0.5');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_attack_timeline',
                    period: period,
                    nonce: vmpfence_firewall.nonce
                },
                success: function(response) {
                    isLoading = false;
                    $(chartCanvas).parent().css('opacity', '1');
                    
                    if (response.success && response.data) {
                        // Validate data structure before creating chart
                        if (response.data.labels && response.data.values && 
                            Array.isArray(response.data.labels) && Array.isArray(response.data.values)) {
                            createChart(response.data);
                        } else {
                            console.error('Invalid chart data structure:', response.data);
                            showChartError('Invalid data format received');
                        }
                    } else {
                        console.error('Failed to load chart data:', response.data ? response.data.message : 'Unknown error');
                        showChartError(response.data && response.data.message ? response.data.message : 'Failed to load chart data');
                    }
                },
                error: function(xhr, status, error) {
                    isLoading = false;
                    $(chartCanvas).parent().css('opacity', '1');
                    console.error('AJAX error loading chart:', error);
                    showChartError('Network error loading chart data');
                }
            });
        }
        
        /**
         * Show error message on chart
         */
        function showChartError(message) {
            // Destroy existing chart first
            if (currentChart) {
                currentChart.destroy();
                currentChart = null;
            }
            
            // Get canvas context and validate dimensions
            const ctx = chartCanvas.getContext('2d');
            const width = chartCanvas.clientWidth || 400;
            const height = chartCanvas.clientHeight || 300;
            
            // Set canvas size if not already set
            chartCanvas.width = width;
            chartCanvas.height = height;
            
            // Clear and draw error message
            ctx.clearRect(0, 0, width, height);
            ctx.font = '14px Arial';
            ctx.fillStyle = '#999';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(message, width / 2, height / 2);
        }
        
        /**
         * Create/update Chart.js instance with data
         */
        function createChart(data) {
            // Check if Chart.js is loaded
            if (typeof Chart === 'undefined') {
                console.error('Chart.js library not loaded');
                showChartError('Chart library not loaded');
                return;
            }
            
            const ctx = chartCanvas;
            
            if (currentChart) {
                currentChart.destroy();
            }
            
            currentChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'Total Attacks',
                        data: data.values,
                        borderColor: '#5DADE2',
                        backgroundColor: 'rgba(93, 173, 226, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4,
                        pointRadius: 0,
                        pointHoverRadius: 5,
                        pointBackgroundColor: '#5DADE2',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            align: 'end',
                            labels: {
                                usePointStyle: true,
                                boxWidth: 12,
                                boxHeight: 12,
                                padding: 15,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            padding: 12,
                            bodyFont: {
                                size: 13
                            },
                            titleFont: {
                                size: 13,
                                weight: 'bold'
                            },
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    label += new Intl.NumberFormat().format(context.parsed.y);
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: true,
                                color: 'rgba(0, 0, 0, 0.05)',
                                drawBorder: false
                            },
                            ticks: {
                                font: {
                                    size: 11
                                },
                                color: '#666',
                                autoSkip: false,
                                maxRotation: 45,
                                minRotation: 45
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                display: true,
                                color: 'rgba(0, 0, 0, 0.05)',
                                drawBorder: false
                            },
                            ticks: {
                                font: {
                                    size: 11
                                },
                                color: '#666',
                                callback: function(value) {
                                    if (value >= 1000000) {
                                        return (value / 1000000).toFixed(0) + 'M';
                                    } else if (value >= 1000) {
                                        return (value / 1000).toFixed(0) + 'K';
                                    }
                                    return value;
                                }
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    }
                }
            });
            
            // Update timestamp
            updateTimestamp();
        }
        
        /**
         * Update the "Last Updated" timestamp
         */
        function updateTimestamp() {
            const timestampElement = document.getElementById('vmpfence-chart-timestamp');
            if (timestampElement) {
                const now = new Date();
                const hours = now.getHours();
                const minutes = now.getMinutes();
                const ampm = hours >= 12 ? 'PM' : 'AM';
                const displayHours = hours % 12 || 12;
                const displayMinutes = minutes < 10 ? '0' + minutes : minutes;
                
                timestampElement.textContent = 'Last Updated: Just now (' + displayHours + ':' + displayMinutes + ' ' + ampm + ')';
            }
        }
        
        // Button click handlers
        const btn24h = document.getElementById('chart-24h');
        const btn30d = document.getElementById('chart-30d');
        
        if (btn24h && btn30d) {
            btn24h.addEventListener('click', function() {
                if (currentView === '24h' || isLoading) return;
                currentView = '24h';
                this.classList.add('vmpfence-active');
                btn30d.classList.remove('vmpfence-active');
                fetchAttackData('24h');
            });
            
            btn30d.addEventListener('click', function() {
                if (currentView === '30d' || isLoading) return;
                currentView = '30d';
                this.classList.add('vmpfence-active');
                btn24h.classList.remove('vmpfence-active');
                fetchAttackData('30d');
            });
        }
        
        // Initial load - fetch 24h data on page load
        fetchAttackData('24h');
    })();
    
    // =========================================
    // Custom Pattern Blocking Handlers
    // =========================================
    
    // Custom Pattern Form Submission
    jQuery('#vmpfence-custom-pattern-form').on('submit', function(e) {
        e.preventDefault();
        
        const patternType = jQuery('#pattern-type').val();
        const patternValue = jQuery('#pattern-value').val().trim();
        const isRegex = jQuery('#is-regex').is(':checked') ? 1 : 0;
        const reason = jQuery('#pattern-reason').val().trim();
        
        // Validation
        if (!patternType || !patternValue || !reason) {
            VMPFenceNotifications.showError('All fields are required');
            return;
        }
        
        const submitBtn = jQuery(this).find('button[type="submit"]');
        submitBtn.prop('disabled', true).text('ADDING...');
        
        jQuery.ajax({
            url: vmpfencePatternAjax.ajax_url,
            method: 'POST',
            data: {
                action: 'vmpfence_add_custom_pattern',
                nonce: vmpfencePatternAjax.nonce,
                pattern_type: patternType,
                pattern_value: patternValue,
                is_regex: isRegex,
                reason: reason
            },
            success: function(response) {
                if (response.success) {
                    VMPFenceNotifications.showSuccess((response.data.message || 'Pattern added successfully') + '. Reloading page in 2 seconds...');
                    jQuery('#vmpfence-custom-pattern-form')[0].reset();
                    
                    // Reload page after 2 seconds to show updated list
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    VMPFenceNotifications.showError(response.data.message || 'Failed to add pattern');
                }
            },
            error: function() {
                VMPFenceNotifications.showError('AJAX request failed');
            },
            complete: function() {
                submitBtn.prop('disabled', false).text('ADD PATTERN');
            }
        });
    });
    
    // Dynamic placeholder update based on pattern type
    jQuery('#pattern-type').on('change', function() {
        const type = jQuery(this).val();
        const patternInput = jQuery('#pattern-value');
        const placeholders = {
            'hostname': '*.amazonaws.com or *.linode.com',
            'user_agent': '*badbot* or *crawler*',
            'referrer': '*spam-site.com*',
            'ip_range': '192.168.1.0/24 or 10.0.0.0/8'
        };
        patternInput.attr('placeholder', placeholders[type] || 'Enter pattern');
    });
    
    // Load Custom Patterns Table
    function loadCustomPatternsTable() {
        jQuery.ajax({
            url: vmpfencePatternAjax.ajax_url,
            method: 'POST',
            data: {
                action: 'vmpfence_get_custom_patterns',
                nonce: vmpfencePatternAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    renderCustomPatternsTable(response.data.patterns);
                } else {
                    jQuery('#vmpfence-patterns-tbody').html('<tr><td colspan="7" style="text-align: center; padding: 40px; color: #dc3545;">Failed to load patterns</td></tr>');
                }
            },
            error: function() {
                jQuery('#vmpfence-patterns-tbody').html('<tr><td colspan="7" style="text-align: center; padding: 40px; color: #dc3545;">Error loading patterns</td></tr>');
            }
        });
    }
    
    // Render patterns table
    function renderCustomPatternsTable(patterns) {
        const tbody = jQuery('#vmpfence-patterns-tbody');
        tbody.empty();
        
        // Update count
        jQuery('#vmpfence-patterns-count').text('(' + (patterns ? patterns.length : 0) + ')');
        
        if (!patterns || patterns.length === 0) {
            tbody.append('<tr><td colspan="7" class="vmpfence-empty-state" style="text-align: center; padding: 60px 20px;"><p style="color: rgba(25,25,112,0.6); font-size: 14px;">No custom patterns configured. Use the form above to add a pattern.</p></td></tr>');
            return;
        }
        
        // Count group_id occurrences to determine which are truly grouped
        const groupCounts = {};
        patterns.forEach(function(pattern) {
            if (pattern.group_id) {
                groupCounts[pattern.group_id] = (groupCounts[pattern.group_id] || 0) + 1;
            }
        });
        
        patterns.forEach(function(pattern) {
            // Status badge matching IP table style
            const statusBadge = pattern.is_active == 1 
                ? '<span style="background: #28A745; color: #FFFFFF; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600;">ACTIVE</span>'
                : '<span style="background: #dc3545; color: #FFFFFF; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600;">DISABLED</span>';
            
            // Type badge without fixed width - let it be natural
            const typeBadge = '<span style="background: #F8F9FA; color: #191970; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600; display: inline-block;">' + 
                escapeHtml(pattern.pattern_type.toUpperCase().replace(/_/g, ' ')) + '</span>';
            
            // Format created_at date
            const createdAt = pattern.created_at ? new Date(pattern.created_at * 1000).toLocaleDateString('en-US', {
                month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
            }) : 'N/A';
            
            // Group indicator badge (only show if group_id exists AND has more than 1 pattern)
            const isPartOfGroup = pattern.group_id && groupCounts[pattern.group_id] > 1;
            const groupBadge = isPartOfGroup ? 
                '<br><span style="background: #667eea; color: #FFFFFF; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600; margin-top: 4px; display: inline-block;" title="Part of grouped patterns">GROUP</span>' : '';
            
            const row = '<tr data-pattern-id="' + pattern.id + '" data-pattern-type="' + pattern.pattern_type + '" data-is-active="' + pattern.is_active + '" data-group-id="' + (pattern.group_id || '') + '">' +
                '<td style="text-align: center;">' + typeBadge + groupBadge + '</td>' +
                '<td style="word-break: break-all;"><code style="font-weight: 600; color: #191970; font-size: 13px;">' + escapeHtml(pattern.pattern_value) + '</code>' +
                (pattern.is_regex == 1 ? ' <span style="background: #e3f2fd; color: #1976d2; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600; margin-left: 5px;">REGEX</span>' : '') +
                '</td>' +
                '<td style="color: #50575e;">' + escapeHtml(pattern.reason || '-') + '</td>' +
                '<td style="color: #646970; font-size: 13px;">' + createdAt + '</td>' +
                '<td style="text-align: center; color: #191970; font-weight: 600;">' + (pattern.match_count || 0) + '</td>' +
                '<td style="text-align: center;">' + statusBadge + '</td>' +
                '<td style="text-align: center;">' +
                    '<button class="toggle-pattern" data-id="' + pattern.id + '" title="' + (pattern.is_active == 1 ? 'Disable' : 'Enable') + ' pattern" ' +
                    'style="background: ' + (pattern.is_active == 1 ? '#dc3545' : '#28A745') + '; color: white; border: none; padding: 6px 12px; margin-right: 5px; border-radius: 6px; cursor: pointer; font-size: 11px; font-weight: 600; transition: opacity 0.2s;">' +
                        (pattern.is_active == 1 ? '✕' : '✓') +
                    '</button>' +
                    '<button class="delete-pattern" data-id="' + pattern.id + '" title="' + (isPartOfGroup ? 'Delete all grouped patterns' : 'Delete pattern') + '" ' +
                    'style="background: #6c757d; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 11px; font-weight: 600; transition: opacity 0.2s;">🗑</button>' +
                '</td>' +
                '</tr>';
            tbody.append(row);
        });
        
        // Apply current filters
        applyPatternFilters();
    }
    
    // Delete pattern handler
    jQuery(document).on('click', '.delete-pattern', function() {
        const btn = jQuery(this);
        const patternId = btn.data('id');
        const $row = btn.closest('tr');
        const groupId = $row.data('group-id');
        
        // Determine confirmation message based on group status
        let confirmTitle = 'Delete Pattern';
        let confirmMessage = 'Are you sure you want to delete this pattern?';
        
        if (groupId) {
            // Count patterns in this group
            const groupCount = jQuery('tr[data-group-id="' + groupId + '"]').length;
            if (groupCount > 1) {
                confirmTitle = 'Delete Grouped Patterns';
                confirmMessage = 'This pattern is part of a group with ' + groupCount + ' patterns. All grouped patterns will be deleted. Continue?';
            }
        }
        
        VMPFenceNotifications.showConfirmModal({
            title: confirmTitle,
            message: confirmMessage,
            confirmText: 'Delete',
            cancelText: 'Cancel',
            type: 'danger',
            showIcon: true
        }).then(function(confirmed) {
            if (!confirmed) {
                return;
            }
            
            btn.prop('disabled', true).text('...');
        
            jQuery.ajax({
                url: vmpfencePatternAjax.ajax_url,
                method: 'POST',
                data: {
                    action: 'vmpfence_delete_custom_pattern',
                    nonce: vmpfencePatternAjax.nonce,
                    pattern_id: patternId
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceNotifications.showSuccess(response.data.message || 'Pattern deleted successfully');
                        loadCustomPatternsTable();
                    } else {
                        VMPFenceNotifications.showError(response.data.message || 'Failed to delete pattern');
                        btn.prop('disabled', false).text('🗑');
                    }
                },
                error: function() {
                    VMPFenceNotifications.showError('Network error. Please try again.');
                    btn.prop('disabled', false).text('🗑');
                }
            });
        });
    });
    
    // Toggle pattern handler
    jQuery(document).on('click', '.toggle-pattern', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const btn = jQuery(this);
        
        // Prevent double-click
        if (btn.prop('disabled')) {
            return false;
        }
        
        const patternId = btn.data('id');
        const $row = btn.closest('tr');
        const currentActive = $row.data('is-active');
        const newActive = currentActive == 1 ? 0 : 1;
        
        btn.prop('disabled', true).text('...');
        
        jQuery.ajax({
            url: vmpfencePatternAjax.ajax_url,
            method: 'POST',
            data: {
                action: 'vmpfence_toggle_custom_pattern',
                nonce: vmpfencePatternAjax.nonce,
                pattern_id: patternId
            },
            success: function(response) {
                if (response.success) {
                    VMPFenceNotifications.showSuccess(response.data.message);
                    
                    // Optimistic UI update - update only this row instead of reloading entire table
                    $row.data('is-active', newActive);
                    
                    // Update status badge
                    const statusBadge = newActive == 1 
                        ? '<span style="background: #28A745; color: #FFFFFF; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600;">ACTIVE</span>'
                        : '<span style="background: #dc3545; color: #FFFFFF; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600;">DISABLED</span>';
                    $row.find('td').eq(5).html(statusBadge);
                    
                    // Update button state
                    btn.css('background', newActive == 1 ? '#dc3545' : '#28A745')
                       .attr('title', newActive == 1 ? 'Disable pattern' : 'Enable pattern')
                       .text(newActive == 1 ? '✕' : '✓')
                       .prop('disabled', false);
                    
                    // Reapply filters to handle active-only filter
                    applyPatternFilters();
                } else {
                    VMPFenceNotifications.showError(response.data.message || 'Failed to toggle pattern');
                    btn.prop('disabled', false);
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Network error. Please try again.');
                btn.prop('disabled', false);
            }
        });
    });
    
    // Helper function
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // Pattern filtering functions
    function applyPatternFilters() {
        const searchTerm = jQuery('#vmpfence-patterns-search').val().toLowerCase();
        const activeOnly = jQuery('#vmpfence-filter-active-patterns').is(':checked');
        const selectedType = jQuery('.vmpfence-pattern-type-filter.active').data('type');
        
        let visibleCount = 0;
        
        jQuery('#vmpfence-patterns-tbody tr').each(function() {
            const $row = jQuery(this);
            
            // Skip empty state row
            if ($row.find('.vmpfence-empty-state').length > 0) {
                return;
            }
            
            const patternType = $row.data('pattern-type');
            const isActive = $row.data('is-active');
            const rowText = $row.text().toLowerCase();
            
            let show = true;
            
            // Filter by search term
            if (searchTerm && rowText.indexOf(searchTerm) === -1) {
                show = false;
            }
            
            // Filter by active status
            if (activeOnly && isActive != 1) {
                show = false;
            }
            
            // Filter by pattern type
            if (selectedType && patternType !== selectedType) {
                show = false;
            }
            
            if (show) {
                $row.show();
                visibleCount++;
            } else {
                $row.hide();
            }
        });
        
        // Update count
        const totalCount = jQuery('#vmpfence-patterns-tbody tr').not(':has(.vmpfence-empty-state)').length;
        jQuery('#vmpfence-patterns-count').text('(Showing ' + visibleCount + ' of ' + totalCount + ')');
    }
    
    // Pattern search handler
    jQuery(document).on('input', '#vmpfence-patterns-search', function() {
        applyPatternFilters();
    });
    
    // Pattern active filter handler
    jQuery(document).on('change', '#vmpfence-filter-active-patterns', function() {
        applyPatternFilters();
    });
    
    // Pattern type filter handler
    jQuery(document).on('click', '.vmpfence-pattern-type-filter', function() {
        jQuery('.vmpfence-pattern-type-filter').removeClass('active');
        jQuery(this).addClass('active');
        applyPatternFilters();
    });
});
