/**
 * VMPFence Scan JavaScript
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.1.0 Removed redundant reputation percentage calculation and Debug button fixes
 * @since 2.1.1 Scanner optimized
 * @since 2.1.2 Critical fixes for scan status persistence, auto-refresh, and debug log handling
 * @since 2.2.4 Sync button cross-disable during scan
 * @since 2.2.6 Scan Results curation and UI update, and scan result description updated for server
 */

jQuery(document).ready(function($) {
    
    let scanProgressInterval;
    let scanStartTime;
    let isLoadingResults = false; // Flag to prevent duplicate result loads
    let scanJustCompleted = false; // Flag to track fresh scan completion vs page load with completed scan
    let idleScanHeartbeat = null; // Idle heartbeat interval for detecting SIEM-initiated scans
    
    // Initialize scan status indicators on page load
    initializeScanStatusIndicators();
    
    // Check if scan is currently running and resume polling
    detectAndResumeOngoingScan();
    
    // Load existing issues on page load
    initializeIssuesToDisplayIfNeeded();
    
    // Note: Reputation percentage is now calculated in scan.php directly
    // No need to load it via AJAX since the circle is already rendered with correct values
    // loadReputationPercentage(); // REMOVED - redundant calculation
    
    /**
     * Initialize scan status indicators
     * Only loads previous scan status if NO scan is currently running
     */
    function initializeScanStatusIndicators() {
        
        // First check if scan is running - if so, skip initialization
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_progress',
                nonce: vmpfence_ajax.nonce
            },
            success: function(progressResponse) {
                // If scan is running or starting, don't load old status
                if (progressResponse.success && progressResponse.data && 
                    (progressResponse.data.status === 'running' || progressResponse.data.status === 'starting')) {
                    // console.log('VMPFence: Scan in progress, skipping status initialization');
                    // Indicators will be set to loading by detectAndResumeOngoingScan()
                    return;
                }
                
                // No scan running, load previous scan status
                $.ajax({
                    url: vmpfence_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_get_scan_status',
                        nonce: vmpfence_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data && response.data.has_data) {
                            updateScanStatusIndicators(response.data.status_data);
                        } else {
                            // No previous scan data, set all to grey (initial state)
                            setAllStatusIndicatorsToGrey();
                        }
                    },
                    error: function(xhr, status, error) {
                        // On error, set all to grey as fallback
                        setAllStatusIndicatorsToGrey();
                    }
                });
            },
            error: function() {
                // If can't check progress, proceed with loading old status
                $.ajax({
                    url: vmpfence_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_get_scan_status',
                        nonce: vmpfence_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data && response.data.has_data) {
                            updateScanStatusIndicators(response.data.status_data);
                        } else {
                            setAllStatusIndicatorsToGrey();
                        }
                    },
                    error: function(xhr, status, error) {
                        setAllStatusIndicatorsToGrey();
                    }
                });
            }
        });
    }
    
    /**
     * Detect if scan is currently running and resume progress polling
     * Called on page load to handle page refresh during scan
     */
    function detectAndResumeOngoingScan() {
        // CRITICAL FIX: Disable button immediately on page load while checking status
        const $button = $('.vmpfence-btn-start-scan');
        $button.prop('disabled', true).text('CHECKING SCAN STATUS...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_progress',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    const status = response.data.status;
                    
                    // Check if scan is actively running
                    if (status === 'scanning' || status === 'starting') {
                        // console.log('VMPFence: Detected ongoing scan on page load, resuming progress polling');
                        
                        // Set UI to scanning state
                        $button.prop('disabled', true).text('SCANNING...');
                        
                        // Set all indicators to loading state
                        setAllStatusIndicatorsToLoading();
                        
                        // Resume progress polling
                        startProgressPolling();
                    } else if (status === 'completed' || status === 'completed_with_timeout') {
                        // console.log('VMPFence: Detected completed scan on page load, loading results');
                        
                        // Re-enable button immediately - scan is already done
                        $button.prop('disabled', false).text('START NEW SCAN');
                        
                        // Mark as already completed (don't trigger auto-reload)
                        scanJustCompleted = false;
                        
                        // Load the completed scan results
                        loadAsyncScanResults();
                        
                        // Start idle heartbeat to detect SIEM-initiated scans
                        startIdleScanHeartbeat();
                    } else if (status === 'error') {
                        // console.log('VMPFence: Detected scan error on page load');
                        // Clear any loading indicators
                        clearAllLoadingIndicators();
                        // Clear the error progress state
                        clearCompletedProgress();
                        // Re-enable button since no scan is running
                        $button.prop('disabled', false).text('START NEW SCAN');
                        // Start idle heartbeat to detect SIEM-initiated scans
                        startIdleScanHeartbeat();
                    } else {
                        // Status is 'idle' or other - no scan running, re-enable button
                        $button.prop('disabled', false).text('START NEW SCAN');
                        // Start idle heartbeat to detect SIEM-initiated scans
                        startIdleScanHeartbeat();
                    }
                }
            },
            error: function(xhr, status, error) {
                console.warn('VMPFence: Could not check for ongoing scan:', error);
                // Re-enable button on error (assume no scan running)
                $button.prop('disabled', false).text('START NEW SCAN');
                // Start idle heartbeat even on error
                startIdleScanHeartbeat();
            }
        });
    }
    
    /**
     * Set all status indicators to grey (initial/fresh scan state)
     */
    /**
     * Idle Scan Heartbeat — Detect SIEM-initiated scans
     * 
     * Polls vmpfence_get_scan_progress every 15s while the scan page is idle.
     * If a scan is detected (status: scanning, starting), the heartbeat stops
     * and switches to fast 2s progress polling (startProgressPolling).
     * This enables bidirectional sync: SIEM portal starts a scan → server
     * loopback-pings wp-cron.php → plugin picks up command → scan starts →
     * this heartbeat detects it and updates the WP-Admin scan UI in real time.
     */
    function startIdleScanHeartbeat() {
        if (idleScanHeartbeat) return; // already running
        if (scanProgressInterval) return; // fast polling active, not idle

        idleScanHeartbeat = setInterval(function() {
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_scan_progress',
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var status = response.data.status;
                        if (status === 'scanning' || status === 'starting') {
                            // Scan detected! Stop idle heartbeat and switch to active UI.
                            stopIdleScanHeartbeat();

                            var $button = $('.vmpfence-btn-start-scan');
                            $button.prop('disabled', true).text('SCANNING...');
                            setAllStatusIndicatorsToLoading();
                            startProgressPolling();
                        }
                    }
                },
                error: function() { /* skip this tick on error */ }
            });
        }, 15000); // Check every 15s while idle
    }

    function stopIdleScanHeartbeat() {
        if (idleScanHeartbeat) {
            clearInterval(idleScanHeartbeat);
            idleScanHeartbeat = null;
        }
    }

    /**
     * Set all status indicators to loading state for scan start
     */
    function setAllStatusIndicatorsToLoading() {
        $('.vmpfence-status-item').each(function(index) {
            const $item = $(this);
            const scanType = $item.data('scan-type');
            
            // Note: All reputation checks are now implemented and active
            // Reset text color to grey for new scan
            const $statusText = $item.find('.vmpfence-status-text p:first-child');
            $statusText.css('color', '#666');
            
            const $svg = $item.find('.vmpfence-status-icon svg');
            if ($svg.length) {
                // Set to circular dotted loading animation
                $svg.html(`
                    <g>
                        <circle cx="15" cy="8" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0s"/>
                        </circle>
                        <circle cx="20.5" cy="11" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.15s"/>
                        </circle>
                        <circle cx="22" cy="15" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.3s"/>
                        </circle>
                        <circle cx="20.5" cy="19" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.45s"/>
                        </circle>
                        <circle cx="15" cy="22" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.6s"/>
                        </circle>
                        <circle cx="9.5" cy="19" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.75s"/>
                        </circle>
                        <circle cx="8" cy="15" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="0.9s"/>
                        </circle>
                        <circle cx="9.5" cy="11" r="1.5" fill="#2196F3">
                            <animate attributeName="opacity" values="1;0.2;1" dur="1.2s" repeatCount="indefinite" begin="1.05s"/>
                        </circle>
                    </g>
                `);
            }
        });
    }
    
    function setAllStatusIndicatorsToGrey() {
        $('.vmpfence-status-item').each(function(index) {
            const $item = $(this);
            const scanType = $item.data('scan-type');
            updateStatusIndicator($item, 'grey');
        });
    }
    
    /**
     * Update scan status indicators based on scan results
     */
    function updateScanStatusIndicators(scanStatus) {
        
        $('.vmpfence-status-item').each(function() {
            const $item = $(this);
            const scanType = $item.data('scan-type');
            
            // Skip undefined scan types (shouldn't happen anymore)
            if (!scanType) {
                // console.log('VMPFence: Skipping item without scan-type attribute');
                return;
            }
            
            // Note: All reputation checks are now implemented and active
            
            if (scanStatus[scanType] !== undefined) {
                const issuesCount = scanStatus[scanType];
                const status = issuesCount > 0 ? 'warning' : 'success';
                updateStatusIndicator($item, status);
            } else {
                // If no data for this scan type, keep it grey
                updateStatusIndicator($item, 'grey');
            }
        });
    }
    
    /**
     * Update a single status indicator
     */
    function updateStatusIndicator($item, status) {
        // Remove all status classes
        $item.removeClass('vmpfence-success vmpfence-warning vmpfence-grey');
        
        // Add the new status class
        $item.addClass('vmpfence-' + status);
        
        // Update SVG based on status
        const $iconContainer = $item.find('.vmpfence-status-icon');
        let newSvg;
        
        switch (status) {
            case 'success':
                // Green checkmark for no issues
                newSvg = `
                    <svg width="30" height="30" viewBox="0 0 30 30">
                        <circle cx="15" cy="15" r="12" fill="#4CAF50"/>
                        <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                    </svg>
                `;
                break;
            case 'warning':
                // Orange warning triangle for issues found
                newSvg = `
                    <svg width="30" height="30" viewBox="0 0 30 30">
                        <path d="M15 3L27 24H3L15 3Z" fill="#FFA726"/>
                        <path d="M15 10V16" stroke="white" stroke-width="2"/>
                        <circle cx="15" cy="19" r="1" fill="white"/>
                    </svg>
                `;
                break;
            case 'grey':
            default:
                // Grey checkmark for not scanned yet
                newSvg = `
                    <svg width="30" height="30" viewBox="0 0 30 30">
                        <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                        <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                    </svg>
                `;
                break;
        }
        
        // Replace the SVG
        $iconContainer.html(newSvg);
    }
    
    /**
     * Initialize issues display if there are existing results
     */
    function initializeIssuesToDisplayIfNeeded() {
        // Check if we have results count displayed (indicating previous scan results exist)
        const resultsFoundCount = $('.vmpfence-stat-count').eq(4).text();
        if (resultsFoundCount && parseInt(resultsFoundCount) > 0) {
            loadScanIssues();
        }
    }
    
    /**
     * Debug Log Button Handler
     */
    $('.vmpfence-btn-debug-logs').on('click', function(e) {
        e.preventDefault();
        showDebugLogs();
    });
    
    /**
     * Debug Modal Close Handlers
     */
    $('#vmpfence-close-debug, #vmpfence-close-debug-2').on('click', function() {
        $('#vmpfence-debug-modal').hide();
    });
    
    /**
     * Debug Modal Refresh Handler
     */
    $('#vmpfence-refresh-debug').on('click', function() {
        loadDebugLogs();
    });

    /**
     * Inline Debug Log Show Handler
     */
    $('#vmpfence-show-log-btn').on('click', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const isVisible = $('#vmpfence-inline-debug-log').is(':visible');
        
        if (isVisible) {
            hideInlineDebugLog();
        } else {
            showInlineDebugLog();
        }
    });

    /**
     * Inline Debug Log Hide Handler
     */
    $('#vmpfence-hide-log-btn').on('click', function(e) {
        e.preventDefault();
        hideInlineDebugLog();
    });
    
    /**
     * Close modal when clicking outside
     */
    $('#vmpfence-debug-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });
    
    /**
     * Email Activity Log Handler
     */
    $('#vmpfence-email-log-btn').on('click', function(e) {
        e.preventDefault();
        showEmailDebugLogsModal();
    });
    
    /**
     * Start New Scan Button Handler
     */
    $('.vmpfence-btn-start-scan').on('click', function(e) {
        e.preventDefault();
        
        const $button = $(this);
        const originalText = $button.text();
        
        // Check if scan is already running
        if (scanProgressInterval) {
            console.warn('VMPFence: Scan already in progress, ignoring new scan request');
            return;
        }
        
        // Disable button and show loading state
        $button.prop('disabled', true).text('SCANNING...');
        
        // Cross-disable: disable sync button while scan is running
        var $syncBtn = $('#vmpfence-sync-signatures');
        if ($syncBtn.length && !$syncBtn.prop('disabled')) {
            $syncBtn.prop('disabled', true).data('disabled-by-scan', true);
        }
        
        // Reset all status indicators to loading state for fresh scan
        setAllStatusIndicatorsToLoading();
        
        // Record scan start time
        scanStartTime = new Date();
        
        // Start progress polling (no modal overlay)
        startProgressPolling();
        
        // Start the scan (async mode)
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_start_scan',
                nonce: vmpfence_ajax.nonce
            },
            beforeSend: function() {
                // console.log('VMPFence: Starting scan...');
            },
            success: function(response) {
                if (response.success && response.data.async) {
                    // Async scan started successfully - keep button disabled and continue polling
                    // console.log('VMPFence: Scan running in background, polling for progress...');
                    // Button remains disabled with "SCANNING..." text until scan completes
                } else if (response.success) {
                    // Unexpected sync response - just stop polling
                    console.warn('VMPFence: Received unexpected sync response');
                    stopProgressPolling();
                    clearAllLoadingIndicators();
                    $button.prop('disabled', false).text(originalText);
                } else {
                    console.error('VMPFence: Failed to start scan:', response.data.message);
                    stopProgressPolling();
                    clearAllLoadingIndicators();
                    $button.prop('disabled', false).text(originalText);
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Scan start failed:', error, xhr.responseText);
                stopProgressPolling();
                clearAllLoadingIndicators();
                $button.prop('disabled', false).text(originalText);
            }
        });
    });
    
    /**
     * Show scan progress
     */
    function showScanProgress() {
        // Create progress overlay if it doesn't exist
        if ($('.vmpfence-scan-overlay').length === 0) {
            const progressHtml = `
                <div class="vmpfence-scan-overlay">
                    <div class="vmpfence-scan-progress-modal">
                        <h3>Scanning Files...</h3>
                        <div class="vmpfence-progress-bar">
                            <div class="vmpfence-progress-fill"></div>
                        </div>
                        <div class="vmpfence-progress-text">
                            <span class="vmpfence-progress-files">0</span> files scanned
                        </div>
                        <div class="vmpfence-progress-status">Initializing scan...</div>
                    </div>
                </div>
            `;
            $('body').append(progressHtml);
        }
        
        $('.vmpfence-scan-overlay').show();
    }
    
    /**
     * Hide scan progress
     */
    function hideScanProgress() {
        $('.vmpfence-scan-overlay').hide();
    }
    
    /**
     * Update scan results display
     */
    function updateScanResults(data) {
        // Safety check - ensure we have data
        if (!data) {
            console.error('VMPFence: No scan data provided');
            return;
        }
        
        const comprehensive_stats = data.comprehensive_statistics || {};
        const totalIssues = data.total_issues || 0;
        const activeCount = data.active_count || 0;
        const ignoredCount = data.ignored_count || 0;
        
        // Update timestamp with completion time
        if (comprehensive_stats.completed_time) {
            const completionDate = new Date(comprehensive_stats.completed_time);
            const timestamp = '[' + completionDate.toLocaleString('en-US', {
                month: 'short',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: true
            }).toUpperCase() + ']';
            $('.vmpfence-scan-timestamp').text(timestamp);
        } else {
            // Fallback to current time if no completed_time
            const now = new Date();
            const timestamp = '[' + now.toLocaleString('en-US', {
                month: 'short',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: true
            }).toUpperCase() + ']';
            $('.vmpfence-scan-timestamp').text(timestamp);
            console.warn('VMPFence: No completed_time in comprehensive_statistics, using current time');
        }
        
        // Build comprehensive completion message using statistics
        // Build message parts from comprehensive statistics
        let messageParts = [];
        if (comprehensive_stats.files_scanned > 0) messageParts.push(`${comprehensive_stats.files_scanned} files`);
        if (comprehensive_stats.plugins_scanned > 0) messageParts.push(`${comprehensive_stats.plugins_scanned} plugins`);
        if (comprehensive_stats.themes_scanned > 0) messageParts.push(`${comprehensive_stats.themes_scanned} themes`);
        if (comprehensive_stats.posts_scanned > 0) messageParts.push(`${comprehensive_stats.posts_scanned} posts`);
        if (comprehensive_stats.comments_scanned > 0) messageParts.push(`${comprehensive_stats.comments_scanned} comments`);
        if (comprehensive_stats.urls_scanned > 0) messageParts.push(`${comprehensive_stats.urls_scanned} URLs`);
        
        // Format duration
        let durationText = 'unknown time';
        if (comprehensive_stats.scan_duration > 0) {
            durationText = formatScanDuration(comprehensive_stats.scan_duration);
        }
        
        // Build final message with HTML line break
        let completionMessage;
        if (messageParts.length > 0) {
            completionMessage = `Comprehensive Scan Complete.<br>Found ${totalIssues} total issues (${activeCount} active, ${ignoredCount} ignored). Scanned ${messageParts.join(', ')} in ${durationText}.`;
        } else {
            // Fallback if no comprehensive stats available
            completionMessage = `Comprehensive Scan Complete.<br>Found ${totalIssues} total issues (${activeCount} active, ${ignoredCount} ignored).`;
            console.warn('VMPFence: No scan statistics available in comprehensive_statistics');
        }
        $('.vmpfence-scan-message').html(completionMessage);
        
        // CRITICAL FIX: Clear loading indicators immediately when results arrive
        // This prevents UI from staying stuck in loading state
        clearAllLoadingIndicators();
        
        // Update scan status indicators by fetching fresh data from database (same as page refresh)
        // console.log('VMPFence: Fetching fresh scan status from database...');
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_status',
                nonce: vmpfence_ajax.nonce
            },
            success: function(statusResponse) {
                // console.log('VMPFence: Got scan status response:', statusResponse);
                if (statusResponse.success && statusResponse.data.status_data) {
                    // console.log('VMPFence: Updating status indicators with data:', statusResponse.data.status_data);
                    updateScanStatusIndicators(statusResponse.data.status_data);
                    // Store scan status for next page load
                    storeScanStatus(statusResponse.data.status_data);
                    
                    // Check repairability after scan completion
                    setTimeout(function() {
                        checkRepairability();
                    }, 500); // Small delay to ensure status indicators are rendered
                } else {
                    console.warn('VMPFence: Invalid status response - scan completed but status data unavailable');
                    console.warn('VMPFence: Keeping current UI state, user can refresh to see status');
                    // CRITICAL FIX: Clear loading indicators even if status data unavailable
                    clearAllLoadingIndicators();
                    setAllStatusIndicatorsToGrey();
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to fetch status data:', error);
                console.error('VMPFence: Scan completed but status indicators could not be updated');
                // CRITICAL FIX: Ensure loading indicators are cleared even on error
                clearAllLoadingIndicators();
                // Set all to grey as fallback since we don't have status data
                setAllStatusIndicatorsToGrey();
            }
        });
        
        // Update statistics based on comprehensive statistics
        $('.vmpfence-stats-row .vmpfence-stat-item').each(function(index) {
            const $count = $(this).find('.vmpfence-stat-count');
            const comprehensive_stats = data.comprehensive_statistics || {};
            
            switch (index) {
                case 0: // Posts, Comments, & Files
                    // Use comprehensive statistics files_scanned + posts + comments
                    const totalFiles = (comprehensive_stats.files_scanned || 0) + 
                                     (comprehensive_stats.posts_scanned || 0) + 
                                     (comprehensive_stats.comments_scanned || 0);
                    $count.text(totalFiles);
                    break;
                case 1: // Themes & Plugins
                    // Use comprehensive statistics plugins + themes
                    const pluginThemeCount = (comprehensive_stats.plugins_scanned || 0) + 
                                           (comprehensive_stats.themes_scanned || 0);
                    $count.text(pluginThemeCount);
                    break;
                case 2: // Users Checked
                    // Use comprehensive statistics users_scanned
                    const usersChecked = comprehensive_stats.users_scanned || 0;
                    $count.text(usersChecked);
                    break;
                case 3: // URLs Checked
                    // Use comprehensive statistics urls_scanned
                    const urlsChecked = comprehensive_stats.urls_scanned || 0;
                    $count.text(urlsChecked);
                    break;
                case 4: // Results Found
                    $count.text(data.total_issues || 0);
                    break;
            }
        });
        
        // Update results tabs
        $('.vmpfence-tab .vmpfence-tab-count').first().text(`(${data.total_issues || 0})`);
        
        // Re-enable scan button now that scan is complete
        $('.vmpfence-btn-start-scan').prop('disabled', false).text('START NEW SCAN');
        
        // Load and display actual scan issues
        if (data.total_issues > 0) {
            loadScanIssues();
        } else {
            $('.vmpfence-no-issues').show();
        }
        
        // CRITICAL FIX: Auto-refresh page after scan completion to ensure fresh data
        // Only reload if this was a fresh scan completion (not page load with completed scan)
        // console.log('VMPFence: scanJustCompleted flag is:', scanJustCompleted);
        if (scanJustCompleted) {
            // console.log('VMPFence: Scan complete - auto-refreshing page in 1.5 seconds...');
            // console.log('VMPFence: Setting reload timeout NOW');
            setTimeout(function() {
                // console.log('VMPFence: RELOADING PAGE NOW!');
                location.reload();
            }, 1500);
            scanJustCompleted = false; // Reset flag
        } else {
            // console.log('VMPFence: Scan results loaded (no auto-refresh for page load with completed scan)');
        }
    }
    
    /**
     * Store scan status for persistence across page loads
     */
    function storeScanStatus(statusData) {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_store_scan_status',
                nonce: vmpfence_ajax.nonce,
                status_data: JSON.stringify(statusData)
            },
            success: function(response) {
                // console.log('VMPFence: Scan status stored successfully');
            },
            error: function() {
                // console.log('VMPFence: Failed to store scan status');
            }
        });
    }
    
    /**
     * Load scan issues from database
     */
    function loadScanIssues() {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_results',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data.issues) {
                    // Store issues data globally for tab switching
                    window.vmpfenceIssuesData = response.data;
                    
                    // Check if any active issues have any form of 'ignored' status
                    if (response.data.issues) {
                        const ignoredInActive = response.data.issues.filter(issue => 
                            issue.status === 'ignored' || 
                            issue.issue_status === 'ignored' ||
                            issue.is_ignored === 1 ||
                            issue.is_ignored === '1' ||
                            issue.ignored === 1 ||
                            issue.ignored === '1'
                        );
                        if (ignoredInActive.length > 0) {
                            // FILTER OUT IGNORED ISSUES FROM ACTIVE LIST
                            response.data.issues = response.data.issues.filter(issue => 
                                issue.status !== 'ignored' && 
                                issue.issue_status !== 'ignored' &&
                                issue.is_ignored !== 1 &&
                                issue.is_ignored !== '1' &&
                                issue.ignored !== 1 &&
                                issue.ignored !== '1'
                            );
                        }
                    }
                    
                    // Update tab counts
                    updateTabCounts(response.data.active_count, response.data.ignored_count);
                    
                    // Update scan message with fresh counts
                    updateScanMessage(response.data.active_count, response.data.ignored_count);
                    
                    // Check which tab is currently active and show appropriate issues
                    const $activeTab = $('.vmpfence-tab.vmpfence-tab-active');
                    const isIgnoredTab = $activeTab.text().includes('Ignored Results');
                    
                    if (isIgnoredTab) {
                        // Show ignored issues if on ignored tab
                        if (response.data.ignored_issues && response.data.ignored_issues.length > 0) {
                            showScanIssues(response.data.ignored_issues, true);
                        } else {
                            $('.vmpfence-scan-issues-list').hide();
                            $('.vmpfence-no-issues').show();
                        }
                    } else {
                        // Show active issues by default
                        showScanIssues(response.data.issues);
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to load issues:', error);
            }
        });
    }
    
    /**
     * Update tab counts
     */
    function updateTabCounts(activeCount, ignoredCount) {
        // Update tab counts (left side)
        $('.vmpfence-tab').each(function() {
            const $tab = $(this);
            const $count = $tab.find('.vmpfence-tab-count');
            
            if ($tab.text().includes('Results Found')) {
                $count.text(`(${activeCount})`);
            } else if ($tab.text().includes('Ignored Results')) {
                $count.text(`(${ignoredCount})`);
            }
        });
        
        // Update statistics (right side) - find the "Results Found" stat
        $('.vmpfence-stats-row .vmpfence-stat-item').each(function(index) {
            const $count = $(this).find('.vmpfence-stat-count');
            const $label = $(this).find('.vmpfence-stat-label');
            
            // Check if this is the "Results Found" statistic (usually the last one)
            if ($label.text().includes('Results Found') || index === 4) {
                $count.text(activeCount);
            }
        });
    }

    /**
     * Update scan message dynamically based on current counts and scan statistics
     */
    function updateScanMessage(activeCount, ignoredCount, scanData = null) {
        const totalIssues = activeCount + ignoredCount;
        
        // Check for comprehensive statistics first
        if (scanData && scanData.comprehensive_statistics) {
            const stats = scanData.comprehensive_statistics;
            
            // Build comprehensive message parts
            let messageParts = [];
            if (stats.files_scanned > 0) messageParts.push(`${stats.files_scanned} files`);
            if (stats.plugins_scanned > 0) messageParts.push(`${stats.plugins_scanned} plugins`);
            if (stats.themes_scanned > 0) messageParts.push(`${stats.themes_scanned} themes`);
            if (stats.posts_scanned > 0) messageParts.push(`${stats.posts_scanned} posts`);
            if (stats.comments_scanned > 0) messageParts.push(`${stats.comments_scanned} comments`);
            if (stats.urls_scanned > 0) messageParts.push(`${stats.urls_scanned} URLs`);
            
            // Create duration text
            let duration = 'unknown time';
            if (stats.scan_duration > 0) {
                duration = formatScanDuration(stats.scan_duration);
            }
            
            // Create final message
            let scanType = stats.scan_type || 'Scan';
            let statusText = totalIssues > 0 
                ? `Complete.<br>Found ${totalIssues} total issues (${activeCount} active, ${ignoredCount} ignored). Scanned ` 
                : 'Complete.<br>Scanned ';
                
            let message = scanType + ' ' + statusText + messageParts.join(', ') + ` in ${duration}.`;
            $('.vmpfence-scan-message').html(message);
            return;
        }
        
        // If we have scan data but no comprehensive statistics, try to extract from scan_data
        if (scanData && scanData.scan_data) {
            const data = scanData.scan_data;
            const stats = data.stats || data;
            
            // Extract scan statistics
            let filesScanned = data.total_files || stats.total_files_checked || stats.core_files_checked || 0;
            let pluginsScanned = stats.plugins_checked || 0;
            let themesScanned = stats.themes_checked || 0;
            let postsScanned = stats.posts_checked || stats.content_items_checked || 0;
            let commentsScanned = stats.comments_checked || 0;
            let urlsScanned = stats.urls_checked || 0;
            let usersScanned = stats.users_checked || 0;
            
            // Calculate scan duration
            let duration = '';
            if (data.scan_duration) {
                duration = formatScanDuration(data.scan_duration);
            } else if (data.completed_time && data.started_time) {
                const startTime = new Date(data.started_time);
                const endTime = new Date(data.completed_time);
                const durationSeconds = Math.floor((endTime - startTime) / 1000);
                duration = formatScanDuration(durationSeconds);
            } else {
                duration = 'unknown time';
            }
            
            // Build comprehensive message parts
            let messageParts = [];
            if (filesScanned > 0) messageParts.push(`${filesScanned} files`);
            if (pluginsScanned > 0) messageParts.push(`${pluginsScanned} plugins`);
            if (themesScanned > 0) messageParts.push(`${themesScanned} themes`);
            if (postsScanned > 0) messageParts.push(`${postsScanned} posts`);
            if (commentsScanned > 0) messageParts.push(`${commentsScanned} comments`);
            if (usersScanned > 0) messageParts.push(`${usersScanned} users`);
            if (urlsScanned > 0) messageParts.push(`${urlsScanned} URLs`);
            
            // Create final message
            let scanType = data.scan_type || 'Scan';
            let statusText = totalIssues > 0 
                ? `Complete.<br>Found ${totalIssues} total issues (${activeCount} active, ${ignoredCount} ignored). Scanned ` 
                : 'Complete.<br>Scanned ';
                
            let message = scanType + ' ' + statusText + messageParts.join(', ') + ` in ${duration}.`;
            $('.vmpfence-scan-message').html(message);
        } else {
            // Fallback to basic message
            const message = totalIssues > 0 
                ? `Last scan completed.<br>Found ${totalIssues} total issues (${activeCount} active, ${ignoredCount} ignored).`
                : 'Last scan completed successfully.<br>No issues found.';
            $('.vmpfence-scan-message').html(message);
        }
    }

    /**
     * Format scan duration into human-readable format
     */
    function formatScanDuration(seconds) {
        if (seconds < 60) {
            return `${seconds} seconds`;
        } else if (seconds < 3600) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return remainingSeconds > 0 ? `${minutes} minutes ${remainingSeconds} seconds` : `${minutes} minutes`;
        } else {
            const hours = Math.floor(seconds / 3600);
            const remainingMinutes = Math.floor((seconds % 3600) / 60);
            const remainingSeconds = seconds % 60;
            let result = `${hours} hours`;
            if (remainingMinutes > 0) result += ` ${remainingMinutes} minutes`;
            if (remainingSeconds > 0) result += ` ${remainingSeconds} seconds`;
            return result;
        }
    }

    /**
     * Show scan issues
     */
    function showScanIssues(issues, isIgnored = false) {
        const $noIssues = $('.vmpfence-no-issues');
        $noIssues.hide();
        
        // Create issues display
        if ($('.vmpfence-scan-issues-list').length === 0) {
            const issuesHtml = `
                <div class="vmpfence-scan-issues-list">
                    <h4>Issues Found:</h4>
                    <div class="vmpfence-issues-container"></div>
                </div>
            `;
            $noIssues.after(issuesHtml);
        }
        
        // Update title based on tab
        $('.vmpfence-scan-issues-list h4').text(isIgnored ? 'Ignored Issues:' : 'Issues Found:');
        $('.vmpfence-scan-issues-list').show();
        
        const $container = $('.vmpfence-issues-container');
        $container.empty();
        
        // Process issues from database format
        if (issues && issues.length > 0) {
            issues.forEach(function(issue) {
                const issueType = issue.issue_type || 'unknown';
                const issueTypeDetail = issue.type || 'Unknown type'; // Use actual type column from database
                const description = issue.description || 'No description available';
                const severity = issue.severity || 'medium';
                
                // Initialize display description (can be overridden in switch cases)
                var displayDescription = description;
                
                let iconClass = '⚠️';
                let issueClass = 'vmpfence-issue-unknown';
                let issueTitle = 'Unknown Issue';
                let actionButtons = '';
                let detailButtons = '';
                
                // Customize based on issue type
                switch (issueTypeDetail) {
                    case 'modified':
                        iconClass = '⚠️';
                        issueClass = 'vmpfence-issue-modified';
                        
                        // Enhanced description with file details
                        const filePath = issue.file_path || issue.location || 'Unknown file';
                        const fileName = filePath.split('/').pop() || filePath; // Get just the filename
                        issueTitle = `Modified Core File: ${fileName}`;
                        const fileDetails = issue.details || '';
                        var enhancedDescription = `File: ${filePath}\n${fileDetails}\n\nWordPress core file has been modified and differs from the official repository version`;
                        
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons =  isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-diff">View Differences</button>
                            <button class="vmpfence-btn-repair-file">Repair File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        
                        // Set display description for this specific case
                        displayDescription = enhancedDescription;
                        break;
                    case 'unknown':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-unknown';
                        issueTitle = 'Suspicious File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_update':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M13.11 4.36L9.87 7.6 8 5.73l3.24-3.24c.35-.34 1.05-.2 1.56.32.52.51.66 1.21.31 1.55zm-8 1.77l.91-1.12 9.01 9.01-1.19.84c-.71.71-2.63 1.16-3.82 1.16H6.14L4.9 17.26c-.59.59-1.54.59-2.12 0-.59-.58-.59-1.53 0-2.12l1.24-1.24v-3.88c0-1.13.4-3.19 1.09-3.89zm7.26 3.97l3.24-3.24c.34-.35 1.04-.21 1.55.31.52.51.66 1.21.31 1.55l-3.24 3.25z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-update';
                        issueTitle = 'Plugin Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update Now</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'theme_update':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M14.48 11.06L7.41 3.99l1.5-1.5c.5-.56 2.3-.47 3.51.32 1.21.8 1.43 1.28 2.91 2.1 1.18.64 2.45 1.26 4.45.85zm-.71.71L6.7 4.7 4.93 6.47c-.39.39-.39 1.02 0 1.41l1.06 1.06c.39.39.39 1.03 0 1.42-.6.6-1.43 1.11-2.21 1.69-.35.26-.7.53-1.01.84C1.43 14.23.4 16.08 1.4 17.07c.99 1 2.84-.03 4.18-1.36.31-.31.58-.66.85-1.02.57-.78 1.08-1.61 1.69-2.21.39-.39 1.02-.39 1.41 0l1.06 1.06c.39.39 1.02.39 1.41 0z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-update';
                        issueTitle = 'Theme Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update Now</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'skipped_path':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M18 16V4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h13c.55 0 1-.45 1-1zM8 11h1c.55 0 1 .45 1 1s-.45 1-1 1H8v1.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V13H6c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V11zm5-2h-1c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V7h1c.55 0 1 .45 1 1s-.45 1-1 1h-1v5.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V9z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-info';
                        issueTitle = 'Path Skipped';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-configure">Configure Settings</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'core_vulnerability':
                        iconClass = '🛡️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'WordPress Core Vulnerability';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update WordPress</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'core_vulnerability_range':
                        iconClass = '🛡️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'WordPress Core Security Risk';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update WordPress</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_vulnerability':
                        iconClass = '⚠️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Plugin Vulnerability Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update Plugin</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_plugin':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-critical';
                        
                        // Try to parse detailed information from JSON description
                        let detailedInfo = null;
                        let pluginName = 'Unknown Plugin';
                        let pluginVersion = 'Unknown Version';
                        let suspiciousKeyword = 'unknown pattern';
                        let details = '';
                        let recommendation = '';
                        
                        try {
                            detailedInfo = JSON.parse(issue.description);
                            if (detailedInfo && detailedInfo.plugin_name) {
                                pluginName = detailedInfo.plugin_name;
                                pluginVersion = detailedInfo.plugin_version || 'Unknown Version';
                                suspiciousKeyword = detailedInfo.suspicious_keyword || 'unknown pattern';
                                details = detailedInfo.details || '';
                                recommendation = detailedInfo.recommendation || '';
                            }
                        } catch (e) {
                            // If JSON parsing fails, use fallback values
                            pluginName = issue.plugin_name || 'Unknown Plugin';
                            pluginVersion = issue.plugin_version || 'Unknown Version';
                            suspiciousKeyword = issue.suspicious_keyword || 'unknown pattern';
                            details = issue.details || issue.description || 'This plugin may be from an untrusted source or contain malicious code.';
                            recommendation = issue.recommendation || 'Remove this plugin immediately and install from official WordPress repository.';
                        }
                        
                        const pluginFile = issue.location || issue.file_path || 'Unknown file';
                        
                        issueTitle = `Suspicious Plugin Detected: ${pluginName}`;
                        var enhancedDescription = `Plugin: ${pluginName} (v${pluginVersion})
Location: ${pluginFile}
Security Risk: Plugin contains suspicious keyword "${suspiciousKeyword}"
Status: ${issue.is_active ? 'Active (High Risk)' : 'Inactive'}

${details}

Recommendation: ${recommendation}`;
                        
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        
                        // Set display description for this specific case
                        displayDescription = enhancedDescription;
                        break;
                    case 'suspicious_theme':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Suspicious Theme Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons =  isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Remove Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'core_update_available':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'WordPress Core Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update WordPress</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_update_available':
                        iconClass = '🔄';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Plugin Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update Plugin</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'theme_update_available':
                        iconClass = '🔄';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Theme Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'malware_detected':
                        iconClass = '🦠';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = issue.title || 'Malware Detected';
                        // Override description to include file path
                        displayDescription = `<strong>File:</strong> ${issue.file_path || 'Unknown file'}<br><br>${description}`;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-code">View Malicious Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'malware':
                        iconClass = '🦠';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Malware Pattern Found';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-code">View Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'adult_content':
                        iconClass = '🔞';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Adult Content Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'violence':
                        iconClass = '⚔️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Violent Content Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'hate_speech':
                        iconClass = '🚫';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Hate Speech Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'spam_scam':
                        iconClass = '💰';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Spam/Scam Content Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'phishing':
                        iconClass = '🎣';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Phishing Content Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_url':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Suspicious URL Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'negative_sentiment':
                        iconClass = '😠';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Negative Sentiment Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'behavioral_pattern':
                        iconClass = '📊';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Behavior Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'behavioral_pattern':
                        iconClass = '📊';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Behavior Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'malicious_links':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Malicious Links Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_punctuation':
                        iconClass = '❗';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Excessive Punctuation Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'illegal_activities':
                        iconClass = '⚖️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Illegal Activities Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'php_functions':
                        iconClass = '⚙️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'PHP Functions Security Issue';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-configure">Configure Settings</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'server_config':
                        iconClass = '🔧';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Server Configuration Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-configure">Configure Server</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'server_permissions':
                        iconClass = '🔒';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Server Permissions Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-permissions">Fix Permissions</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'security_headers':
                        iconClass = '🛡️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Security Headers Missing';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-add-headers">Add Headers</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'ssl_configuration':
                        iconClass = '🔐';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'SSL Configuration Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-ssl">Fix SSL</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'directory_listing':
                        iconClass = '📂';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Directory Listing Enabled';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-disable-listing">Disable Listing</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'php_version':
                        iconClass = '🐘';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Outdated PHP Version';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-contact-host">Contact Host</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'wordpress_core':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'WordPress Core Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update">Update WordPress</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'file_permissions':
                        iconClass = '🔒';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Insecure File Permissions';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-permissions">Fix Permissions</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'database_prefix':
                        iconClass = '🗃️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Default Database Prefix';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-configure">Change Prefix</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'database_version':
                        iconClass = '🗄️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Old Database Version';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-contact-host">Contact Host</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'ssl_https':
                        iconClass = '🔐';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'SSL/HTTPS Not Enabled';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-enable-ssl">Enable SSL</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'wordpress_urls':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'WordPress URLs Not HTTPS';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-urls">Update URLs</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'memory_limit':
                        iconClass = '💾';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Low Memory Limit';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-increase-memory">Increase Memory</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'execution_time':
                        iconClass = '⏱️';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Low Execution Time Limit';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-increase-time">Increase Time Limit</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'upload_limit':
                        iconClass = '📤';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Low Upload File Size Limit';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-increase-upload">Increase Upload Limit</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'server_version':
                        iconClass = '🖥️';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Server Version Exposed';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-hide-version">Hide Version</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'debug_mode':
                        iconClass = '🐛';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Debug Mode Enabled';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-disable-debug">Disable Debug</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'ip_detection':
                        iconClass = '🌐';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'IP Detection Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-configure">Configure IP Detection</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'waf_status':
                        iconClass = '🛡️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'No Web Application Firewall';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'vmpfence_protection':
                        iconClass = '🛡️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'VMPFence Protection Disabled';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-enable-protection">Enable Protection</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'disk_space':
                        iconClass = '💽';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Low Disk Space';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'scan_exclusions':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M18 16V4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h13c.55 0 1-.45 1-1zM8 11h1c.55 0 1 .45 1 1s-.45 1-1 1H8v1.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V13H6c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V11zm5-2h-1c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V7h1c.55 0 1 .45 1 1s-.45 1-1 1h-1v5.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V9z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-low';
                        
                        // Parse exclusion data from message field (contains JSON)
                        let exclusionData = {};
                        try {
                            // Try to find JSON data in the message field
                            const jsonMatch = issue.message ? issue.message.match(/\{.*\}/) : null;
                            if (jsonMatch) {
                                exclusionData = JSON.parse(jsonMatch[0]);
                            }
                        } catch (e) {
                            // console.error('Error parsing exclusion data:', e);
                        }
                        
                        const skippedPaths = exclusionData.skipped_paths || [];
                        const pathCount = skippedPaths.length;
                        
                        // Create title similar to
                        issueTitle = pathCount === 1 
                            ? '1 path was skipped for the malware scan due to scan settings'
                            : `${pathCount} paths were skipped for the malware scan due to scan settings`;
                        
                        // Create detailed description similar to
                        let pathList = '';
                        if (skippedPaths.length > 0) {
                            if (skippedPaths.length === 1) {
                                pathList = skippedPaths[0];
                            } else if (skippedPaths.length === 2) {
                                pathList = skippedPaths.join(' and ');
                            } else {
                                const lastPath = skippedPaths.pop();
                                pathList = skippedPaths.join(', ') + ', and ' + lastPath;
                            }
                        }
                        
                        const pathText = pathCount === 1 ? 'path' : 'paths';
                        const explanation = pathCount === 1
                            ? `The option "Scan files outside your WordPress installation" is disabled, so 1 path is not scanned. Ignore this issue to keep skipping it, or enable the option to include it in future scans.`
                            : `The option "Scan files outside your WordPress installation" is disabled, so ${pathCount} paths are not scanned. Ignore this issue to keep skipping them, or enable the option to include them in future scans.`;
                        
                        var enhancedDescription = `${explanation}\n\nThe ${pathText} skipped ${pathCount === 1 ? 'is' : 'are'}: ${pathList}`;
                        
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-scan-settings">Go To Option</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        
                        // Set display description
                        displayDescription = enhancedDescription;
                        break;
                    case 'public_files':
                        iconClass = '<svg viewBox="0 0 20 20" width="40" height="40" fill="#888"><g><path d="M18 16V4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h13c.55 0 1-.45 1-1zM8 11h1c.55 0 1 .45 1 1s-.45 1-1 1H8v1.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V13H6c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V11zm5-2h-1c-.55 0-1-.45-1-1s.45-1 1-1h1V5.5c0-.28.22-.5.5-.5s.5.22.5.5V7h1c.55 0 1 .45 1 1s-.45 1-1 1h-1v5.5c0 .28-.22.5-.5.5s-.5-.22-.5-.5V9z"></path></g></svg>';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Publicly Accessible Sensitive File';
                        displayDescription = description;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'scanner_error':
                        iconClass = '❌';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Scanner Check Failed';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-contact-support">Contact Support</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'new_admin_user':
                        iconClass = '👤';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'New Admin User Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-investigate">Investigate User</button>
                            <button class="vmpfence-btn-remove-user">Remove User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_admin_username':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Admin Username';
                        
                        // Clean up description by removing redundant prefixes and duplicates
                        let cleanDescription = description;
                        
                        // Remove "Suspicious Admin Username:" prefix if present
                        if (cleanDescription.startsWith('Suspicious Admin Username:')) {
                            cleanDescription = cleanDescription.replace('Suspicious Admin Username:', '').trim();
                        }
                        
                        // Remove redundant "An admin user with a suspicious username admin was found. Details:" part
                        if (cleanDescription.includes('. Details:')) {
                            const parts = cleanDescription.split('. Details:');
                            if (parts.length > 1) {
                                cleanDescription = parts[1].trim(); // Use only the part after "Details:"
                            }
                        }
                        
                        displayDescription = cleanDescription;
                        
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_option_url':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Suspicious URL in WordPress Option';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-url">Remove URL</button>
                            <button class="vmpfence-btn-edit-option">Edit Option</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    // User Security Scanner types
                    case 'weak_username':
                        iconClass = '⚠️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Weak Username Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'admin_weak':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Admin User with Weak Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-rename-user">Rename Admin</button>
                            <button class="vmpfence-btn-demote-user">Demote User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'email_match':
                        iconClass = '📧';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Username Matches Email';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'name_exposed':
                        iconClass = '👁️';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Display Name Exposes Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-display-name">Update Display Name</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'numeric_username':
                        iconClass = '🔢';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Numeric-Only Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_admins':
                        iconClass = '👥';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Too Many Administrator Accounts';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-admins">Review Admin Users</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'admin_user_id_1':
                        iconClass = '🎯';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Admin User with ID 1';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-create-new-admin">Create New Admin</button>
                            <button class="vmpfence-btn-demote-user">Demote This User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'inactive_admin':
                        iconClass = '💤';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Inactive Admin Account';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-user">Remove User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'sequential_ids':
                        iconClass = '🔢';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Sequential User ID Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-enumeration">Review Enumeration Risk</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'api_exposure':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'User Enumeration via REST API';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-disable-api">Disable User API</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    // File Scanner types - modified case handled above at line 761
                    case 'unknown_threat':
                        iconClass = '❓';
                        issueClass = 'vmpfence-issue-critical';
                        
                        // Get file path information
                        const threatFilePath = issue.file_path || issue.location || 'Unknown file';
                        const threatFileName = threatFilePath.split('/').pop() || threatFilePath;
                        
                        issueTitle = `Unknown Threat Detected: ${threatFileName}`;
                        
                        // Enhanced description with file details
                        var enhancedDescription = `File: ${threatFilePath}
${issue.description || 'Suspicious file with potential security risk detected'}

This file contains patterns or characteristics that suggest it may be malicious but doesn't match known malware signatures. Manual investigation is recommended.`;
                        
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete-file">Delete File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        
                        // Set display description for this specific case
                        displayDescription = enhancedDescription;
                        break;
                    case 'malicious_content':
                        iconClass = '🦠';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Malicious Content Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete-file">Delete File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_external_file':
                        iconClass = '📁';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious File Outside WordPress';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'legitimacy_concern':
                        iconClass = '🔍';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Legitimacy Concern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_update':
                        iconClass = '🔄';
                        issueClass = 'vmpfence-issue-info';
                        issueTitle = 'Plugin Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-plugin">Update Plugin</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'theme_update':
                        iconClass = '🎨';
                        issueClass = 'vmpfence-issue-info';
                        issueTitle = 'Theme Update Available';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-theme">Update Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_modified':
                        iconClass = '⚡';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Plugin File Modified';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-reinstall-plugin">Reinstall Plugin</button>
                            <button class="vmpfence-btn-view-changes">View Changes</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_suspicious_file':
                        iconClass = '🔍';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious File in Plugin';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-file">Remove File</button>
                            <button class="vmpfence-btn-investigate">Investigate</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'theme_suspicious':
                        iconClass = '🎨';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Theme File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-file">Edit File</button>
                            <button class="vmpfence-btn-reinstall-theme">Reinstall Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'theme_suspicious_file':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Critical Malicious Pattern in Theme';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-theme">Remove Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    
                    // === MALWARE SCANNER TYPES (class-malware-scanner.php) ===
                    case 'malware_detected':
                        iconClass = '☠️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Malware Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-code">View Malware</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'context_analysis':
                        iconClass = '🔍';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Context Analysis Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">Review Context</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'obfuscation':
                        iconClass = '🌫️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Code Obfuscation';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View Obfuscated Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'base64_malware':
                        iconClass = '🔤';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Base64 Encoded Malware';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-decode">Decode Base64</button>
                            <button class="vmpfence-btn-view-code">View Encoded Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'entropy_analysis':
                        iconClass = '📊';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'High Entropy Content';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">Review Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'malicious_url':
                        iconClass = '🌐';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Malicious URL';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View URL Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === BADSTRINGS DETECTOR TYPES (class-badstrings-detector.php) ===
                    case 'eval_encoding_combination':
                        iconClass = '🦠';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Eval + Encoding Malware Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-code">View Obfuscated Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'multiple_encoding_layers':
                        iconClass = '🧅';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Multiple Encoding Layers';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-decode">Decode Layers</button>
                            <button class="vmpfence-btn-view-code">View Layered Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'obfuscated_variable_eval':
                        iconClass = '🔀';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Obfuscated Variable Eval';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View Variable Eval</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'concatenated_function_name':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Concatenated Function Name';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View Function Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'multi_category_badstring_cluster':
                        iconClass = '🎯';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Multiple Malware Indicators';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-code">View Cluster Pattern</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === WP INTEGRITY CHECKER TYPES (class-wp-integrity-checker.php) ===
                    case 'missing_core_file':
                        iconClass = '❌';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Missing WordPress Core File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-restore-core">Restore Core File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'modified_core_file':
                        iconClass = '⚠️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Modified WordPress Core File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-diff">View Differences</button>
                            <button class="vmpfence-btn-restore-core">Restore Core File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'missing_plugin_file':
                        iconClass = '🔌';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Missing Plugin File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-reinstall-plugin">Reinstall Plugin</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'modified_plugin_file':
                        iconClass = '🔧';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Modified Plugin File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-diff">View Changes</button>
                            <button class="vmpfence-btn-repair-file">Repair File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'missing_theme_file':
                        iconClass = '🎨';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Missing Theme File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-reinstall-theme">Reinstall Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'modified_theme_file':
                        iconClass = '🎨';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Modified Theme File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-diff">View Changes</button>
                            <button class="vmpfence-btn-restore-theme">Restore Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === PASSWORD SCANNER TYPES (class-password-scanner.php) ===
                    case 'weak_username':
                        iconClass = '👤';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Weak Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-username">Change Username</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'admin_simple_username':
                        iconClass = '👨‍💼';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Admin Simple Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-username">Change Admin Username</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'username_email_match':
                        iconClass = '📧';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Username Matches Email';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-username">Change Username</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'username_display_name':
                        iconClass = '👁️';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Username Matches Display Name';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-display-name">Change Display Name</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'multiple_admins':
                        iconClass = '👥';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Multiple Admin Users';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-admins">Review Admin Users</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'admin_user_id_1':
                        iconClass = '🥇';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Admin User ID 1';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-user-id">Change User ID</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === USER SECURITY SCANNER TYPES (class-user-security-scanner.php) ===
                    case 'admin_weak':
                        iconClass = '🔐';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Admin Weak Security';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-strengthen-admin">Strengthen Admin Security</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'email_match':
                        iconClass = '📬';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Email Match Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-email">Fix Email Issue</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'name_exposed':
                        iconClass = '👁️‍🗨️';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Name Exposed';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-hide-name">Hide Name</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'numeric_username':
                        iconClass = '🔢';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Numeric Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-username">Change Username</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_admins':
                        iconClass = '👥';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Excessive Admin Users';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-admins">Review Admin Users</button>
                            <button class="vmpfence-btn-demote-users">Demote Some Users</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'inactive_admin':
                        iconClass = '😴';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Inactive Admin User';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-demote-user">Demote User</button>
                            <button class="vmpfence-btn-delete-user">Delete User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'sequential_ids':
                        iconClass = '🔢';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Sequential User IDs';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-users">Review User IDs</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'api_exposure':
                        iconClass = '🔌';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'API Exposure Risk';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-secure-api">Secure API</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === VULNERABILITY SCANNER TYPES (class-vulnerability-scanner.php) ===
                    case 'core_vulnerability':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'WordPress Core Vulnerability';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-core">Update WordPress</button>
                            <button class="vmpfence-btn-view-cve">View CVE Details</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'core_vulnerability_range':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'WordPress Core Vulnerability Range';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-core">Update WordPress</button>
                            <button class="vmpfence-btn-view-cve">View CVE Details</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_theme':
                        iconClass = '🎨';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Suspicious Theme';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-switch-theme">Switch Theme</button>
                            <button class="vmpfence-btn-delete-theme">Delete Theme</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'plugin_vulnerability':
                        iconClass = '🔌';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Plugin Vulnerability';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-update-plugin">Update Plugin</button>
                            <button class="vmpfence-btn-deactivate-plugin">Deactivate Plugin</button>
                            <button class="vmpfence-btn-view-cve">View CVE Details</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === USER OPTION AUDIT SCANNER TYPES (class-user-option-audit-scanner.php) ===
                    case 'new_admin_user':
                        iconClass = '👨‍💼';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'New Admin User Created';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-review-user">Review User</button>
                            <button class="vmpfence-btn-demote-user">Demote User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_admin_username':
                        iconClass = '🔍';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Suspicious Admin Username';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-change-username">Change Username</button>
                            <button class="vmpfence-btn-delete-user">Delete User</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_option_url':
                        iconClass = '⚙️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Option URL';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-option">Fix Option</button>
                            <button class="vmpfence-btn-view-option">View Option</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === CONTENT SAFETY SCANNER TYPES (class-content-safety-scanner.php) ===
                    case 'aggressive_tone':
                        iconClass = '😡';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Aggressive Tone Content';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_language':
                        iconClass = '🗣️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Language';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_url':
                        iconClass = '🔗';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Suspicious URL';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-url">Remove URL</button>
                            <button class="vmpfence-btn-check-url">Check URL</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'blacklisted_domain':
                        iconClass = '🚫';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Blacklisted Domain';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-domain">Remove Domain</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_url_length':
                        iconClass = '📏';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Excessive URL Length';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-shorten-url">Shorten URL</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_redirect_param':
                        iconClass = '↪️';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious Redirect Parameter';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-param">Remove Parameter</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_uppercase':
                        iconClass = '🔠';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Excessive Uppercase Text';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-case">Fix Text Case</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_special_chars':
                        iconClass = '❗';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Excessive Special Characters';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-clean-chars">Clean Characters</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'mixed_script_homograph':
                        iconClass = '🔤';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Mixed Script Homograph Attack';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-script">Fix Script Issues</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'hidden_unicode_chars':
                        iconClass = '👻';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Hidden Unicode Characters';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-remove-unicode">Remove Hidden Chars</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'high_pressure_tactics':
                        iconClass = '⏰';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'High Pressure Tactics';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-edit-content">Edit Content</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'excessive_punctuation':
                        iconClass = '❓';
                        issueClass = 'vmpfence-issue-low';
                        issueTitle = 'Excessive Punctuation';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-fix-punctuation">Fix Punctuation</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === SENSITIVITY SCANNER TYPES (class-sensitivity-scanner.php) ===
                    case 'embedded_php':
                        iconClass = '🐘';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Embedded PHP Code';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View PHP Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'suspicious_string':
                        iconClass = '🧵';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Suspicious String Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View String</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'svg_script':
                        iconClass = '🖼️';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'SVG Script Injection';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-clean-svg">Clean SVG</button>
                            <button class="vmpfence-btn-view-code">View SVG Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === PUBLIC FILES SCANNER TYPES (class-public-files-scanner.php) ===
                    case 'public_config_file':
                        iconClass = '⚙️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Public Config File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-secure-file">Secure File</button>
                            <button class="vmpfence-btn-move-file">Move File</button>
                            <button class="vmpfence-btn-view-file">View File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'public_quarantined_file':
                        iconClass = '📦';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'Public Quarantined File';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-secure-file">Secure File</button>
                            <button class="vmpfence-btn-delete-file">Delete File</button>
                            <button class="vmpfence-btn-view-file">View File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    // === BINARY DETECTOR DYNAMIC TYPES ===
                    case 'EXECUTABLE':
                        iconClass = '⚙️';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Executable File in Web Directory';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-view-hex">View Executable</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                    case 'UNKNOWN':
                        iconClass = '❓';
                        issueClass = 'vmpfence-issue-medium';
                        issueTitle = 'Unknown Binary Pattern';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-analyze">Analyze Pattern</button>
                            <button class="vmpfence-btn-view-hex">View Binary Data</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'core_unknown':
                        iconClass = '🚨';
                        issueClass = 'vmpfence-issue-unknown';
                        issueTitle = 'Unknown Core File Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-delete">Delete</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'code_injection_in_option':
                        iconClass = '💉';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Code Injection in WordPress Option';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-clean-option">Clean Option</button>
                            <button class="vmpfence-btn-view-code">View Injected Code</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'domain_blocklist':
                        iconClass = '🚫';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Domain Blocklist Detection';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-investigate">Investigate Domain</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'spamvertising':
                        iconClass = '📧';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = 'Spamvertising Activity Detected';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'ip_spam':
                        iconClass = '🌐';
                        issueClass = 'vmpfence-issue-high';
                        issueTitle = 'IP Spam Reputation Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-contact-host">Contact Host Provider</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    case 'binary_signature':
                        iconClass = '🦠';
                        issueClass = 'vmpfence-issue-critical';
                        issueTitle = issue.title || 'Binary Malware Signature';
                        // Override description to include file path
                        displayDescription = `<strong>File:</strong> ${issue.file_path || 'Unknown file'}<br><br>${description}`;
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-view-code">View Malicious Code</button>
                            <button class="vmpfence-btn-delete">Delete File</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                        
                    default:
                        iconClass = '❓';
                        issueClass = 'vmpfence-issue-other';
                        issueTitle = 'Other Issue';
                        actionButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-details">Details</button>
                        `;
                        detailButtons = isIgnored ? `
                            <button class="vmpfence-btn-unignore">Unignore</button>
                        ` : `
                            <button class="vmpfence-btn-ignore">Ignore</button>
                            <button class="vmpfence-btn-mark-fixed">Mark as Fixed</button>
                        `;
                        break;
                }
                
                // Add status indicator for ignored issues
                const statusIndicator = isIgnored ? '<span class="vmpfence-issue-ignored-badge">IGNORED</span>' : '';
                
                let issueHtml;
                
                // Special handling for plugin and theme updates
                if (issueTypeDetail === 'plugin_update' || issueTypeDetail === 'theme_update') {
                    const isPlugin = issueTypeDetail === 'plugin_update';
                    
                    // Extract plugin/theme info from description (e.g., "Plugin 'Akismet' needs an upgrade (5.3.7 -> 5.5)")
                    const descMatch = description.match(/(Plugin|Theme) '([^']+)' needs an upgrade \(([^)]+) -> ([^)]+)\)/);
                    if (descMatch) {
                        const name = descMatch[2];
                        const currentVersion = descMatch[3];
                        const newVersion = descMatch[4];
                        
                        // Generate URLs from file_path (e.g., "plugin:akismet/akismet.php" or "theme:twentytwentyone")
                        let slug = issue.file_path.replace(isPlugin ? 'plugin:' : 'theme:', '');
                        if (isPlugin && slug.includes('/')) {
                            slug = slug.split('/')[0]; // Get plugin directory name
                        }
                        
                        const url = isPlugin ? `https://wordpress.org/plugins/${slug}/` : `https://wordpress.org/themes/${slug}/`;
                        const changelogUrl = isPlugin ? `https://wordpress.org/plugins/${slug}/#developers` : `https://wordpress.org/themes/${slug}/#developers`;
                        const detailsText = `You need to upgrade '${name}' to the newest version to ensure you have any security fixes the developer has released.`;
                        
                        // Generate update URL (same logic as Update Now button)
                        const currentUrl = window.location.href;
                        const baseUrl = currentUrl.substring(0, currentUrl.indexOf('/wp-admin/'));
                        const updateUrl = isPlugin ? 
                            `${baseUrl}/wp-admin/update-core.php#update-plugins-table` : 
                            `${baseUrl}/wp-admin/update-core.php#update-themes-table`;
                        
                        issueHtml = `
                            <div class="vmpfence-issue-item ${issueClass} ${isIgnored ? 'vmpfence-issue-ignored' : ''}" data-issue-id="${issue.id}">
                                <div class="vmpfence-issue-summary">
                                    <!-- Icon Column -->
                                    <div class="vmpfence-issue-icon">${iconClass}</div>
                                    
                                    <!-- Column 1: Title and Type -->
                                    <div class="vmpfence-issue-col-1">
                                        <div class="vmpfence-issue-title">${issueTitle} ${statusIndicator}</div>
                                        <div class="vmpfence-issue-file">${issueType}</div>
                                    </div>
                                    
                                    <!-- Column 2: Detection Time and Severity -->
                                    <div class="vmpfence-issue-col-2">
                                        <div class="vmpfence-issue-time">${new Date(issue.detected_time).toLocaleString()}</div>
                                        <div class="vmpfence-issue-severity vmpfence-severity-${severity}">${severity}</div>
                                    </div>
                                    
                                    <!-- Column 3: Action Buttons -->
                                    <div class="vmpfence-issue-col-3">
                                        <div class="vmpfence-issue-controls">
                                            ${actionButtons}
                                        </div>
                                    </div>
                                </div>
                                <div class="vmpfence-issue-detail">
                                    <div class="vmpfence-update-details">
                                        <p><strong>${isPlugin ? 'Plugin' : 'Theme'} Name:</strong> ${name}</p>
                                        <p><strong>Current ${isPlugin ? 'Plugin' : 'Theme'} Version:</strong> ${currentVersion}</p>
                                        <p><strong>New ${isPlugin ? 'Plugin' : 'Theme'} Version:</strong> ${newVersion}</p>
                                        <p><strong>Details:</strong> ${detailsText} <a href="${updateUrl}">Click here to update now.</a></p>
                                        <p><strong>${isPlugin ? 'Plugin' : 'Theme'} URL:</strong> <a href="${url}" target="_blank">${url}</a></p>
                                        <p><strong>Changelog:</strong> <a href="${changelogUrl}" target="_blank">${changelogUrl}</a></p>
                                    </div>
                                    <div class="vmpfence-issue-controls">
                                        ${detailButtons}
                                    </div>
                                </div>
                            </div>
                        `;
                    } else {
                        // Fallback if we can't parse the description
                        issueHtml = `
                            <div class="vmpfence-issue-item ${issueClass} ${isIgnored ? 'vmpfence-issue-ignored' : ''}" data-issue-id="${issue.id}">
                                <div class="vmpfence-issue-summary">
                                    <div class="vmpfence-issue-icon">${iconClass}</div>
                                    <div class="vmpfence-issue-title">${issueTitle} ${statusIndicator}</div>
                                </div>
                                <div class="vmpfence-issue-detail">
                                    <div class="vmpfence-issue-description"><strong>Details:</strong> ${displayDescription}</div>
                                </div>
                            </div>
                        `;
                    }
                } else {
                    // Standard issue layout for non-update issues
                    issueHtml = `
                        <div class="vmpfence-issue-item ${issueClass} ${isIgnored ? 'vmpfence-issue-ignored' : ''}" data-issue-id="${issue.id}" data-file-path="${issue.file_path || ''}">
                            <div class="vmpfence-issue-summary">
                                <!-- Icon Column -->
                                <div class="vmpfence-issue-icon">${iconClass}</div>
                                
                                <!-- Column 1: Title and Type -->
                                <div class="vmpfence-issue-col-1">
                                    <div class="vmpfence-issue-title">${issueTitle} ${statusIndicator}</div>
                                    <div class="vmpfence-issue-file">${issueType}</div>
                                </div>
                                
                                <!-- Column 2: Detection Time and Severity -->
                                <div class="vmpfence-issue-col-2">
                                    <div class="vmpfence-issue-time">${new Date(issue.detected_time).toLocaleString()}</div>
                                    <div class="vmpfence-issue-severity vmpfence-severity-${severity}">${severity}</div>
                                </div>
                                
                                <!-- Column 3: Action Buttons -->
                                <div class="vmpfence-issue-col-3">
                                    <div class="vmpfence-issue-controls">
                                        ${actionButtons}
                                    </div>
                                </div>
                            </div>
                            <div class="vmpfence-issue-detail">
                                <div class="vmpfence-issue-description"><strong>Details:</strong> ${displayDescription}</div>
                                <div class="vmpfence-issue-meta">
                                    <div><strong>Issue Type:</strong> ${issueType}</div>
                                    <div><strong>Violation Type:</strong> ${issueTypeDetail}</div>
                                    <div><strong>Severity:</strong> ${severity}</div>
                                    <div><strong>Detected:</strong> ${new Date(issue.detected_time).toLocaleString()}</div>
                                    ${isIgnored ? `<div><strong>Ignored:</strong> ${new Date(issue.resolved_time).toLocaleString()}</div>` : ''}
                                </div>
                                <div class="vmpfence-issue-controls">
                                    ${detailButtons}
                                </div>
                            </div>
                        </div>
                    `;
                }
                $container.append(issueHtml);
            });
        }
    }
    
    /**
     * Handle issue summary clicks
     */
    $(document).on('click', '.vmpfence-issue-summary', function(e) {
        // Don't expand if clicking on buttons
        if ($(e.target).closest('.vmpfence-issue-controls').length) {
            return;
        }
        
        const $item = $(this).closest('.vmpfence-issue-item');
        const $details = $item.find('.vmpfence-issue-detail');
        
        if ($details.is(':visible')) {
            $details.slideUp();
        } else {
            $details.slideDown();
        }
    });
        
    /**
     * Handle Details button clicks
     */
    $(document).on('click', '.vmpfence-btn-details', function(e) {
        e.stopPropagation();
        const $item = $(this).closest('.vmpfence-issue-item');
        const $details = $item.find('.vmpfence-issue-detail');
        
        if ($details.is(':visible')) {
            $details.slideUp();
            $(this).text('Details');
        } else {
            $details.slideDown();
            $(this).text('Hide Details');
        }
    });

    /**
     * Handle ignore button clicks
     */
    $(document).on('click', '.vmpfence-btn-ignore', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            console.error('VMPFence: No issue ID found');
            return;
        }
        
        // Disable button and show loading
        $button.prop('disabled', true).text('Ignoring...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_ignore_issue',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Success - update UI
                    // Remove issue from current view with animation
                    $issueItem.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update tab counts
                        updateTabCounts(response.data.active_count, response.data.ignored_count);
                        
                        // Reload fresh data from database to ensure consistency
                        loadScanIssues();
                        
                        // Check if no issues left in current view
                        if ($('.vmpfence-issues-container .vmpfence-issue-item').length === 0) {
                            $('.vmpfence-no-issues').show();
                            $('.vmpfence-scan-issues-list').hide();
                        }
                    });
                } else {
                    console.error('VMPFence: Failed to ignore issue:', response.data.message || 'Unknown error');
                    $button.prop('disabled', false).text('Ignore');
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to ignore issue:', error);
                $button.prop('disabled', false).text('Ignore');
            }
        });
    });

    /**
     * Handle unignore button clicks
     */
    $(document).on('click', '.vmpfence-btn-unignore', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            console.error('VMPFence: No issue ID found');
            return;
        }
        
        // Disable button and show loading
        $button.prop('disabled', true).text('Unignoring...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_unignore_issue',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Remove issue from ignored view with animation
                    $issueItem.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update tab counts
                        updateTabCounts(response.data.active_count, response.data.ignored_count);
                        
                        // Issue moved back to Results Found
                        // Reload fresh data from database to ensure consistency
                        loadScanIssues();
                        
                        // Check if no ignored issues left
                        if ($('.vmpfence-issues-container .vmpfence-issue-item').length === 0) {
                            $('.vmpfence-no-issues').show();
                            $('.vmpfence-scan-issues-list').hide();
                        }
                    });
                } else {
                    console.error('VMPFence: Failed to unignore issue:', response.data.message || 'Unknown error');
                    $button.prop('disabled', false).text('Unignore');
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to unignore issue:', error);
                $button.prop('disabled', false).text('Unignore');
            }
        });
    });

    /**
     * Handle mark as fixed button clicks
     */
    $(document).on('click', '.vmpfence-btn-mark-fixed', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            console.error('VMPFence: No issue ID found');
            return;
        }
        
        // Disable button and show loading
        $button.prop('disabled', true).text('Marking as Fixed...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_mark_as_fixed',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Success - remove issue immediately
                    // Remove the issue element immediately
                    $issueItem.remove();
                    
                    // Update tab counts
                    updateTabCounts(response.data.active_count, response.data.ignored_count);
                    
                    // Update scan message
                    updateScanMessage(response.data.active_count, response.data.ignored_count);
                    
                    // Refresh status indicators to reflect the updated issues_found counts
                    $.ajax({
                        url: vmpfence_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'vmpfence_get_scan_status',
                            nonce: vmpfence_ajax.nonce
                        },
                        success: function(statusResponse) {
                            if (statusResponse.success && statusResponse.data.status_data) {
                                updateScanStatusIndicators(statusResponse.data.status_data);
                            }
                        },
                        error: function() {
                            console.warn('VMPFence: Failed to refresh status indicators');
                        }
                    });
                    
                    // Check if no issues left
                    if ($('.vmpfence-issues-container .vmpfence-issue-item').length === 0) {
                        $('.vmpfence-no-issues').show();
                        $('.vmpfence-scan-issues-list').hide();
                    }
                } else {
                    console.error('VMPFence: Failed to mark issue as fixed:', response.data.message || 'Unknown error');
                    $button.prop('disabled', false).text('Mark as Fixed');
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: AJAX error:', error);
                console.error('VMPFence: XHR:', xhr);
                $button.prop('disabled', false).text('Mark as Fixed');
            }
        });
    });

    /**
     * Handle disable debug button clicks
     */
    $(document).on('click', '.vmpfence-btn-disable-debug', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            console.error('VMPFence: No issue ID found');
            VMPFenceNotifications.showError('Unable to identify the issue. Please try again.', 4000);
            return;
        }
        
        // Show confirmation dialog
        VMPFenceNotifications.showConfirmModal({
            title: 'Disable Debug Mode',
            message: 'This will modify your wp-config.php file to set WP_DEBUG to false. A backup will be created automatically. Do you want to continue?',
            confirmText: 'Yes, Disable Debug',
            cancelText: 'Cancel',
            type: 'warning',
            showIcon: true
        }).then(function(confirmed) {
            if (!confirmed) {
                // console.log('VMPFence: Debug disable cancelled by user');
                return;
            }
            
            // Disable button and show loading state
            $button.prop('disabled', true).text('Disabling Debug...');
            
            // Show loading toast
            const loadingToast = VMPFenceNotifications.showInfo('Modifying wp-config.php...', 0, 'Please Wait');
            
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_disable_debug',
                    issue_id: issueId,
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    // Remove loading toast
                    VMPFenceNotifications.removeToast(loadingToast);
                    
                    if (response.success) {
                        // Show success message
                        VMPFenceNotifications.showSuccess(
                            response.data.message || 'Debug mode has been successfully disabled.',
                            4000,
                            'Success'
                        );
                        
                        // Remove the issue from UI
                        $issueItem.remove();
                        
                        // Update tab counts
                        updateTabCounts(response.data.active_count, response.data.ignored_count);
                        
                        // Update scan message
                        updateScanMessage(response.data.active_count, response.data.ignored_count);
                        
                        // Refresh status indicators
                        $.ajax({
                            url: vmpfence_ajax.ajax_url,
                            type: 'POST',
                            data: {
                                action: 'vmpfence_get_scan_status',
                                nonce: vmpfence_ajax.nonce
                            },
                            success: function(statusResponse) {
                                if (statusResponse.success && statusResponse.data.status_data) {
                                    updateScanStatusIndicators(statusResponse.data.status_data);
                                }
                            },
                            error: function() {
                                console.warn('VMPFence: Failed to refresh status indicators');
                            }
                        });
                        
                        // Check if no issues left
                        if ($('.vmpfence-issues-container .vmpfence-issue-item').length === 0) {
                            $('.vmpfence-no-issues').show();
                            $('.vmpfence-scan-issues-list').hide();
                        }
                    } else {
                        // Show error message
                        VMPFenceNotifications.showError(
                            response.data.message || 'Failed to disable debug mode.',
                            6000,
                            'Error'
                        );
                        $button.prop('disabled', false).text('Disable Debug');
                    }
                },
                error: function(xhr, status, error) {
                    // Remove loading toast
                    VMPFenceNotifications.removeToast(loadingToast);
                    
                    VMPFenceNotifications.showError(
                        'Network error occurred: ' + error,
                        6000,
                        'AJAX Error'
                    );
                    console.error('VMPFence: AJAX error:', error);
                    console.error('VMPFence: XHR:', xhr);
                    $button.prop('disabled', false).text('Disable Debug');
                }
            });
        });
    });

    /**
     * Handle "Go To Scan Settings" button clicks
     */
    $(document).on('click', '.vmpfence-btn-scan-settings', function(e) {
        e.preventDefault();
        
        // Find the Advanced Scan Options section
        const advancedSection = document.getElementById('advanced-content');
        const advancedHeader = document.querySelector('.vmpfence-options-section-header[onclick="toggleSection(\'advanced\')"]');
        
        if (advancedSection && advancedHeader) {
            // Expand the Advanced Scan Options section if it's collapsed
            if (advancedSection.style.display === 'none' || !advancedSection.style.display) {
                // Call the toggleSection function to expand it
                if (typeof toggleSection === 'function') {
                    toggleSection('advanced');
                }
            }
            
            // Scroll to the Advanced Scan Options section
            advancedHeader.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
            
            // Add a highlight effect to draw attention
            advancedHeader.style.transition = 'background-color 0.3s ease';
            advancedHeader.style.backgroundColor = '#fff3cd';
            
            // Remove highlight after 2 seconds
            setTimeout(() => {
                advancedHeader.style.backgroundColor = '';
            }, 2000);
        } else {
            // Fallback: Navigate to VMPFence scan settings page and target advanced options
            const settingsUrl = 'admin.php?page=vmpfence-scan-options#advanced-content';
            window.open(settingsUrl, '_blank');
        }
    });

    /**
     * Handle "Manage Options" button clicks for general options
     */
    $(document).on('click', '.vmpfence-btn-general-options', function(e) {
        e.preventDefault();
        
        // Find the General Options section (or whatever section contains reputation settings)
        const generalSection = document.getElementById('general-content');
        const generalHeader = document.querySelector('.vmpfence-options-section-header[onclick="toggleSection(\'general\')"]');
        
        if (generalSection && generalHeader) {
            // Expand the General Options section if it's collapsed
            if (generalSection.style.display === 'none' || !generalSection.style.display) {
                // Call the toggleSection function to expand it
                if (typeof toggleSection === 'function') {
                    toggleSection('general');
                }
            }
            
            // Scroll to the General Options section
            generalHeader.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
            
            // Add a highlight effect to draw attention
            generalHeader.style.transition = 'background-color 0.3s ease';
            generalHeader.style.backgroundColor = '#fff3cd';
            
            // Remove highlight after 2 seconds
            setTimeout(() => {
                generalHeader.style.backgroundColor = '';
            }, 2000);
        } else {
            // Fallback: Navigate to VMPFence general options page and target general section
            const optionsUrl = 'admin.php?page=vmpfence-scan-options#general-content';
            window.location.href = optionsUrl;
        }
    });

    /**
     * Handle update button clicks
     */
    $(document).on('click', '.vmpfence-btn-update', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueType = $issueItem.find('.vmpfence-issue-icon').next().text().trim();
        
        // Determine the update URL based on issue type
        let updateUrl = '/wp-admin/update-core.php';
        
        if (issueType.includes('Plugin')) {
            updateUrl = '/wp-admin/update-core.php#update-plugins-table';
        } else if (issueType.includes('Theme')) {
            updateUrl = '/wp-admin/update-core.php#update-themes-table';
        }
        
        // Get the current site URL and append the update path
        const currentUrl = window.location.href;
        const baseUrl = currentUrl.substring(0, currentUrl.indexOf('/wp-admin/'));
        const fullUpdateUrl = baseUrl + updateUrl;
        
        // Open the update page in the same window
        window.location.href = fullUpdateUrl;
    });

    /**
     * Handle "View Malicious Code" button clicks
     */
    $(document).on('click', '.vmpfence-btn-view-code', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        const issueTitle = $issueItem.find('.vmpfence-issue-title').text().trim();
        
        if (!issueId) {
            VMPFenceNotifications.showError('Issue ID not found');
            return;
        }

        // For code injection in WordPress options, show modal instead of opening file
        if (issueTitle.includes('Code Injection in WordPress Option')) {
            showOptionCodeModal(issueId);
            return;
        }

        // For file-based issues, use the existing file view functionality
        // Create URL similar to VIEW FULL LOG button
        const nonce = vmpfence_ajax.nonce.replace('vmpfence_scan_nonce', 'vmpfence_view_file_nonce');
        const viewUrl = window.location.origin + window.location.pathname.replace('wp-admin/admin.php', '') + 
                       '?_vmpfence=viewMaliciousFile&issue_id=' + issueId + '&nonce=' + 
                       btoa(Math.random().toString()).substring(10, 15); // Simple nonce for now
        
        // We need to create a proper nonce, let's do it via AJAX first
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_view_file_nonce',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data.view_url) {
                    window.open(response.data.view_url, '_blank');
                } else {
                    VMPFenceNotifications.showError('Unable to access file: ' + (response.data || 'Unknown error'));
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error requesting file access');
            }
        });
    });

    /**
     * Handle "Clean Option" button clicks for code injection in WordPress options
     */
    $(document).on('click', '.vmpfence-btn-clean-option', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            showCleanOptionResultModal('Error', 'Issue ID not found', 'error');
            return;
        }

        // Show confirmation modal instead of browser confirm
        showCleanOptionConfirmModal(issueId, $issueItem);
    });

    /**
     * Show clean option confirmation modal
     */
    function showCleanOptionConfirmModal(issueId, $issueItem) {
        // Get option name from the issue details - try multiple selectors and sources
        let displayOptionName = 'Unknown option';
        
        // Try to get from the Details section which is more reliable
        const detailsSection = $issueItem.find('.vmpfence-issue-details, .details').text();
        
        // Also try the main issue description
        const issueDescription = $issueItem.text();
        
        // Combine both sources for better matching
        const fullText = detailsSection + ' ' + issueDescription;
        
        // Try multiple patterns
        let optionMatch = fullText.match(/Option\s*'([^']+)'/i) || 
                         fullText.match(/'([^']+)'\s*contains/i) ||
                         fullText.match(/option_name[:\s]*['"]([^'"]+)['"]/i) ||
                         fullText.match(/([a-zA-Z_][a-zA-Z0-9_]*)\s*contains\s*suspicious/i);
        
        if (optionMatch) {
            displayOptionName = optionMatch[1];
        }
        
        const modalHTML = `
            <div id="vmpfence-clean-confirm-modal" class="vmpfence-modal-overlay">
                <div class="vmpfence-modal-content">
                    <div class="vmpfence-modal-header">
                        <h3><i class="fas fa-broom"></i> Clean WordPress Option</h3>
                        <button class="vmpfence-modal-close" type="button">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-modal-file-info">
                            <strong>Option:</strong> <span class="option-name">${displayOptionName}</span>
                        </div>
                        <div class="vmpfence-modal-description">
                            <p><i class="fas fa-exclamation-triangle" style="color: #f39c12;"></i> <strong>This action will remove detected malicious code from the WordPress option.</strong></p>
                            <p>The cleaning process will:</p>
                            <ul>
                                <li>Remove suspicious PHP code patterns</li>
                                <li>Remove malicious JavaScript injections</li>
                                <li>Preserve legitimate option data</li>
                                <li>Mark the security issue as resolved</li>
                            </ul>
                        </div>
                        <div class="vmpfence-modal-question">
                            <h4>Are you sure you want to proceed?</h4>
                            <p class="vmpfence-modal-note"><strong>Note:</strong> This action cannot be undone. Make sure you have a backup if needed.</p>
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-danger vmpfence-btn-confirm-clean" type="button" data-issue-id="${issueId}">
                            <i class="fas fa-broom"></i> Clean Option
                        </button>
                        <button class="vmpfence-btn vmpfence-btn-secondary vmpfence-modal-close" type="button">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        `;

        // Remove existing modal if any
        $('#vmpfence-clean-confirm-modal').remove();
        
        // Add modal to body
        $('body').append(modalHTML);
        
        // Show modal
        $('#vmpfence-clean-confirm-modal').fadeIn(300);
    }

    /**
     * Handle clean option confirmation
     */
    $(document).on('click', '.vmpfence-btn-confirm-clean', function() {
        const $button = $(this);
        const issueId = $button.data('issue-id');
        const $issueItem = $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`);
        
        // Close confirmation modal
        $('#vmpfence-clean-confirm-modal').fadeOut(300, function() {
            $(this).remove();
        });

        // Show loading state on the original button
        const $originalButton = $issueItem.find('.vmpfence-btn-clean-option');
        const originalText = $originalButton.text();
        $originalButton.text('Cleaning...').prop('disabled', true);

        // Send AJAX request to clean the option
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_clean_option',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    showCleanOptionResultModal(
                        'Success',
                        `WordPress option cleaned successfully!<br><br>
                        <strong>Details:</strong><br>
                        • Option: ${response.data.option_name || 'Unknown'}<br>
                        • Original size: ${response.data.original_length || 'Unknown'} characters<br>
                        • Cleaned size: ${response.data.cleaned_length || 'Unknown'} characters<br>
                        • Removed: ${(response.data.original_length || 0) - (response.data.cleaned_length || 0)} characters`,
                        'success'
                    );
                    
                    // Mark the issue as fixed
                    $issueItem.fadeOut(500, function() {
                        $(this).remove();
                        updateIssueCount();
                    });
                } else {
                    showCleanOptionResultModal(
                        'Error',
                        'Failed to clean option: ' + (response.data || 'Unknown error'),
                        'error'
                    );
                }
            },
            error: function() {
                showCleanOptionResultModal(
                    'Error',
                    'An error occurred while cleaning the option. Please try again.',
                    'error'
                );
            },
            complete: function() {
                // Restore button state
                $originalButton.text(originalText).prop('disabled', false);
            }
        });
    });

    /**
     * Show clean option result modal
     */
    function showCleanOptionResultModal(title, message, type) {
        const iconClass = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle';
        const iconColor = type === 'success' ? '#27ae60' : '#e74c3c';
        const titleColor = type === 'success' ? '#27ae60' : '#e74c3c';
        
        const modalHTML = `
            <div id="vmpfence-clean-result-modal" class="vmpfence-modal-overlay">
                <div class="vmpfence-modal-content">
                    <div class="vmpfence-modal-header">
                        <h3 style="color: ${titleColor};"><i class="${iconClass}" style="color: ${iconColor};"></i> ${title}</h3>
                        <button class="vmpfence-modal-close" type="button">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-modal-description">
                            <p>${message}</p>
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-primary vmpfence-modal-close" type="button">
                            OK
                        </button>
                    </div>
                </div>
            </div>
        `;

        // Remove existing result modal if any
        $('#vmpfence-clean-result-modal').remove();
        
        // Add modal to body
        $('body').append(modalHTML);
        
        // Show modal
        $('#vmpfence-clean-result-modal').fadeIn(300);
    }

    /**
     * Show option code in modal for code injection issues
     */
    function showOptionCodeModal(issueId) {
        // Show loading state
        showCodeModal('Loading...', 'Loading option content...', 'Loading...');
        
        // Fetch option content via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_view_option_code',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    showCodeModal(
                        `WordPress Option: ${data.option_name}`,
                        data.issue_details,
                        data.option_value
                    );
                } else {
                    showCodeModal(
                        'Error',
                        'Failed to load option content',
                        `Error: ${response.data || 'Unknown error'}`
                    );
                }
            },
            error: function() {
                showCodeModal(
                    'Error',
                    'Failed to load option content',
                    'Network error occurred while fetching option content'
                );
            }
        });
    }

    /**
     * Show code modal with content
     */
    function showCodeModal(title, description, code) {
        // Remove existing modal if any
        $('#vmpfence-code-modal').remove();
        
        // Create modal HTML
        const modalHtml = `
            <div id="vmpfence-code-modal" class="vmpfence-modal-overlay">
                <div class="vmpfence-modal-content vmpfence-code-modal">
                    <div class="vmpfence-modal-header">
                        <h3>${escapeHtml(title)}</h3>
                        <button class="vmpfence-modal-close">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-code-description">
                            ${escapeHtml(description)}
                        </div>
                        <div class="vmpfence-code-container">
                            <div class="vmpfence-code-header">
                                <span>Code Content:</span>
                                <button class="vmpfence-btn-copy-code">Copy to Clipboard</button>
                            </div>
                            <pre class="vmpfence-code-content"><code>${escapeHtml(code)}</code></pre>
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-secondary vmpfence-modal-close">Close</button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Show modal
        $('#vmpfence-code-modal').fadeIn(300);
    }

    /**
     * Handle modal close functionality for all modals
     */
    $(document).on('click', '.vmpfence-modal-close', function() {
        // Find the parent modal and close it
        const $modal = $(this).closest('.vmpfence-modal-overlay');
        if ($modal.length) {
            $modal.fadeOut(300, function() {
                $(this).remove();
            });
        } else {
            // Fallback: close any visible modal
            $('.vmpfence-modal-overlay:visible').fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    // Handle clicking outside modal to close
    $(document).on('click', '.vmpfence-modal-overlay', function(e) {
        if (e.target === this) {
            $(this).fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    // Handle ESC key to close modal
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('.vmpfence-modal-overlay:visible').length) {
            $('.vmpfence-modal-overlay:visible').fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    $(document).on('click', '.vmpfence-btn-copy-code', function() {
        const codeText = $('.vmpfence-code-content code').text();
        
        // Try to use modern clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(codeText).then(function() {
                $(this).text('Copied!').removeClass('vmpfence-btn-copy-code');
                setTimeout(() => {
                    $('.vmpfence-btn-copy-code').text('Copy to Clipboard');
                }, 2000);
            }).catch(function() {
                fallbackCopyToClipboard(codeText);
            });
        } else {
            fallbackCopyToClipboard(codeText);
        }
    });

    /**
     * Fallback copy to clipboard for older browsers
     */
    function fallbackCopyToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            VMPFenceNotifications.showSuccess('Code copied to clipboard!');
        } catch (err) {
            VMPFenceNotifications.showError('Unable to copy to clipboard');
        } finally {
            document.body.removeChild(textArea);
        }
    }

    /**
     * Escape HTML for safe display
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Handle tab switching
     */
    $('.vmpfence-tab').on('click', function() {
        $('.vmpfence-tab').removeClass('vmpfence-tab-active');
        $(this).addClass('vmpfence-tab-active');
        
        // Show/hide content based on tab
        const $tab = $(this);
        const isIgnoredTab = $tab.text().includes('Ignored Results');
        
        // Always fetch fresh data from database when switching tabs
        loadScanIssuesForTab(isIgnoredTab);
    });
    
    /**
     * Load scan issues for specific tab (active or ignored)
     */
    function loadScanIssuesForTab(isIgnoredTab) {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_results',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Store fresh issues data globally
                    window.vmpfenceIssuesData = response.data;
                    
                    // Update tab counts with fresh data
                    updateTabCounts(response.data.active_count, response.data.ignored_count);
                    
                    // Update scan message with fresh counts
                    updateScanMessage(response.data.active_count, response.data.ignored_count);
                    
                    if (isIgnoredTab) {
                        // Show ignored issues
                        if (response.data.ignored_issues && response.data.ignored_issues.length > 0) {
                            showScanIssues(response.data.ignored_issues, true);
                        } else {
                            $('.vmpfence-scan-issues-list').hide();
                            $('.vmpfence-no-issues').show();
                        }
                    } else {
                        // Show active issues
                        if (response.data.issues && response.data.issues.length > 0) {
                            showScanIssues(response.data.issues, false);
                        } else {
                            $('.vmpfence-scan-issues-list').hide();
                            $('.vmpfence-no-issues').show();
                        }
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to load issues for tab:', error);
                $('.vmpfence-scan-issues-list').hide();
                $('.vmpfence-no-issues').show();
            }
        });
    }
    
    /**
     * Start progress polling during scan
     */
    function startProgressPolling() {
        
        // Stop idle heartbeat — we're now in active scan mode
        stopIdleScanHeartbeat();
        
        // Reset loading flag when starting new poll
        isLoadingResults = false;
        
        scanProgressInterval = setInterval(function() {
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_scan_progress',
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        updateProgressDisplay(response.data);
                        
                        // Check for async scan completion (prevent duplicate loads)
                        if (!isLoadingResults && (response.data.status === 'completed' || response.data.status === 'completed_with_timeout')) {
                            isLoadingResults = true; // Set flag immediately
                            scanJustCompleted = true; // Mark as fresh completion (trigger auto-reload)
                            stopProgressPolling();
                            
                            // Load scan results automatically for async scans
                            if (response.data.async_mode) {
                                // console.log('VMPFence: Async scan completed, loading results...');
                                loadAsyncScanResults();
                            }
                        } else if (response.data.status === 'error') {
                            stopProgressPolling();
                            clearAllLoadingIndicators();
                            // Clear error progress immediately to prevent it persisting
                            clearCompletedProgress();
                            $('.vmpfence-btn-start-scan').prop('disabled', false).text('START NEW SCAN');
                            console.error('VMPFence: Scan error:', response.data.current_section);
                        } else if (response.data.status === 'idle') {
                            stopProgressPolling();
                            $('.vmpfence-btn-start-scan').prop('disabled', false).text('START NEW SCAN');
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.warn('VMPFence: Progress polling error:', error);
                    // Continue polling even on error
                }
            });
        }, 2000); // Poll every 2000ms to catch fast scanners
    }
    
    /**
     * Load scan results after async completion
     */
    function loadAsyncScanResults() {
        // console.log('VMPFence: Loading async scan results...');
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_results',
                nonce: vmpfence_ajax.nonce,
                _nocache: Date.now() // Cache buster to force fresh data
            },
            success: function(response) {
                // console.log('VMPFence: Got scan results response:', response);
                if (response.success && response.data) {
                    // console.log('VMPFence: Calling updateScanResults with data:', response.data);
                    // Pass full response data including scan_data and comprehensive_statistics
                    // Note: updateScanResults will handle status indicator updates via updateScanStatusIndicators
                    updateScanResults(response.data);
                    
                    // console.log('VMPFence: Async scan results loaded successfully');
                    
                    // Show notification if scan completed with timeout
                    if (response.data && response.data.scan_data && response.data.scan_data.status === 'completed_with_timeout') {
                        console.warn('VMPFence: Scan completed with timeout - some scanners may have been skipped');
                    }
                    
                    // Clear the completed progress state to prevent re-detection
                    clearCompletedProgress();
                } else {
                    console.error('VMPFence: Failed to load scan results - invalid response');
                    clearAllLoadingIndicators();
                }
                
                // Reset flag after loading completes
                isLoadingResults = false;
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Error loading scan results:', error);
                clearAllLoadingIndicators();
                isLoadingResults = false; // Reset flag on error too
            }
        });
    }
    
    /**
     * Clear completed progress state (called after results loaded)
     * CRITICAL FIX: Made synchronous to prevent race condition with page reload
     */
    function clearCompletedProgress() {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            async: false, // CRITICAL: Must complete before page reloads
            data: {
                action: 'vmpfence_clear_scan_progress',
                nonce: vmpfence_ajax.nonce
            },
            success: function() {
                // console.log('VMPFence: Scan progress cleared successfully');
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to clear scan progress:', error);
            }
        });
    }
    
    /**
     * Stop progress polling
     */
    function stopProgressPolling() {
        if (scanProgressInterval) {
            clearInterval(scanProgressInterval);
            scanProgressInterval = null;
        }
        // Cross-disable cleanup: re-enable sync button if we disabled it
        var $syncBtn = $('#vmpfence-sync-signatures');
        if ($syncBtn.length && $syncBtn.data('disabled-by-scan')) {
            $syncBtn.prop('disabled', false).removeData('disabled-by-scan');
        }
        // Resume idle heartbeat to detect next external scan
        startIdleScanHeartbeat();
    }
    
    /**
     * Update progress display - simplified since all indicators show loading
     */
    function updateProgressDisplay(progress) {
        // All scan types already show loading animation
        
        // Highlight currently active scanner based on progress stage
        if (progress.scan_progress) {
            const currentStage = parseInt(progress.scan_progress);
            const stageMapping = {
                1: 'server_state',           // Server state scanning
                2: 'file_changes',           // File integrity scanning  
                3: 'user_security',          // User security scanning
                4: 'content_safety',         // Content safety scanning
                5: 'public_files',           // Public files scanning
                6: 'user_option_audit',      // User option audit
                7: 'vulnerability_scan',     // Vulnerability scanning
                8: 'malware_scan',           // Malware scanning
                9: 'blocklist_check',        // Domain blocklist check (reputation)
                10: 'spamvertising_checks',  // Spamvertising check (reputation)
                11: 'spam_check'             // IP spam check (reputation)
            };
            
            const activeScanType = stageMapping[currentStage];
            if (activeScanType) {        
                // Track ALL scanner changes - not just repeating ones
                if (!window.vmpfenceLastScanType || window.vmpfenceLastScanType !== activeScanType) {
                    const timestamp = new Date().toLocaleTimeString();
                    // console.log(`VMPFence: 🔄 [${timestamp}] Scanner transition: ${window.vmpfenceLastScanType || 'none'} → ${activeScanType} (Stage ${currentStage})`);
                    
                    // Track timing for performance analysis
                    if (window.vmpfenceLastScanType && window.vmpfenceLastStageTime) {
                        const duration = Date.now() - window.vmpfenceLastStageTime;
                        // console.log(`VMPFence: ⏱️ Stage ${window.vmpfenceLastStage} (${window.vmpfenceLastScanType}) duration: ${duration}ms`);
                    }
                    
                    window.vmpfenceLastScanType = activeScanType;
                    window.vmpfenceLastStage = currentStage;
                    window.vmpfenceLastStageTime = Date.now();
                    window.vmpfenceScanCount = 1;
                } else {
                    window.vmpfenceScanCount = (window.vmpfenceScanCount || 0) + 1;
                    if (window.vmpfenceScanCount % 10 === 0) {
                        // console.log(`VMPFence: ⏳ Still running ${activeScanType} scanner... (${window.vmpfenceScanCount} polls)`);
                    }
                }
                
                // Clear previous active states
                $('.vmpfence-status-item').removeClass('scanning-active');
                
                // Highlight current scanner
                $(`.vmpfence-status-item[data-scan-type="${activeScanType}"]`).addClass('scanning-active');
            }
        }
        
        // Log completion timestamps to track which scanners finish too fast to be caught
        if (progress.status === 'completed' || progress.status === 'idle') {
            const completionTime = new Date().toLocaleTimeString();
            const finalStage = progress.scan_progress || window.vmpfenceLastStage || 'unknown';
            // console.log(`VMPFence: 🏁 [${completionTime}] SCAN COMPLETED! Final stage was ${finalStage}`);
            
            if (window.vmpfenceLastScanType && window.vmpfenceLastStageTime) {
                const finalDuration = Date.now() - window.vmpfenceLastStageTime;
                // console.log(`VMPFence: ⏱️ Final stage (${window.vmpfenceLastScanType}) duration: ${finalDuration}ms`);
            }
            
            // Clear all active scanner highlighting
            $('.vmpfence-status-item').removeClass('scanning-active');
            
            // Reset tracking variables
            window.vmpfenceLastScanType = null;
            window.vmpfenceLastStage = null;
            window.vmpfenceLastStageTime = null;
            window.vmpfenceScanCount = 0;
        }
    }
    
    /**
     * Clear all loading indicators and restore to small grey circles
     */
    function clearAllLoadingIndicators() {
        $('.vmpfence-status-item').each(function() {
            const $item = $(this);
            const scanType = $item.data('scan-type');
            
            // Note: All reputation checks are now implemented and active
            
            const $svg = $item.find('.vmpfence-status-icon svg');
            
            if ($svg.length && scanType) {
                // console.log(`VMPFence: Clearing loading for ${scanType}`);
                // Restore to small grey circle (will be updated by status system after scan)
                $svg.html(`
                    <circle cx="15" cy="15" r="8" fill="#9E9E9E"/>
                `);
            }
        });
    }
    
    /**
     * Show debug logs modal
     */
    function showDebugLogs() {
        $('#vmpfence-debug-modal').show();
        loadDebugLogs();
    }
    
    /**
     * Show Email Activity Log Modal
     */
    function showEmailDebugLogsModal() {
        const modalHtml = `
            <div id="vmpfence-email-modal" style="display: block; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 10001;">
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; width: 400px; max-width: 90%; border-radius: 8px; overflow: hidden;">
                    <div style="padding: 20px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin: 0;">Email VMP Fence Activity Log</h3>
                        <button id="vmpfence-close-email" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
                    </div>
                    <div style="padding: 20px;">
                        <p style="margin-bottom: 15px; color: #666; font-size: 14px;">
                            Enter the email address where you would like to send the VMP Fence activity log. 
                            The logs contain scan activity and diagnostic information for troubleshooting purposes.
                        </p>
                        <input type="email" id="vmpfence-email-input" placeholder="user@example.com" 
                               style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 15px; box-sizing: border-box;">
                    </div>
                    <div style="padding: 15px 20px; border-top: 1px solid #ddd; text-align: right; background: #f8f9fa;">
                        <button id="vmpfence-cancel-email" style="background: #6c757d; color: white; padding: 8px 16px; border: none; border-radius: 4px; margin-right: 10px; cursor: pointer;">Cancel</button>
                        <button id="vmpfence-send-email" style="background: #0073aa; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">Send Email</button>
                    </div>
                </div>
            </div>
        `;
        
        // Remove any existing email modal
        $('#vmpfence-email-modal').remove();
        
        // Add the modal to the page
        $('body').append(modalHtml);
        
        // Focus on email input
        $('#vmpfence-email-input').focus();
        
        // Handle close button
        $('#vmpfence-close-email, #vmpfence-cancel-email').on('click', function() {
            $('#vmpfence-email-modal').remove();
        });
        
        // Handle send button
        $('#vmpfence-send-email').on('click', function() {
            sendDebugLogsEmail();
        });
        
        // Handle enter key in email input
        $('#vmpfence-email-input').on('keypress', function(e) {
            if (e.which === 13) { // Enter key
                sendDebugLogsEmail();
            }
        });
        
        // Close modal when clicking outside
        $('#vmpfence-email-modal').on('click', function(e) {
            if (e.target === this) {
                $(this).remove();
            }
        });
    }
    
    /**
     * Send activity log via email
     */
    function sendDebugLogsEmail() {
        const email = $('#vmpfence-email-input').val().trim();
        const $sendBtn = $('#vmpfence-send-email');
        
        // Validate email
        if (!email) {
            VMPFenceNotifications.showError('Please enter an email address.', 5000);
            return;
        }
        
        if (!isValidEmail(email)) {
            VMPFenceNotifications.showError('Please enter a valid email address.', 5000);
            return;
        }
        
        // Disable send button and show loading
        $sendBtn.prop('disabled', true).text('Sending...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_email_activity_log',
                email: email,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#vmpfence-email-modal').remove();
                    VMPFenceNotifications.showSuccess(response.data.message || 'Activity log has been sent successfully to ' + email, 6000);
                } else {
                    VMPFenceNotifications.showError('Error: ' + (response.data?.message || 'Failed to send email'), 7000);
                    $sendBtn.prop('disabled', false).text('Send Email');
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error sending email. Please try again.', 6000);
                $sendBtn.prop('disabled', false).text('Send Email');
            }
        });
    }
    
    /**
     * Simple email validation
     */
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
    
    /**
     * Load debug logs from server
     */
    function loadDebugLogs() {
        $('#vmpfence-debug-content').html('<p>Loading debug logs...</p>');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_debug_logs',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    displayDebugLogs(response.data);
                } else {
                    $('#vmpfence-debug-content').html('<p style="color: #d63384;">Failed to load debug logs.</p>');
                }
            },
            error: function() {
                $('#vmpfence-debug-content').html('<p style="color: #d63384;">Error loading debug logs.</p>');
            }
        });
    }
    
    /**
     * Display debug logs in the modal
     */
    function displayDebugLogs(data) {
        let html = '';
        
        if (data.timestamp) {
            html += '<div style="background: #e3f2fd; padding: 10px; margin-bottom: 15px; border-radius: 4px;">';
            html += '<strong>Last Scan:</strong> ' + data.timestamp;
            html += '</div>';
        }
        
        // Server State Debug Log
        if (data.server_state && data.server_state.length > 0) {
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #495057;">Server State Scan Debug Log</h4>';
            
            data.server_state.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('ISSUE:')) {
                    color = '#d63384';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // File Changes Debug Log
        if (data.file_changes && data.file_changes.length > 0) {
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #856404;">File Changes Scan Debug Log</h4>';
            
            data.file_changes.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('ISSUE:') || logEntry.includes('Modified') || logEntry.includes('Unknown')) {
                    color = '#d63384';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed') || logEntry.includes('TIMEOUT')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('SKIP') || logEntry.includes('WARNING')) {
                    color = '#fd7e14';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // User Security Debug Log
        if (data.user_security && data.user_security.length > 0) {
            html += '<div style="background: #d1ecf1; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #0c5460;">User Security Analysis Debug Log</h4>';
            
            data.user_security.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('VULNERABILITY:') || logEntry.includes('ISSUE:')) {
                    color = '#d63384';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('WARNING') || logEntry.includes('Admin user')) {
                    color = '#fd7e14';
                } else if (logEntry.includes('Analyzing') || logEntry.includes('User Security')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Content Safety Debug Log
        if (data.content_safety && data.content_safety.length > 0) {
            html += '<div style="background: #f8d7da; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #721c24;">Content Safety Scan Debug Log</h4>';
            
            data.content_safety.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('VIOLATION:') || logEntry.includes('ISSUE:')) {
                    color = '#d63384';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('WARNING') || logEntry.includes('suspicious')) {
                    color = '#fd7e14';
                } else if (logEntry.includes('Content Safety') || logEntry.includes('scan complete')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Public Files Debug Log
        if (data.public_files && data.public_files.length > 0) {
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #664d03;">Public Files Scan Debug Log</h4>';
            
            data.public_files.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('VULNERABILITY:') || logEntry.includes('publicly accessible')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Testing') || logEntry.includes('OK:')) {
                    color = '#198754';
                } else if (logEntry.includes('Public Files') || logEntry.includes('scan complete')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // User Audit Debug Log
        if (data.user_audit && data.user_audit.length > 0) {
            html += '<div style="background: #e7f3ff; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #0842a0;">User & Option Audit Debug Log</h4>';
            
            data.user_audit.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('detected:') || logEntry.includes('Suspicious')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Checking') || logEntry.includes('Scanning')) {
                    color = '#198754';
                } else if (logEntry.includes('User & Option') || logEntry.includes('admin users')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Vulnerability Scan Debug Log
        if (data.vulnerability && data.vulnerability.length > 0) {
            html += '<div style="background: #fff0f0; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #8b0000;">Vulnerability Scan Debug Log</h4>';
            
            data.vulnerability.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('vulnerability found') || logEntry.includes('Suspicious') || logEntry.includes('abandoned')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Checking') || logEntry.includes('Scanning')) {
                    color = '#198754';
                } else if (logEntry.includes('TODO') || logEntry.includes('API integration')) {
                    color = '#fd7e14';
                } else if (logEntry.includes('Vulnerability') || logEntry.includes('Local-Only Mode')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Malware Scan Debug Log
        if (data.malware && data.malware.length > 0) {
            html += '<div style="background: #fff5f5; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #8b0000;">Malware Scan Debug Log</h4>';
            
            data.malware.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('malware found') || logEntry.includes('Malware') || logEntry.includes('backdoor') || logEntry.includes('injection')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Scanning') || logEntry.includes('Checking')) {
                    color = '#198754';
                } else if (logEntry.includes('TODO') || logEntry.includes('pattern')) {
                    color = '#fd7e14';
                } else if (logEntry.includes('Local-Only Mode') || logEntry.includes('patterns loaded')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Domain Blocklist Debug Log
        if (data.domain_blocklist && data.domain_blocklist.length > 0) {
            html += '<div style="background: #ffe6f0; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #8e1538;">Domain Blocklist Check Debug Log</h4>';
            
            // Filter logs to show only domain blocklist related entries
            var filteredLogs = data.domain_blocklist.filter(function(logEntry) {
                return logEntry.includes('Starting domain blocklist check') ||
                       logEntry.includes('Checking domain:') ||
                       (logEntry.includes('Private IP detected') && logEntry.includes('domain blocklist')) ||
                       logEntry.includes('Google Safe Browsing') ||
                       logEntry.includes('SURBL blocklist') ||
                       (logEntry.includes('save_scan_summary') && logEntry.includes('blocklist_check')) ||
                       logEntry.includes('Successfully saved scan summary for blocklist_check');
            });
            
            filteredLogs.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('flagged') || logEntry.includes('Google Safe Browsing flagged') || logEntry.includes('SURBL') || logEntry.includes('found in')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Checking') || logEntry.includes('clean')) {
                    color = '#198754';
                } else if (logEntry.includes('Google Safe Browsing') || logEntry.includes('domain:')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // Spamvertising Debug Log
        if (data.spamvertising && data.spamvertising.length > 0) {
            html += '<div style="background: #fff3e0; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #8a4500;">Spamvertising Check Debug Log</h4>';
            
            // Filter logs to show only spamvertising related entries
            var filteredLogs = data.spamvertising.filter(function(logEntry) {
                return logEntry.includes('Starting spamvertising check') ||
                       logEntry.includes('Checking spamvertising for domain:') ||
                       (logEntry.includes('Private IP detected') && logEntry.includes('spamvertising')) ||
                       logEntry.includes('Spamhaus DBL:') ||
                       logEntry.includes('SURBL:') ||
                       (logEntry.includes('save_scan_summary') && logEntry.includes('spamvertising_checks')) ||
                       logEntry.includes('Successfully saved scan summary for spamvertising_checks');
            });
            
            filteredLogs.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('flagged') || logEntry.includes('Spamhaus') || logEntry.includes('SURBL') || logEntry.includes('found in')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Checking') || logEntry.includes('clean')) {
                    color = '#198754';
                } else if (logEntry.includes('spamvertising') || logEntry.includes('domain:')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        // IP Spam Debug Log
        if (data.ip_spam && data.ip_spam.length > 0) {
            html += '<div style="background: #ffeaa7; padding: 15px; border-radius: 4px; margin-bottom: 10px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #6c5ce7;">IP Spam Check Debug Log</h4>';
            
            // Filter logs to show only IP spam related entries (exclude domain/spamvertising private IP messages)
            var filteredLogs = data.ip_spam.filter(function(logEntry) {
                return (logEntry.includes('Starting IP spam reputation check') ||
                       logEntry.includes('Using private IP for local development:') ||
                       logEntry.includes('Checking IP:') ||
                       (logEntry.includes('Private IP detected') && !logEntry.includes('domain blocklist') && !logEntry.includes('spamvertising')) ||
                       logEntry.includes('RBL checks skipped') ||
                       logEntry.includes('Attempting to save IP spam check summary') ||
                       (logEntry.includes('save_scan_summary') && logEntry.includes('spam_check')) ||
                       logEntry.includes('Successfully saved scan summary for spam_check') ||
                       logEntry.includes('IP spam check summary save completed') ||
                       (logEntry.includes('Spamhaus') && logEntry.includes('IP')) ||
                       (logEntry.includes('SpamCop') && logEntry.includes('IP')) ||
                       (logEntry.includes('SORBS') && logEntry.includes('IP')) ||
                       (logEntry.includes('Barracuda') && logEntry.includes('IP'))) &&
                       !logEntry.includes('domain blocklist') && !logEntry.includes('spamvertising');
            });
            
            filteredLogs.forEach(function(logEntry) {
                let color = '#333';
                if (logEntry.includes('flagged') || logEntry.includes('Spamhaus') || logEntry.includes('SpamCop') || logEntry.includes('found in')) {
                    color = '#dc3545';
                } else if (logEntry.includes('Starting') || logEntry.includes('completed')) {
                    color = '#0d6efd';
                } else if (logEntry.includes('Checking') || logEntry.includes('clean') || logEntry.includes('Private IP') || logEntry.includes('skipped')) {
                    color = '#198754';
                } else if (logEntry.includes('IP:') || logEntry.includes('RBL') || logEntry.includes('Public IP')) {
                    color = '#6f42c1';
                }
                
                html += '<div style="margin: 3px 0; color: ' + color + ';">';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
            
            html += '</div>';
        }
        
        if (!data.server_state && !data.file_changes && !data.user_security && !data.content_safety && !data.public_files && !data.user_audit && !data.vulnerability && !data.malware && !data.domain_blocklist && !data.spamvertising && !data.ip_spam) {
            html += '<p>No debug logs available. Run a scan first to see detailed debugging information.</p>';
        }
        
        $('#vmpfence-debug-content').html(html);
    }
    
    /**
     * Escape HTML for security
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Show inline debug log
     */
    function showInlineDebugLog() {
        $('#vmpfence-inline-debug-log').slideDown(300);
        $('#vmpfence-show-log-btn').text('HIDE LOG');
        loadInlineDebugLogs();
    }

    /**
     * Hide inline debug log
     */
    function hideInlineDebugLog() {
        $('#vmpfence-inline-debug-log').slideUp(300);
        $('#vmpfence-show-log-btn').text('SHOW LOG');
    }

    /**
     * Load debug logs for inline display
     */
    function loadInlineDebugLogs() {
        $('#vmpfence-inline-debug-content').html('<p>Loading debug logs...</p>');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'vmpfence_get_debug_logs',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    displayInlineDebugLogs(response.data);
                } else {
                    $('#vmpfence-inline-debug-content').html('<p style="color: #d63384;">Failed to load debug logs.</p>');
                }
            },
            error: function() {
                $('#vmpfence-inline-debug-content').html('<p style="color: #d63384;">Error loading debug logs.</p>');
            }
        });
    }

    /**
     * Display debug logs in inline format
     */
    function displayInlineDebugLogs(data) {
        let html = '';
        
        // Server State Debug Log
        if (data.server_state && data.server_state.length > 0) {
            html += '<div class="debug-log-section">Server State Scan</div>';
            data.server_state.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // File Changes Debug Log
        if (data.file_changes && data.file_changes.length > 0) {
            html += '<div class="debug-log-section">File Changes Scan</div>';
            data.file_changes.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // User Security Debug Log
        if (data.user_security && data.user_security.length > 0) {
            html += '<div class="debug-log-section">User Security Analysis</div>';
            data.user_security.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // Content Safety Debug Log
        if (data.content_safety && data.content_safety.length > 0) {
            html += '<div class="debug-log-section">Content Safety Scan</div>';
            data.content_safety.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // Public Files Debug Log
        if (data.public_files && data.public_files.length > 0) {
            html += '<div class="debug-log-section">Public Files Scan</div>';
            data.public_files.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // Malware Scan Debug Log
        if (data.malware && data.malware.length > 0) {
            html += '<div class="debug-log-section">Malware Scan</div>';
            data.malware.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // Domain Blocklist Debug Log
        if (data.domain_blocklist && data.domain_blocklist.length > 0) {
            html += '<div class="debug-log-section">Domain Blocklist Check</div>';
            
            // Filter logs to show only domain blocklist related entries
            var filteredLogs = data.domain_blocklist.filter(function(logEntry) {
                return logEntry.includes('Starting domain blocklist check') ||
                       logEntry.includes('Checking domain:') ||
                       logEntry.includes('Google Safe Browsing') ||
                       logEntry.includes('SURBL blocklist') ||
                       logEntry.includes('save_scan_summary') && logEntry.includes('blocklist_check') ||
                       logEntry.includes('Successfully saved scan summary for blocklist_check');
            });
            
            filteredLogs.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // Spamvertising Debug Log
        if (data.spamvertising && data.spamvertising.length > 0) {
            html += '<div class="debug-log-section">Spamvertising Check</div>';
            
            // Filter logs to show only spamvertising related entries
            var filteredLogs = data.spamvertising.filter(function(logEntry) {
                return logEntry.includes('Starting spamvertising check') ||
                       logEntry.includes('Checking spamvertising for domain:') ||
                       logEntry.includes('Spamhaus DBL:') ||
                       logEntry.includes('SURBL:') ||
                       logEntry.includes('save_scan_summary') && logEntry.includes('spamvertising_checks') ||
                       logEntry.includes('Successfully saved scan summary for spamvertising_checks');
            });
            
            filteredLogs.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        // IP Spam Debug Log
        if (data.ip_spam && data.ip_spam.length > 0) {
            html += '<div class="debug-log-section">IP Spam Check</div>';
            
            // Filter logs to show only IP spam related entries
            var filteredLogs = data.ip_spam.filter(function(logEntry) {
                return logEntry.includes('Starting IP spam reputation check') ||
                       logEntry.includes('Using private IP for local development:') ||
                       logEntry.includes('Checking IP:') ||
                       logEntry.includes('Private IP detected') ||
                       logEntry.includes('RBL checks skipped') ||
                       logEntry.includes('Attempting to save IP spam check summary') ||
                       logEntry.includes('save_scan_summary') && logEntry.includes('spam_check') ||
                       logEntry.includes('Successfully saved scan summary for spam_check') ||
                       logEntry.includes('IP spam check summary save completed') ||
                       (logEntry.includes('Spamhaus') && logEntry.includes('IP')) ||
                       (logEntry.includes('SpamCop') && logEntry.includes('IP')) ||
                       (logEntry.includes('SORBS') && logEntry.includes('IP')) ||
                       (logEntry.includes('Barracuda') && logEntry.includes('IP'));
            });
            
            filteredLogs.forEach(function(logEntry) {
                html += '<div class="debug-log-entry">';
                html += '<span class="debug-log-timestamp">[Aug 26 07:27:45]</span> ';
                html += escapeHtml(logEntry);
                html += '</div>';
            });
        }
        
        if (!html) {
            html = '<p>No debug logs available. Run a scan first to see detailed debugging information.</p>';
        }
        
        $('#vmpfence-inline-debug-content').html(html);
    }

    /**
     * Load existing scan results on page load
     */
    function loadExistingResults() {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_results',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {    
                if (response.success && response.data) {
                    // Store issues data globally for tab switching
                    window.vmpfenceIssuesData = response.data;
                    
                    // Update tab counts
                    updateTabCounts(response.data.active_count, response.data.ignored_count);
                    
                    // Update statistics section if scan data exists
                    if (response.data.scan_data) {
                        let scanResults = null;
                        
                        // Try different possible data structures
                        if (response.data.scan_data.scan_data) {
                            // Case 1: scan_data.scan_data (JSON decoded)
                            scanResults = response.data.scan_data.scan_data;
                        } else if (typeof response.data.scan_data === 'string') {
                            // Case 2: scan_data is JSON string
                            try {
                                scanResults = JSON.parse(response.data.scan_data);
                            } catch (e) {
                                console.error('VMPFence: Failed to parse scan_data JSON:', e);
                            }
                        } else {
                            // Case 3: scan_data is already the object
                            scanResults = response.data.scan_data;
                        }
                        
                        if (scanResults) {
                            // Check if data is under stats property
                            const statsData = scanResults.stats || scanResults;
                            
                            // Update statistics based on comprehensive statistics
                            $('.vmpfence-stats-row .vmpfence-stat-item').each(function(index) {
                                const $count = $(this).find('.vmpfence-stat-count');
                                const comprehensive_stats = response.data.comprehensive_statistics || {};
                                
                                switch (index) {
                                    case 0: // Posts, Comments, & Files
                                        // Use comprehensive statistics files_scanned + posts + comments
                                        const totalFiles = (comprehensive_stats.files_scanned || 0) + 
                                                         (comprehensive_stats.posts_scanned || 0) + 
                                                         (comprehensive_stats.comments_scanned || 0);
                                        $count.text(totalFiles);
                                        break;
                                    case 1: // Themes & Plugins
                                        // Use comprehensive statistics plugins + themes
                                        const pluginThemeCount = (comprehensive_stats.plugins_scanned || 0) + 
                                                               (comprehensive_stats.themes_scanned || 0);
                                        $count.text(pluginThemeCount);
                                        break;
                                    case 2: // Users Checked
                                        // Use comprehensive statistics users_scanned
                                        const usersChecked = comprehensive_stats.users_scanned || 0;
                                        $count.text(usersChecked);
                                        break;
                                    case 3: // URLs Checked
                                        // Use comprehensive statistics urls_scanned
                                        const urlsChecked = comprehensive_stats.urls_scanned || 0;
                                        $count.text(urlsChecked);
                                        break;
                                    case 4: // Results Found
                                        $count.text(response.data.active_count || 0);
                                        break;
                                }
                            });
                        }
                        
                        // Update timestamp if available
                        if (response.data.comprehensive_statistics.completed_time) {
                            const scanDate = new Date(response.data.comprehensive_statistics.completed_time);
                            const timestamp = '[' + scanDate.toLocaleString('en-US', {
                                month: 'short',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                                hour12: true
                            }).toUpperCase() + ']';
                            $('.vmpfence-scan-timestamp').text(timestamp);
                        }
                        
                        // Update scan message using the dynamic function with scan data
                        updateScanMessage(response.data.active_count, response.data.ignored_count, response.data);
                    }
                    
                    // Show active issues if there are any
                    if (response.data.issues && response.data.issues.length > 0) {
                        showScanIssues(response.data.issues);
                        $('.vmpfence-no-issues').hide();
                        
                        // Update repairability after loading issues
                        checkRepairability();
                    } else {
                        $('.vmpfence-no-issues').show();
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence: Failed to load existing results:', error);
                // Don't show error notification on page load as there might simply be no results
            }
        });
    }
    
    // Load existing results when page loads
    $(document).ready(function() {
        loadExistingResults();
    });

    /**
     * Generate HTML for plugin/theme updates
     */
    function generateUpdateIssueHtml(issue, isIgnored = false) {
        if (issue.type !== 'plugin_update' && issue.type !== 'theme_update') {
            return null; // Not an update issue
        }
        
        const isPlugin = issue.type === 'plugin_update';
        
        // Extract plugin/theme info from file_path (e.g., "plugin:akismet/akismet.php")
        let identifier = issue.file_path.replace(isPlugin ? 'plugin:' : 'theme:', '');
        let name = identifier;
        
        // Try to extract name from description (e.g., "Plugin 'Akismet' needs an upgrade (5.3.7 -> 5.5)")
        const descMatch = issue.description.match(/(Plugin|Theme) '([^']+)' needs an upgrade \(([^)]+) -> ([^)]+)\)/);
        if (descMatch) {
            name = descMatch[2];
            const currentVersion = descMatch[3];
            const newVersion = descMatch[4];
            
            // Generate URLs
            const slug = isPlugin ? identifier.split('/')[0] : identifier;
            const url = isPlugin ? `https://wordpress.org/plugins/${slug}/` : `https://wordpress.org/themes/${slug}/`;
            const changelogUrl = isPlugin ? `https://wordpress.org/plugins/${slug}/#developers` : `https://wordpress.org/themes/${slug}/#developers`;
            const detailsText = `You need to upgrade '${name}' to the newest version to ensure you have any security fixes the developer has released.`;
            
            return `
                <div class="vmpfence-issue-item" data-issue-id="${issue.id}">
                    <div class="vmpfence-issue-summary">
                        <div style="padding: 10px; border-left: 3px solid #FF9800;">
                            <h4>${isPlugin ? 'Plugin' : 'Theme'} Update Available</h4>
                            <p><strong>${isPlugin ? 'Plugin' : 'Theme'} Name:</strong> ${name}</p>
                            <p><strong>Current ${isPlugin ? 'Plugin' : 'Theme'} Version:</strong> ${currentVersion}</p>
                            <p><strong>New ${isPlugin ? 'Plugin' : 'Theme'} Version:</strong> ${newVersion}</p>
                            <p><strong>Details:</strong> ${detailsText} <a href="#" onclick="return false;">Click here to update now.</a></p>
                            <p><strong>${isPlugin ? 'Plugin' : 'Theme'} URL:</strong> <a href="${url}" target="_blank">${url}</a></p>
                            <p><strong>Changelog:</strong> <a href="${changelogUrl}" target="_blank">${changelogUrl}</a></p>
                            <div style="margin-top: 10px;">
                                <button class="button-primary">MARK AS FIXED</button>
                                <button class="button">VIEW UPDATES</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        return null; // Couldn't parse the description
    }

    /**
     * Override showScanIssues to use custom formatting for plugin/theme updates
     */
    const originalShowScanIssues = window.showScanIssues;
    window.showScanIssues = function(issues, isIgnored = false) {
        if (!issues || issues.length === 0) {
            if (originalShowScanIssues) {
                return originalShowScanIssues.call(this, issues, isIgnored);
            }
            return;
        }

        const $noIssues = $('.vmpfence-no-issues');
        $noIssues.hide();
        
        // Create issues display
        if ($('.vmpfence-scan-issues-list').length === 0) {
            const issuesHtml = `
                <div class="vmpfence-scan-issues-list">
                    <h4>Issues Found:</h4>
                    <div class="vmpfence-issues-container"></div>
                </div>
            `;
            $noIssues.after(issuesHtml);
        }
        
        // Update title based on tab
        $('.vmpfence-scan-issues-list h4').text(isIgnored ? 'Ignored Issues:' : 'Issues Found:');
        $('.vmpfence-scan-issues-list').show();

        const $container = $('.vmpfence-issues-container');
        $container.empty();

        // Process each issue
        issues.forEach(function(issue) {
            let issueHtml;
            
            // Check if this is a plugin/theme update
            if (issue.type === 'plugin_update' || issue.type === 'theme_update') {
                issueHtml = generateUpdateIssueHtml(issue, isIgnored);
                if (issueHtml) {
                    $container.append(issueHtml);
                    return; // Skip the rest of processing for this issue
                }
            }
            
            // For non-update issues, use original processing or simple display
            issueHtml = `
                <div class="vmpfence-issue-item" data-issue-id="${issue.id}">
                    <div class="vmpfence-issue-summary">
                        <div style="padding: 10px; border: 1px solid #ddd; margin: 5px 0;">
                            <h4>${issue.type || 'Issue'}</h4>
                            <p>${issue.description || 'No description available'}</p>
                            <small>Detected: ${issue.detected_time || 'Unknown time'}</small>
                        </div>
                    </div>
                </div>
            `;
            $container.append(issueHtml);
        });
    };
    
    /**
     * File Repair Functionality
     * Complete file repair system
     */
    
    // Initialize repair functionality
    initializeRepairFunctionality();
    
    /**
     * Initialize repair functionality
     */
    function initializeRepairFunctionality() {
        
        // Bulk repair button handler
        $(document).on('click', '.vmpfence-btn-repair', function(e) {
            e.preventDefault();
            handleBulkRepair();
        });
        
        // Individual repair button handler
        $(document).on('click', '.vmpfence-btn-repair-file', function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const $issueItem = $button.closest('.vmpfence-issue-item');
            
            const issueId = $issueItem.data('issue-id');
            
            if (!issueId) {
                console.error('VMPFence: No issue ID found');
                showNotification('Error: Issue ID not found', 'error');
                return;
            }
            
            handleSingleFileRepair(issueId);
        });
        
        // Check repairability on page load
        checkRepairability();
    }
    
    /**
     * Check repairability of all issues
     */
    function checkRepairability() {
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_check_repairability',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    updateRepairabilityUI(response.data);
                } else {
                    //console.log('VMPFence: Error checking repairability:', response.data ? response.data.message : 'Unknown error');
                }
            },
            error: function(xhr, status, error) {
                //console.log('VMPFence: AJAX error checking repairability:', error);
            }
        });
    }
    
    /**
     * Update UI based on repairability results
     */
    function updateRepairabilityUI(data) {
        const { total_issues, repairable_count, repairable_issues } = data;
        
        // Update bulk repair button
        const $bulkRepairBtn = $('.vmpfence-btn-repair');
        if (repairable_count > 0) {
            $bulkRepairBtn.prop('disabled', false).text(`REPAIR ${repairable_count} REPAIRABLE FILES`);
        } else {
            $bulkRepairBtn.prop('disabled', true).text('NO REPAIRABLE FILES');
        }
        
        // Add repair buttons to individual repairable issues
        repairable_issues.forEach(issueId => {
            const $issueItem = $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`);
            if ($issueItem.length && !$issueItem.find('.vmpfence-btn-repair-file').length) {
                const repairButton = `<button class="vmpfence-btn-repair-file" style="background: #4CAF50; color: white; padding: 5px 10px; border: none; border-radius: 3px; margin: 5px; cursor: pointer;">Repair File</button>`;
                $issueItem.find('.vmpfence-issue-summary').append(repairButton);
            }
        });
    }
    
    /**
     * Handle single file repair
     */
    function handleSingleFileRepair(issueId) {
        
        if (!issueId) {
            showNotification('Error: Issue ID not found', 'error');
            return;
        }
        
        const $issueItem = $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`);
        
        // Get file information 
        const fileName = $issueItem.find('.vmpfence-issue-description').text().match(/File: ([^\n]+)/);
        const fileDisplayName = fileName ? fileName[1] : 'Unknown file';
        
        // Create proper HTML modal dialog
        createRepairConfirmationModal(issueId, fileDisplayName, $issueItem);
    }
    
    
    // Function to create repair confirmation modal
    function createRepairConfirmationModal(issueId, fileName, $issueItem, bulkIssueIds = null) {
        // Remove existing modal if any
        $('#vmpfence-repair-modal').remove();
        
        const isBulkRepair = bulkIssueIds !== null;
        const title = isBulkRepair ? 'Bulk File Repair Confirmation' : 'File Repair Confirmation';
        const fileLabel = isBulkRepair ? 'Files:' : 'File:';
        const description = isBulkRepair 
            ? 'This will download clean files from WordPress.org and replace your current versions.'
            : 'This will download the clean file from WordPress.org and replace your current version.';
        const backupText = isBulkRepair 
            ? 'Backups will be created automatically for all files.'
            : 'A backup will be created automatically.';
        const questionText = isBulkRepair 
            ? 'Do you want to download the current files first?'
            : 'Do you want to download the current file first?';
        const noteText = isBulkRepair 
            ? 'This allows you to keep copies of the current (potentially infected) files for analysis.'
            : 'This allows you to keep a copy of the current (potentially infected) file for analysis.';
        const downloadBtnText = isBulkRepair 
            ? 'Download All First, Then Repair'
            : 'Download First, Then Repair';
        const repairBtnText = isBulkRepair 
            ? 'Repair All Directly'
            : 'Repair Directly';
        
        const modalHTML = `
            <div id="vmpfence-repair-modal" class="vmpfence-modal-overlay">
                <div class="vmpfence-modal-content">
                    <div class="vmpfence-modal-header">
                        <h3>${title}</h3>
                        <button class="vmpfence-modal-close" type="button">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-modal-file-info">
                            <strong>${fileLabel}</strong> <span class="file-name">${fileName}</span>
                        </div>
                        <div class="vmpfence-modal-description">
                            <p>${description}</p>
                            <p><strong>${backupText}</strong></p>
                        </div>
                        <div class="vmpfence-modal-question">
                            <h4>${questionText}</h4>
                            <p class="vmpfence-modal-note">${noteText}</p>
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-download-repair" type="button">
                            <i class="fas fa-download"></i> ${downloadBtnText}
                        </button>
                        <button class="vmpfence-btn vmpfence-btn-direct-repair" type="button">
                            <i class="fas fa-wrench"></i> ${repairBtnText}
                        </button>
                        <button class="vmpfence-btn vmpfence-btn-secondary vmpfence-modal-cancel" type="button">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal styles if not exists
        if (!$('#vmpfence-modal-styles').length) {
            const modalStyles = `
                <style id="vmpfence-modal-styles">
                .vmpfence-modal-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.7);
                    z-index: 999999;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .vmpfence-modal-content {
                    background: #fff;
                    border-radius: 8px;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
                    max-width: 600px;
                    width: 90%;
                    max-height: 80vh;
                    overflow-y: auto;
                }
                
                .vmpfence-modal-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 20px 30px 15px;
                    border-bottom: 1px solid #e0e0e0;
                }
                
                .vmpfence-modal-header h3 {
                    margin: 0;
                    color: #333;
                    font-size: 18px;
                }
                
                .vmpfence-modal-close {
                    background: none;
                    border: none;
                    font-size: 24px;
                    cursor: pointer;
                    color: #999;
                    padding: 0;
                    width: 30px;
                    height: 30px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .vmpfence-modal-close:hover {
                    color: #666;
                }
                
                .vmpfence-modal-body {
                    padding: 25px 30px;
                }
                
                .vmpfence-modal-file-info {
                    background: #f8f9fa;
                    padding: 15px;
                    border-radius: 5px;
                    margin-bottom: 20px;
                }
                
                .vmpfence-modal-file-info .file-name {
                    font-family: monospace;
                    background: #e9ecef;
                    padding: 2px 6px;
                    border-radius: 3px;
                }
                
                .vmpfence-modal-description p {
                    margin: 10px 0;
                    line-height: 1.5;
                }
                
                .vmpfence-modal-question {
                    margin-top: 25px;
                    padding-top: 20px;
                    border-top: 1px solid #e0e0e0;
                }
                
                .vmpfence-modal-question h4 {
                    margin: 0 0 10px 0;
                    color: #333;
                }
                
                .vmpfence-modal-note {
                    font-size: 14px;
                    color: #666;
                    font-style: italic;
                    margin: 5px 0 0 0;
                }
                
                .vmpfence-modal-footer {
                    padding: 20px 30px 25px;
                    border-top: 1px solid #e0e0e0;
                    display: flex;
                    gap: 10px;
                    flex-wrap: wrap;
                }
                
                .vmpfence-modal-footer .vmpfence-btn {
                    padding: 10px 16px;
                    border: none;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: 500;
                    display: inline-flex;
                    align-items: center;
                    gap: 6px;
                    transition: all 0.2s ease;
                }
                
                .vmpfence-btn-download-repair {
                    background: #007cba;
                    color: white;
                }
                
                .vmpfence-btn-download-repair:hover {
                    background: #005a87;
                }
                
                .vmpfence-btn-direct-repair {
                    background: #00a32a;
                    color: white;
                }
                
                .vmpfence-btn-direct-repair:hover {
                    background: #008a20;
                }
                
                .vmpfence-btn-secondary {
                    background: #f1f1f1;
                    color: #333;
                    border: 1px solid #ddd;
                }
                
                .vmpfence-btn-secondary:hover {
                    background: #e0e0e0;
                }
                </style>
            `;
            $('head').append(modalStyles);
        }
        
        // Add modal to page
        $('body').append(modalHTML);
        
        // Check if modal was added successfully
        const $modal = $('#vmpfence-repair-modal');
        
        // Force modal to be visible
        $modal.show();
        
        // Handle modal interactions
        $('#vmpfence-repair-modal').on('click', function(e) {
            if (e.target === this) {
                closeRepairModal();
            }
        });
        
        $('#vmpfence-repair-modal .vmpfence-modal-close, #vmpfence-repair-modal .vmpfence-modal-cancel').on('click', function() {
            closeRepairModal();
        });
        
        $('#vmpfence-repair-modal .vmpfence-btn-download-repair').on('click', function() {
            closeRepairModal();
            if (bulkIssueIds) {
                performBulkRepair(bulkIssueIds, true);
            } else {
                downloadAndRepair(issueId, fileName, $issueItem, true);
            }
        });
        
        $('#vmpfence-repair-modal .vmpfence-btn-direct-repair').on('click', function() {
            closeRepairModal();
            const $repairBtn = $issueItem.find('.vmpfence-btn-repair-file');
            if (bulkIssueIds) {
                performBulkRepair(bulkIssueIds, false);
            } else {
                performRepair(issueId, $issueItem, $repairBtn);
            }
        });
    }
    
    function closeRepairModal() {
        $('#vmpfence-repair-modal').fadeOut(200, function() {
            $(this).remove();
        });
    }

    function downloadAndRepair(issueId, fileName, $issueItem, shouldDownload) {
        const $repairBtn = $issueItem.find('.vmpfence-btn-repair-file');
        
        if (shouldDownload) {
            // Download current file first
            $repairBtn.prop('disabled', true).text('Downloading...');
            
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_download_file',
                    issue_id: issueId,
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    if (response.success && response.data && response.data.download_url) {
                        // Use filename from server response if available, otherwise extract from path
                        const downloadFileName = response.data.filename || extractFilename(fileName);
                        
                        // Trigger download with proper filename
                        const link = document.createElement('a');
                        link.href = response.data.download_url;
                        link.download = downloadFileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        
                        showNotification(`File "${downloadFileName}" downloaded! Starting repair...`, 'success');
                        setTimeout(() => performRepair(issueId, $issueItem, $repairBtn), 1000);
                    } else {
                        $repairBtn.prop('disabled', false).text('Repair File');
                        showNotification('Download failed. Proceeding with repair...', 'warning');
                        setTimeout(() => performRepair(issueId, $issueItem, $repairBtn), 500);
                    }
                },
                error: function() {
                    $repairBtn.prop('disabled', false).text('Repair File');
                    showNotification('Download failed. Proceeding with repair...', 'warning');
                    setTimeout(() => performRepair(issueId, $issueItem, $repairBtn), 500);
                }
            });
        } else {
            // Direct repair
            performRepair(issueId, $issueItem, $repairBtn);
        }
    }
    
    /**
     * Extract actual filename from path
     */
    function extractFilename(filePath) {
        if (!filePath) return 'unknown-file';
        
        // Remove any path separators and get just the filename
        let filename = filePath.replace(/^.*[\\\/]/, '');
        
        // If it's still a path-like string, try to extract the actual file
        if (filename.includes('/') || filename.includes('\\')) {
            const parts = filename.split(/[\\\/]/);
            filename = parts[parts.length - 1];
        }
        
        // If no extension, ensure it has one
        if (!filename.includes('.')) {
            filename += '.php';
        }
        
        return filename;
    }
    
    function performRepair(issueId, $issueItem, $repairBtn) {
        $repairBtn.prop('disabled', true).text('Repairing...');
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_repair_file',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $issueItem.fadeOut(500, function() {
                        $(this).remove();
                        updateIssueCount();
                    });
                    showNotification('File repaired successfully!', 'success');
                } else {
                    $repairBtn.prop('disabled', false).text('Repair File');
                    showNotification('Repair failed: ' + (response.data ? response.data.message : 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                $repairBtn.prop('disabled', false).text('Repair File');
                showNotification('Repair failed: Network error', 'error');
            }
        });
    }
    
    /**
     * Handle bulk repair of all repairable files
     */
    function handleBulkRepair() {
        const repairableIssueIds = [];
        
        // Collect all repairable issue IDs
        $('.vmpfence-btn-repair-file').each(function() {
            const issueId = $(this).closest('.vmpfence-issue-item').data('issue-id');
            if (issueId) {
                repairableIssueIds.push(issueId);
            }
        });
        
        if (repairableIssueIds.length === 0) {
            VMPFenceNotifications.showInfo('No repairable files found');
            return;
        }
        
        // Create bulk repair confirmation modal
        createBulkRepairConfirmationModal(repairableIssueIds);
    }
    
    /**
     * Create bulk repair confirmation modal (uses same modal as single file repair)
     */
    function createBulkRepairConfirmationModal(repairableIssueIds) {
        const fileCount = repairableIssueIds.length;
        const fileName = `${fileCount} files`;
        
        // Use the exact same modal function as single file repair
        createRepairConfirmationModal('bulk', fileName, null, repairableIssueIds);
    }
    
    /**
     * Perform bulk repair with or without download
     */
    function performBulkRepair(repairableIssueIds, shouldDownload) {
        const $bulkRepairBtn = $('.vmpfence-btn-repair');
        $bulkRepairBtn.prop('disabled', true).text('REPAIRING FILES...');
        
        //console.log(`VMPFence: Starting bulk repair for ${repairableIssueIds.length} files, download first: ${shouldDownload}`);
        
        // If download first is requested, handle downloads
        if (shouldDownload) {
            $bulkRepairBtn.text('DOWNLOADING FILES...');
            downloadAllFilesBeforeRepair(repairableIssueIds, function() {
                // After downloads complete, proceed with repair
                $bulkRepairBtn.text('REPAIRING FILES...');
                executeBulkRepair(repairableIssueIds, $bulkRepairBtn);
            });
        } else {
            // Direct repair
            executeBulkRepair(repairableIssueIds, $bulkRepairBtn);
        }
    }
    
    /**
     * Download all files before repair
     */
    function downloadAllFilesBeforeRepair(issueIds, callback) {
        let downloadCount = 0;
        const totalFiles = issueIds.length;
        
        // Process downloads one by one to avoid overwhelming the server
        function downloadNext() {
            if (downloadCount >= totalFiles) {
                showNotification(`${downloadCount} files downloaded! Starting repair...`, 'success');
                callback();
                return;
            }
            
            const issueId = issueIds[downloadCount];
            
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_download_file',
                    issue_id: issueId,
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    downloadCount++;
                    
                    if (response.success && response.data && response.data.download_url) {
                        // Use filename from server response if available
                        let downloadFileName = response.data.filename;
                        
                        // Fallback to extracting from issue item if server doesn't provide filename
                        if (!downloadFileName) {
                            const $issueItem = $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`);
                            if ($issueItem.length) {
                                const fileNameMatch = $issueItem.find('.vmpfence-issue-description').text().match(/File: ([^\n]+)/);
                                if (fileNameMatch) {
                                    downloadFileName = extractFilename(fileNameMatch[1]);
                                }
                            } else {
                                downloadFileName = 'unknown-file.php';
                            }
                        }
                        
                        // Trigger download with proper filename
                        const link = document.createElement('a');
                        link.href = response.data.download_url;
                        link.download = downloadFileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                    
                    // Continue with next download after a short delay
                    setTimeout(downloadNext, 500);
                },
                error: function() {
                    downloadCount++;
                    // Continue even if download fails
                    setTimeout(downloadNext, 500);
                }
            });
        }
        
        downloadNext();
    }
    
    /**
     * Execute the actual bulk repair
     */
    function executeBulkRepair(repairableIssueIds, $bulkRepairBtn) {
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_bulk_repair',
                issue_ids: repairableIssueIds,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                
                if (response.success && response.data) {
                    const { success_count, failure_count, results } = response.data;
                    
                    // Remove successfully repaired issues from display
                    Object.keys(results).forEach(issueId => {
                        if (results[issueId].success) {
                            $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`).fadeOut(500, function() {
                                $(this).remove();
                            });
                        }
                    });
                    
                    // Update UI after delay
                    setTimeout(() => {
                        updateIssueCount();
                        checkRepairability(); // Refresh repair status
                    }, 600);
                    
                    // Show results
                    showNotification(`Bulk repair completed: ${success_count} successful, ${failure_count} failed`, 
                                   failure_count === 0 ? 'success' : 'warning');
                    
                } else {
                    $bulkRepairBtn.prop('disabled', false).text('REPAIR ALL REPAIRABLE FILES');
                    showNotification('Bulk repair failed: ' + (response.data ? response.data.message : 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                $bulkRepairBtn.prop('disabled', false).text('REPAIR ALL REPAIRABLE FILES');
                showNotification('Bulk repair failed: Network error', 'error');
            }
        });
    }
    
    /**
     * Update issue count displays
     */
    function updateIssueCount() {
        const activeCount = $('.vmpfence-issue-item:visible').length;
        
        // Update tab counts
        $('.vmpfence-results-tabs .vmpfence-tab-active .vmpfence-tab-count').text(`(${activeCount})`);
        
        // Update stats
        $('.vmpfence-stat-item').last().find('.vmpfence-stat-count').text(activeCount);
        
        // Show/hide no issues message
        if (activeCount === 0) {
            $('.vmpfence-no-issues').show();
            $('.vmpfence-results-actions').hide();
        } else {
            $('.vmpfence-no-issues').hide();
            $('.vmpfence-results-actions').show();
        }
    }
    
    /**
     * Show notification message
     */
    function showNotification(message, type = 'info') {
        const typeClass = type === 'success' ? 'notice-success' : 
                         type === 'error' ? 'notice-error' : 
                         type === 'warning' ? 'notice-warning' : 'notice-info';
        
        const notification = $(`
            <div class="notice ${typeClass} is-dismissible" style="margin: 10px 0;">
                <p>${message}</p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `);
        
        // Insert at top of page
        $('.wrap').first().prepend(notification);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            notification.fadeOut();
        }, 5000);
        
        // Manual dismiss handler
        notification.on('click', '.notice-dismiss', function() {
            notification.fadeOut();
        });
    }

    /**
     * Handle "View Differences" button clicks for modified core files
     */
    $(document).on('click', '.vmpfence-btn-view-diff', function() {
        const $button = $(this);
        const $issueItem = $button.closest('.vmpfence-issue-item');
        const issueId = $issueItem.data('issue-id');
        
        if (!issueId) {
            VMPFenceNotifications.showError('Issue ID not found');
            return;
        }

        // Show loading state
        const originalText = $button.text();
        $button.text('Loading...').prop('disabled', true);

        // Get file differences via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_file_differences',
                issue_id: issueId,
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    showFileDifferencesModal(response.data);
                } else {
                    VMPFenceNotifications.showError('Failed to get file differences: ' + (response.data || 'Unknown error'));
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error occurred while getting file differences');
            },
            complete: function() {
                // Restore button state
                $button.text(originalText).prop('disabled', false);
            }
        });
    });

    /**
     * Show file differences modal
     */
    function showFileDifferencesModal(data) {
        const modalHTML = `
            <div id="vmpfence-diff-modal" class="vmpfence-modal-overlay">
                <div class="vmpfence-modal-content vmpfence-diff-modal">
                    <div class="vmpfence-modal-header">
                        <h3><i class="fas fa-code-branch"></i> File Differences: ${data.file_name}</h3>
                        <button class="vmpfence-modal-close" type="button">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-diff-tabs">
                            <button class="vmpfence-diff-tab active" data-tab="differences">
                                <i class="fas fa-exchange-alt"></i> Differences
                            </button>
                            <button class="vmpfence-diff-tab" data-tab="current">
                                <i class="fas fa-file-code"></i> Current File
                            </button>
                            <button class="vmpfence-diff-tab" data-tab="original">
                                <i class="fas fa-file-alt"></i> Original File
                            </button>
                        </div>
                        
                        <div class="vmpfence-diff-content">
                            <div class="vmpfence-diff-panel active" id="differences-panel">
                                <div class="vmpfence-diff-info">
                                    <p><strong>File:</strong> ${data.file_path}</p>
                                    <p><strong>Status:</strong> <span class="status-modified">Modified</span></p>
                                    <p><strong>Changes:</strong> ${data.changes_summary || 'Multiple modifications detected'}</p>
                                </div>
                                <div class="vmpfence-diff-display">
                                    ${data.formatted_diff || '<p>Difference calculation not available. Please compare the Current File and Original File tabs manually.</p>'}
                                </div>
                            </div>
                            
                            <div class="vmpfence-diff-panel" id="current-panel">
                                <div class="vmpfence-code-content">
                                    <pre><code>${escapeHtml(data.current_content || 'Current file content not available')}</code></pre>
                                </div>
                            </div>
                            
                            <div class="vmpfence-diff-panel" id="original-panel">
                                <div class="vmpfence-code-content">
                                    <pre><code>${escapeHtml(data.original_content || 'Original file content not available')}</code></pre>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-primary vmpfence-btn-copy-diff" type="button">
                            <i class="fas fa-copy"></i> Copy Differences
                        </button>
                        <button class="vmpfence-btn vmpfence-btn-secondary vmpfence-modal-close" type="button">
                            Close
                        </button>
                    </div>
                </div>
            </div>
        `;

        // Remove existing modal if any
        $('#vmpfence-diff-modal').remove();
        
        // Add modal to body
        $('body').append(modalHTML);
        
        // Show modal
        $('#vmpfence-diff-modal').fadeIn(300);
    }

    /**
     * Handle diff modal tab switching
     */
    $(document).on('click', '.vmpfence-diff-tab', function() {
        const $tab = $(this);
        const tabName = $tab.data('tab');
        
        // Update active tab
        $('.vmpfence-diff-tab').removeClass('active');
        $tab.addClass('active');
        
        // Update active panel
        $('.vmpfence-diff-panel').removeClass('active');
        $('#' + tabName + '-panel').addClass('active');
    });

    /**
     * Handle copy differences functionality
     */
    $(document).on('click', '.vmpfence-btn-copy-diff', function() {
        const $button = $(this);
        const activePanel = $('.vmpfence-diff-panel.active');
        let textToCopy = '';
        
        if (activePanel.attr('id') === 'differences-panel') {
            textToCopy = activePanel.find('.vmpfence-diff-display').text();
        } else {
            textToCopy = activePanel.find('code').text();
        }
        
        // Try to use modern clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(textToCopy).then(function() {
                const originalText = $button.text();
                $button.html('<i class="fas fa-check"></i> Copied!');
                setTimeout(() => {
                    $button.html('<i class="fas fa-copy"></i> Copy Differences');
                }, 2000);
            }).catch(function() {
                fallbackCopyToClipboard(textToCopy);
            });
        } else {
            fallbackCopyToClipboard(textToCopy);
        }
    });

    /**
     * Escape HTML for safe display
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Handle individual file delete button clicks
     */
    $(document).on('click', '.vmpfence-btn-delete, .vmpfence-btn-delete-file', function(e) {
        e.preventDefault();
        const $button = $(this);
        const $issueRow = $button.closest('.vmpfence-issue-item');
        
        const issueId = $issueRow.data('issue-id');
        
        // Try alternative methods to get issue ID
        const issueIdAttr = $issueRow.attr('data-issue-id');
        
        // Check for alternative ID attributes
        const altId = $issueRow.data('id') || $issueRow.attr('data-id');
        
        const finalIssueId = issueId || issueIdAttr || altId;
        const filePath = $issueRow.find('.vmpfence-issue-title').text().split(': ').pop() || 'Unknown file';
        
        // Show confirmation modal
        showDeleteFileModal(finalIssueId, filePath, 'single');
    });

    /**
     * Handle bulk delete all deletable files button
     */
    $(document).on('click', '#delete-all-deletable-files, .vmpfence-btn-bulk-delete', function(e) {
        e.preventDefault();
        
        // Count deletable files
        const deletableIssues = $('.vmpfence-issue-item').filter(function() {
            const $issue = $(this);
            return $issue.find('.vmpfence-btn-delete, .vmpfence-btn-delete-file').length > 0;
        });
        
        if (deletableIssues.length === 0) {
            VMPFenceNotifications.showInfo('No deletable files found.');
            return;
        }
        
        // Show confirmation modal for bulk delete
        showDeleteFileModal(null, null, 'bulk', deletableIssues.length);
    });

    /**
     * Show delete confirmation modal
     */
    function showDeleteFileModal(issueId, filePath, deleteType, fileCount = 1) {
        const isMultiple = deleteType === 'bulk';
        const title = isMultiple ? `Delete ${fileCount} Files` : 'Delete File';
        const message = isMultiple 
            ? `Are you sure you want to delete all ${fileCount} deletable files? This action cannot be undone.`
            : `Are you sure you want to delete the file:<br><strong>${escapeHtml(filePath)}</strong><br><br>This action cannot be undone.`;

        const modalHTML = `
            <div id="vmpfence-delete-modal" class="vmpfence-modal-overlay" style="display: none;">
                <div class="vmpfence-modal-content">
                    <div class="vmpfence-modal-header">
                        <h3><i class="fas fa-trash"></i> ${title}</h3>
                        <button class="vmpfence-modal-close">&times;</button>
                    </div>
                    <div class="vmpfence-modal-body">
                        <div class="vmpfence-delete-warning">
                            <i class="fas fa-exclamation-triangle" style="color: #ff6b6b; font-size: 48px; margin-bottom: 15px;"></i>
                            <p>${message}</p>
                            ${isMultiple ? '<p><strong>Warning:</strong> This will delete all suspicious files that can be safely removed.</p>' : ''}
                        </div>
                    </div>
                    <div class="vmpfence-modal-footer">
                        <button class="vmpfence-btn vmpfence-btn-secondary vmpfence-modal-close">Cancel</button>
                        <button class="vmpfence-btn vmpfence-btn-danger" id="vmpfence-confirm-delete" 
                                data-issue-id="${issueId || ''}" 
                                data-delete-type="${deleteType}">
                            <i class="fas fa-trash"></i> Delete ${isMultiple ? 'All Files' : 'File'}
                        </button>
                    </div>
                </div>
            </div>
        `;

        // Remove existing modal if any
        $('#vmpfence-delete-modal').remove();
        
        // Add modal to body
        $('body').append(modalHTML);
        
        // Show modal
        $('#vmpfence-delete-modal').fadeIn(300);
    }

    /**
     * Handle delete confirmation
     */
    $(document).on('click', '#vmpfence-confirm-delete', function() {
        const $button = $(this);
        const issueId = $button.data('issue-id');
        const deleteType = $button.data('delete-type');

        if (deleteType === 'bulk') {
            performBulkDelete();
        } else {
            performSingleDelete(issueId);
        }
        
        // Close modal
        $('#vmpfence-delete-modal').fadeOut(300, function() {
            $(this).remove();
        });
    });

    /**
     * Perform single file deletion
     */
    function performSingleDelete(issueId) {
        // Show loading state
        const $issueRow = $(`.vmpfence-issue-item[data-issue-id="${issueId}"]`);
        const $deleteButton = $issueRow.find('.vmpfence-btn-delete, .vmpfence-btn-delete-file');
        
        const originalText = $deleteButton.html();
        
        $deleteButton.html('<i class="fas fa-spinner fa-spin"></i> Deleting...').prop('disabled', true);
        
        const ajaxData = {
            action: 'vmpfence_delete_file',
            nonce: vmpfence_ajax.nonce,
            issue_id: issueId
        };
        
        // Make AJAX request to delete file
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    // Remove the issue row with animation
                    $issueRow.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update issue count
                        updateIssueCount();
                        
                        // Show success message
                        showNotification('File deleted successfully', 'success');
                    });
                } else {
                    console.error('VMPFence Delete: Error response:', response);
                    
                    // Show error message
                    showNotification('Error deleting file: ' + (response.data || 'Unknown error'), 'error');
                    
                    // Restore button
                    $deleteButton.html(originalText).prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                console.error('VMPFence Delete: AJAX error:', {xhr, status, error});
                console.error('VMPFence Delete: Response text:', xhr.responseText);
                
                // Show error message
                showNotification('Network error: Could not delete file', 'error');
                
                // Restore button
                $deleteButton.html(originalText).prop('disabled', false);
            }
        });
    }

    /**
     * Perform bulk file deletion
     */
    function performBulkDelete() {
        const $deletableIssues = $('.vmpfence-issue-item').filter(function() {
            return $(this).find('.vmpfence-btn-delete, .vmpfence-btn-delete-file').length > 0;
        });
        
        if ($deletableIssues.length === 0) {
            showNotification('No deletable files found', 'warning');
            return;
        }
        
        // Get all issue IDs
        const issueIds = [];
        $deletableIssues.each(function() {
            const $issue = $(this);
            const issueId = $issue.data('issue-id');
            const issueIdAttr = $issue.attr('data-issue-id');
            const altId = $issue.data('id') || $issue.attr('data-id');
            const finalIssueId = issueId || issueIdAttr || altId;
            
            if (finalIssueId) {
                issueIds.push(finalIssueId);
            }
        });
        
        if (issueIds.length === 0) {
            console.error('VMPFence Bulk Delete: No valid issue IDs found');
            showNotification('Error: No valid issue IDs found for deletion', 'error');
            return;
        }
        
        // Show loading state
        const $bulkButton = $('#delete-all-deletable-files');
        const originalText = $bulkButton.html();
        $bulkButton.html('<i class="fas fa-spinner fa-spin"></i> Deleting...').prop('disabled', true);
        
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_bulk_delete_files',
                nonce: vmpfence_ajax.nonce,
                issue_ids: issueIds
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.errors && response.data.errors.length > 0) {
                        // console.log('VMPFence Bulk Delete: Errors:', response.data.errors);
                    }
                    
                    // Remove all deleted issue rows with animation
                    $deletableIssues.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update issue count
                        updateIssueCount();
                        
                        // Show success message
                        const deletedCount = response.data.deleted_count || issueIds.length;
                        showNotification(`Successfully deleted ${deletedCount} files`, 'success');
                    });
                } else {
                    console.error('VMPFence Bulk Delete: Error response:', response);
                    // Show error message
                    showNotification('Error deleting files: ' + (response.data || 'Unknown error'), 'error');
                }
                
                // Restore button
                $bulkButton.html(originalText).prop('disabled', false);
            },
            error: function(xhr, status, error) {
                console.error('VMPFence Bulk Delete: AJAX error:', {xhr, status, error});
                // Show error message
                showNotification('Network error: Could not delete files', 'error');
                
                // Restore button
                $bulkButton.html(originalText).prop('disabled', false);
            }
        });
    }

    /**
     * Handle modal close events
     */
    $(document).on('click', '.vmpfence-modal-close, .vmpfence-modal-overlay', function(e) {
        if (e.target === this) {
            $('.vmpfence-modal-overlay').fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    /**
     * Update issue count after deletions
     */
    function updateIssueCount() {
        const remainingIssues = $('.vmpfence-issue-item:visible').length;
        const $countElement = $('.vmpfence-issue-count');
        if ($countElement.length) {
            $countElement.text(remainingIssues);
        }
        
        // Update the results found count if it exists
        const $resultsCount = $('.vmpfence-results-count');
        if ($resultsCount.length) {
            $resultsCount.text(remainingIssues);
        }
        
        // If no issues left, show "no issues" message
        if (remainingIssues === 0) {
            $('.vmpfence-scan-results').html(`
                <div class="vmpfence-no-issues">
                    <i class="fas fa-check-circle" style="color: #28a745; font-size: 48px; margin-bottom: 15px;"></i>
                    <h3>No Issues Found</h3>
                    <p>All security issues have been resolved.</p>
                </div>
            `);
        }
    }

    /**
     * Load and display reputation percentage
     */
    function loadReputationPercentage() {
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_reputation_percentage',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    updateReputationCard(response.data.percentage);
                } else {
                    // console.log('VMPFence: Failed to load reputation percentage');
                }
            },
            error: function(xhr, status, error) {
                console.log('VMPFence: Error loading reputation percentage:', error);
            }
        });
    }
    
    /**
     * Update the reputation check card with calculated percentage
     */
    function updateReputationCard(percentage) {
        const $reputationCard = $('.vmpfence-scan-card').eq(2); // Third card is reputation
        const $progressBar = $reputationCard.find('.vmpfence-circle-progress-bar');
        const $percentageText = $reputationCard.find('.vmpfence-circle-text');
        
        // Update percentage text
        $percentageText.text(percentage + '%');
        
        // Update progress bar
        $progressBar.attr('stroke-dasharray', percentage + ',100');
        
        // Update color based on percentage (matching dashboard and status modal logic)
        let color;
        if (percentage >= 80) {
            color = '#28a745'; // Green for excellent
        } else if (percentage >= 60) {
            color = '#17a2b8'; // Blue for good
        } else if (percentage >= 40) {
            color = '#ffc107'; // Yellow for fair
        } else {
            color = '#dc3545'; // Red for poor
        }
        
        $progressBar.attr('stroke', color);
    }

    

    
    /**
     * Load security scores (scan types and malware signatures)
     */
    function loadSecurityScores() {
        
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_security_scores',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Scan type now calculated in PHP (30% premium + 11% reputation + 59% options)
                    // Malware signatures now calculated in PHP (70% free + 30% premium)
                    updateScanTypeTitle(response.data.scan_type_name);
                    // updateMalwareStatus(response.data.malware_status);
                } else {
                    // console.log('VMPFence Scan: Failed to load security scores - invalid response');
                }
            },
            error: function(error) {
                console.log('VMPFence Scan: Error loading security scores:', error);
            }
        });
    }

    /**
     * Update security score circle
     */
    function updateSecurityScoreCircle(textElementId, progressElementId, percentage) {
        // Update text
        const textElement = document.getElementById(textElementId);
        if (textElement) {
            textElement.textContent = percentage + '%';
        }
        
        // Update circle progress
        const progressElement = document.getElementById(progressElementId);
        if (progressElement) {
            const circumference = 2 * Math.PI * 15.91549431;
            const offset = circumference - (percentage / 100) * circumference;
            progressElement.style.strokeDasharray = percentage + ',100';
            
            // Color coding
            if (percentage < 60) {
                progressElement.setAttribute('stroke', '#f44336'); // Red
            } else if (percentage < 85) {
                progressElement.setAttribute('stroke', '#ff9800'); // Orange
            } else {
                progressElement.setAttribute('stroke', '#4CAF50'); // Green
            }
        }
    }
    
    /**
     * Update scan type title
     */
    function updateScanTypeTitle(scanTypeName) {
        const titleElement = document.getElementById('scan-types-title');
        if (titleElement) {
            titleElement.textContent = 'Scan Type: ' + scanTypeName;
        }
    }

    /**
     * Update malware status description
     */
    // function updateMalwareStatus(statusDescription) {
    //     const descriptionElement = document.getElementById('malware-signatures-description');
    //     if (descriptionElement) {
    //         descriptionElement.textContent = statusDescription;
    //     }
    // }
    
    // Load security scores on page load
    loadSecurityScores();

    
    /**
     * Show notification message
     */
    function showNotification(message, type = 'info') {
        const iconMap = {
            'success': 'fa-check-circle',
            'error': 'fa-exclamation-circle',
            'warning': 'fa-exclamation-triangle',
            'info': 'fa-info-circle'
        };
        
        const icon = iconMap[type] || iconMap['info'];
        
        const notification = $(`
            <div class="vmpfence-notification vmpfence-notification-${type}">
                <i class="fas ${icon}"></i>
                <span>${message}</span>
                <button class="vmpfence-notification-close">&times;</button>
            </div>
        `);
        
        // Add to page
        if ($('.vmpfence-notifications').length === 0) {
            $('body').append('<div class="vmpfence-notifications"></div>');
        }
        
        $('.vmpfence-notifications').append(notification);
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            notification.fadeOut(300, function() {
                $(this).remove();
            });
        }, 5000);
    }
    
    /**
     * Handle notification close
     */
    $(document).on('click', '.vmpfence-notification-close', function() {
        $(this).parent().fadeOut(300, function() {
            $(this).remove();
        });
    });

});
