/**
 * VMPFence Diagnostics Tool
 *
 * @package VMPFence
 * @subpackage Tools
 * @since 2.2.0
 */

(function($) {
    'use strict';

    /**
     * Diagnostics Tool Handler
     */
    const DiagnosticsTool = {
        
        /**
         * Current diagnostic results
         */
        results: null,

        /**
         * Initialize diagnostics
         */
        init: function() {
            this.bindEvents();
            // Auto-run diagnostics on page load
            this.runDiagnostics();
        },

        /**
         * Bind event handlers
         */
        bindEvents: function() {
            const self = this;

            // Export report button
            $('#vmpfence-export-diagnostics').on('click', function(e) {
                e.preventDefault();
                self.exportReport();
            });

            // Email report button
            $('#vmpfence-email-diagnostics').on('click', function(e) {
                e.preventDefault();
                self.emailReport();
            });

            // Expand all diagnostics button
            $('#vmpfence-expand-all-diagnostics').on('click', function(e) {
                e.preventDefault();
                self.expandAll();
            });
        },

        /**
         * Run diagnostic tests
         */
        runDiagnostics: function() {
            const self = this;
                        
            // Remove any existing messages
            $('.diagnostics-status-message').remove();
            $('.diagnostics-loading-bar').remove();
            

            // Show loading bar outside diagnostics-top-section
            const loadingBar = '<div class="diagnostics-loading-bar" style="margin-top: 15px; width: 100%;">' +
                '<div class="diagnostics-loading-bar-wrapper" style="background: #e0e0e0; height: 4px; border-radius: 2px; overflow: hidden; width: 100%;">' +
                    '<div class="diagnostics-loading-bar-progress" style="background: #00709e; height: 100%; width: 0; animation: diagnostics-loading 2s ease-in-out infinite;"></div>' +
                '</div>' +
                '<p style="margin: 10px 0 10px 0; color: #666; font-size: 13px;">Running diagnostics...</p>' +
            '</div>';
            
            $('.diagnostics-top-section').after(loadingBar);
            
            // Add CSS animation if not already added
            if (!$('#diagnostics-loading-animation').length) {
                $('head').append('<style id="diagnostics-loading-animation">' +
                    '@keyframes diagnostics-loading {' +
                        '0% { width: 0; }' +
                        '50% { width: 70%; }' +
                        '100% { width: 100%; }' +
                    '}' +
                '</style>');
            }

            // Make AJAX request
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_run_diagnostics',
                    nonce: vmpfenceTools.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.results = response.data.results;
                        self.renderResults(response.data.results);
                        $('.diagnostics-loading-bar').fadeOut(300, function() {
                            $(this).remove();
                        });
                    } else {
                        console.error('[VMPFence Diagnostics] Test failed:', response.data.message);
                        $('.diagnostics-loading-bar').remove();
                        self.showMessage(response.data.message || 'Failed to run diagnostics', 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[VMPFence Diagnostics] AJAX error:', status, error);
                    console.error('[VMPFence Diagnostics] XHR:', xhr);
                    $('.diagnostics-loading-bar').remove();
                    self.showMessage('Failed to run diagnostics. Please try again.', 'error');
                }
            });
        },

        /**
         * Render diagnostic results
         */
        renderResults: function(results) {
            const self = this;
            
            // Map test keys to accordion IDs
            const testMapping = {
                'vmpfence_status': 'vmpfence-status',
                'filesystem': 'filesystem-permissions',
                'config': 'config-files',
                'firewall': 'firewall-rules',
                'database': 'mysql-version',
                'php_environment': 'php-environment',
                'connectivity': 'connectivity',
                'time': 'time-synchronization',
                'ip_detection': 'ip-detection',
                'wordpress_settings': 'wordpress-settings',
                'wordpress_plugins': 'wordpress-plugins',
                'mu_plugins': 'mu-plugins',
                'dropin_plugins': 'dropin-plugins',
                'themes': 'wordpress-themes',
                'cron_jobs': 'cron-jobs',
                'database_tables': 'database-tables',
                'log_files': 'log-files'
            };

            // Update each test result
            $.each(results.tests, function(testKey, testData) {
                const accordionId = testMapping[testKey];
                if (!accordionId) return;

                const $accordion = $('#' + accordionId);
                if (!$accordion.length) return;

                // Update accordion header status icon
                self.updateAccordionStatus($accordion, testData.status);

                // Update content
                const html = self.generateTestHTML(testData, testKey);
                $accordion.find('.diagnostics-accordion-content').html(html);
            });
        },

        /**
         * Update accordion status icon
         */
        updateAccordionStatus: function($accordion, status) {
            const $title = $accordion.find('.diagnostics-accordion-title');
            const $icon = $title.find('.diagnostics-status-icon');
            const accordionId = $accordion.attr('id');

            // Remove existing status classes
            $icon.removeClass('dashicons-yes-alt dashicons-warning dashicons-info');
            
            // Reset title text color
            $title.css('color', '');

            // Add appropriate icon based on status
            if (status === 'failed') {
                $icon.addClass('dashicons-warning').css('color', '#d63638').show();
                
                // Make Database Tables accordion header text red when failed
                if (accordionId === 'database-tables') {
                    $title.css('color', '#dc3232');
                }
                
                // Make MySQL accordion header text red when failed
                if (accordionId === 'mysql-version') {
                    $title.css('color', '#dc3232');
                }
                
                // Make Filesystem accordion header text red when failed
                if (accordionId === 'filesystem-permissions') {
                    $title.css('color', '#dc3232');
                }
                
                // Make Config accordion header text red when failed
                if (accordionId === 'config-files') {
                    $title.css('color', '#dc3232');
                }
            } else if (status === 'warning') {
                $icon.addClass('dashicons-warning').css('color', '#dba617').show();
                
                // Make Connectivity accordion header text red when warning (failed tests)
                if (accordionId === 'connectivity') {
                    $title.css('color', '#dc3232');
                }
                
                // Make Filesystem accordion header text red when warning
                if (accordionId === 'filesystem-permissions') {
                    $title.css('color', '#dc3232');
                }
            } else if (status === 'passed') {
                // Hide checkmark on success, show only warnings/errors
                $icon.hide();
            }
        },

        /**
         * Generate HTML for test results
         */
        generateTestHTML: function(testData, testKey) {
            let html = '<table class="diagnostics-results-table">';

            // Add message only if not empty
            if (testData.message) {
                html += '<tr><td colspan="2"><strong>' + testData.message + '</strong></td></tr>';
            }

            // Add details
            if (testData.details && testData.details.length > 0) {
                // Special handling for Log Files section
                if (testKey === 'log_files' && testData.raw_data && testData.raw_data.log_files) {
                    const logFiles = testData.raw_data.log_files;
                    
                    if (logFiles.length > 0) {
                        // Header row
                        html += '<tr style="background: #EBEBEB;"><th style="padding: 16px; border-right: 1px solid #ccc;">File</th><th style="text-align: right; padding: 15px;">Download</th></tr>';
                        
                        $.each(logFiles, function(i, logFile) {
                            html += '<tr>';
                            html += '<td style="padding: 10px;">';
                            html += logFile.path + ' (' + logFile.size_formatted + ', ' + logFile.modified + ')';
                            html += '</td>';
                            html += '<td style="text-align: right; padding: 10px;">';
                            html += '<a href="#" class="vmpfence-download-log" data-path="' + logFile.full_path + '" style="color: #00709e; text-decoration: none;">Download</a>';
                            html += '</td>';
                            html += '</tr>';
                        });
                    } else {
                        $.each(testData.details, function(i, detail) {
                            const statusClass = 'diagnostics-status-' + detail.status;
                            html += '<tr>';
                            html += '<td>' + detail.label + '</td>';
                            html += '<td><span class="' + statusClass + '">' + detail.value + '</span></td>';
                            html += '</tr>';
                        });
                    }
                    html += '</table>';
                    return html;
                }
                // Special handling for Database Tables section
                else if (testKey === 'database_tables' && testData.raw_data && testData.raw_data.tables) {
                    const tables = testData.raw_data.tables;
                    const total = testData.raw_data.total;
                    const displayed = testData.raw_data.displayed;
                    
                    // Show summary first
                    $.each(testData.details, function(i, detail) {
                        const statusClass = 'diagnostics-status-' + detail.status;
                        const statusIcon = detail.status === 'passed' ? '✓' : 
                                         detail.status === 'failed' ? '✗' : '';
                        
                        // Special color styling for VMPFence Table Check
                        let valueHtml = detail.value;
                        let colorStyle = '';
                        if (detail.label.includes('VMPFence Table Check')) {
                            if (detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            } else if (detail.status === 'failed') {
                                colorStyle = ' style="color: #dc3232; font-weight: 600;"';
                            }
                        }
                        
                        html += '<tr>';
                        html += '<td style="width: 75%; min-width: 300px;">' + detail.label + '</td>';
                        html += '<td class="wf-right"><span class="' + statusClass + '"' + colorStyle + '>' + (statusIcon ? statusIcon + ' ' : '') + detail.value + '</span></td>';
                        html += '</tr>';
                    });
                    
                    html += '</table>';
                    html += '<div style="max-width: 100%; overflow: auto; padding: 1px; margin-top: 20px;">';
                    html += '<table class="diagnostics-results-table" style="font-size: 85%;">';
                    
                    // Table header with all columns
                    if (tables.length > 0) {
                        const preferredKeyOrder = ['Name', 'Comment', 'Engine', 'Rows', 'Avg_row_length', 'Data_length', 'Index_length', 'Auto_increment', 'Create_time', 'Row_format', 'Collation', 'Version', 'Max_data_length', 'Data_free', 'Update_time', 'Check_time', 'Checksum', 'Create_options'];
                        const firstTable = tables[0];
                        const actualKeys = Object.keys(firstTable);
                        
                        // Build display order: preferred keys first, then remaining
                        const displayKeyOrder = [];
                        preferredKeyOrder.forEach(function(key) {
                            if (actualKeys.includes(key)) {
                                displayKeyOrder.push(key);
                            }
                        });
                        actualKeys.forEach(function(key) {
                            if (!preferredKeyOrder.includes(key)) {
                                displayKeyOrder.push(key);
                            }
                        });
                        
                        // Header row
                        html += '<thead style="background: #EBEBEB;"><tr>';
                        displayKeyOrder.forEach(function(key) {
                            html += '<th style="padding: 16px; border-right: 1px solid #ccc;">' + key + '</th>';
                        });
                        html += '</tr></thead>';
                        
                        // Data rows
                        html += '<tbody>';
                        let count = 0;
                        tables.forEach(function(table) {
                            html += '<tr>';
                            displayKeyOrder.forEach(function(key) {
                                const value = table[key] !== null && table[key] !== undefined ? table[key] : '';
                                html += '<td style="padding: 16px;">' + value + '</td>';
                            });
                            html += '</tr>';
                            count++;
                            
                            if (count >= 250 && total > count) {
                                html += '<tr><td colspan=\"' + displayKeyOrder.length + '\">and ' + (total - count) + ' more</td></tr>';
                                return false; // break
                            }
                        });
                        html += '</tbody>';
                    }
                    html += '</table></div>';
                    return html;
                }
                // Special handling for IP Detection section
                else if (testKey === 'ip_detection') {
                    html += '<tr style="text-align: justify; background: #EBEBEB;"><th style="padding-left: 10px;">IPs</th><th>Value</th><th>Used</th></tr>';
                    $.each(testData.details, function(i, detail) {
                        const statusClass = 'diagnostics-status-' + detail.status;
                        const statusIcon = detail.status === 'passed' && detail.used ? '✓' : '';
                        
                        // Special color styling for "In use"
                        let usedColorStyle = '';
                        if (detail.used === 'In use') {
                            usedColorStyle = ' style="color: #46b450; font-weight: 600;"';
                        }
                        
                        html += '<tr>';
                        html += '<td style="padding-left: 10px;">' + detail.label + '</td>';
                        html += '<td><span class="' + statusClass + '">' + detail.value + '</span></td>';
                        html += '<td style="text-align: left !important;"><span class="' + statusClass + '"' + usedColorStyle + '>' + (statusIcon ? statusIcon + ' ' : '') + detail.used + '</span></td>';
                        html += '</tr>';
                    });
                } else if (testKey === 'wordpress_settings') {
                    // Special handling for WordPress Settings section - 3 column layout
                    $.each(testData.details, function(i, detail) {
                        const statusClass = 'diagnostics-status-' + detail.status;
                        
                        html += '<tr>';
                        html += '<td style="width: 30%;">' + detail.label + '</td>';
                        if (detail.description) {
                            html += '<td style="width: 30%;"><span class="' + statusClass + '">' + detail.description + '</span></td>';
                        } else {
                            html += '<td style="width: 30%;"></td>';
                        }
                        html += '<td style="width: 40%; text-align: left !important;"><span class="' + statusClass + '">' + detail.value + '</span></td>';
                        html += '</tr>';
                    });
                } else {
                    $.each(testData.details, function(i, detail) {
                        const statusClass = 'diagnostics-status-' + detail.status;
                        // Don't show status icon for time, cron_jobs, and firewall sections
                        // For connectivity, show cross (✗) for warnings/failures, not warning sign (⚠)
                        // For php_environment, only show checkmark for specific items
                        // For vmpfence_status, only show checkmark for VMPFence Version
                        let statusIcon = '';
                        if (testKey !== 'time' && testKey !== 'cron_jobs' && testKey !== 'firewall') {
                            if (testKey === 'php_environment') {
                                // Only show checkmark for these 5 specific items
                                const phpEnvCheckmarkLabels = [
                                    'PHP version >= PHP 7.0.0',
                                    'Process Owner',
                                    'Checking for OpenSSL support',
                                    'Checking OpenSSL version',
                                    'Checking for cURL support'
                                ];
                                const shouldShowCheckmark = phpEnvCheckmarkLabels.some(label => detail.label.includes(label));
                                if (detail.status === 'passed' && shouldShowCheckmark) {
                                    statusIcon = '✓';
                                } else if (detail.status === 'warning' || detail.status === 'failed') {
                                    statusIcon = '✗';
                                }
                            } else if (testKey === 'vmpfence_status') {
                                // Only show checkmark for VMPFence Version
                                if (detail.label.includes('VMPFence Version') && detail.status === 'passed') {
                                    statusIcon = '✓';
                                } else if (detail.status === 'warning' || detail.status === 'failed') {
                                    statusIcon = '✗';
                                }
                            } else if (detail.status === 'passed') {
                                statusIcon = '✓';
                            } else if (testKey === 'connectivity' && detail.status === 'warning') {
                                statusIcon = '✗'; // Cross for connectivity warnings
                            } else if (detail.status === 'warning') {
                                statusIcon = '⚠';
                            } else {
                                statusIcon = '✗';
                            }
                        }
                        
                        // Highlight directory paths with grey background
                        let label = detail.label;
                        label = label.replace(/(~\/[^\s]+)/g, '<span class="diagnostics-code-path">$1</span>');
                        
                        // Special color styling for active items (theme, plugins, mu-plugins)
                        let colorStyle = '';
                        if ((testKey === 'themes' || testKey === 'wordpress_plugins' || testKey === 'mu_plugins') && 
                            detail.value === 'Active' && detail.status === 'passed') {
                            colorStyle = ' style="color: #46b450; font-weight: 600;"';
                        }
                        
                        // Special color styling for connectivity section
                        if (testKey === 'connectivity') {
                            if (detail.value === 'OK' && detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            } else if (detail.status === 'warning' || detail.status === 'failed') {
                                colorStyle = ' style="color: #dc3232; font-weight: 600;"';
                            }
                        }
                        
                        // Special color styling for php_environment section - only for the 5 specific items
                        if (testKey === 'php_environment') {
                            const phpEnvGreenLabels = [
                                'PHP version >= PHP 7.0.0',
                                'Process Owner',
                                'Checking for OpenSSL support',
                                'Checking OpenSSL version',
                                'Checking for cURL support'
                            ];
                            const shouldBeGreen = phpEnvGreenLabels.some(label => detail.label.includes(label));
                            if (shouldBeGreen && detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            }
                        }
                        
                        // Special color styling for database (MySQL) section
                        if (testKey === 'database') {
                            if (detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            } else if (detail.status === 'failed') {
                                colorStyle = ' style="color: #dc3232; font-weight: 600;"';
                            }
                        }
                        
                        // Special color styling for filesystem section
                        if (testKey === 'filesystem') {
                            if (detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            } else if (detail.status === 'failed' || detail.status === 'warning') {
                                colorStyle = ' style="color: #dc3232; font-weight: 600;"';
                            }
                        }
                        
                        // Special color styling for config section
                        if (testKey === 'config') {
                            if (detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            } else if (detail.status === 'failed') {
                                colorStyle = ' style="color: #dc3232; font-weight: 600;"';
                            }
                        }
                        
                        // Special color styling for vmpfence_status section - only for VMPFence Version
                        if (testKey === 'vmpfence_status') {
                            if (detail.label.includes('VMPFence Version') && detail.status === 'passed') {
                                colorStyle = ' style="color: #46b450; font-weight: 600;"';
                            }
                        }
                        
                        html += '<tr>';
                        html += '<td>' + label + '</td>';
                        html += '<td><span class="' + statusClass + '"' + colorStyle + '>' + (statusIcon ? statusIcon + ' ' : '') + detail.value + '</span></td>';
                        html += '</tr>';
                    });
                }
            }

            // Add recommendations
            if (testData.recommendations && testData.recommendations.length > 0) {
                html += '<tr><td colspan="2"><strong>Recommendations:</strong></td></tr>';
                $.each(testData.recommendations, function(i, rec) {
                    html += '<tr><td colspan="2">• ' + rec + '</td></tr>';
                });
            }

            html += '</table>';
            return html;
        },

        /**
         * Export diagnostic report
         */
        exportReport: function() {
            const self = this;
            

            if (!this.results) {
                console.warn('[VMPFence Diagnostics] No results available for export');
                self.showMessage('Please run diagnostics first', 'error');
                return;
            }

            const button = $('#vmpfence-export-diagnostics');
            button.prop('disabled', true).text('Exporting...');

            try {
                // Generate text report using shared method
                const reportText = self.generateTextReport();

                // Create blob and download
                const blob = new Blob([reportText], { type: 'text/plain;charset=utf-8' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'vmp-wordpress-diagnostics-' + Date.now() + '.txt';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                self.showMessage('Diagnostic report exported successfully', 'success');
            } catch (error) {
                console.error('[VMPFence Diagnostics] Export failed:', error);
                self.showMessage('Failed to export report. Please try again.', 'error');
            } finally {
                button.prop('disabled', false).text('EXPORT');
            }
        },

        /**
         * Email diagnostic report
         */
        emailReport: function() {
            const self = this;
            

            if (!this.results) {
                console.warn('[VMPFence Diagnostics] No results available for email');
                self.showMessage('Please run diagnostics first', 'error');
                return;
            }

            // Show the email form
            $('#vmpfence-email-form').slideDown();
            
            // Scroll to the form
            $('html, body').animate({
                scrollTop: $('#vmpfence-email-form').offset().top - 100
            }, 500);
        },

        /**
         * Send diagnostic report via email
         */
        sendEmailReport: function() {
            const self = this;
            
            const email = $('#vmpfence-email-address').val().trim();
            const ticketNumber = $('#vmpfence-ticket-number').val().trim();

            if (!email) {
                self.showMessage('Please enter an email address', 'error');
                return;
            }

            // Generate the same text report as export
            const reportText = self.generateTextReport();

            const button = $('#vmpfence-send-email-btn');
            const originalText = button.text();
            button.prop('disabled', true).text('SENDING...');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_email_diagnostics',
                    nonce: vmpfenceTools.nonce,
                    email: email,
                    ticket_number: ticketNumber,
                    report_text: reportText
                },
                success: function(response) {
                    if (response.success) {
                        self.showMessage(response.data.message || 'Email sent successfully', 'success');
                        // Hide form after successful send
                        $('#vmpfence-email-form').slideUp();
                    } else {
                        self.showMessage(response.data.message || 'Failed to send email', 'error');
                    }
                },
                error: function() {
                    self.showMessage('Failed to send email. Please try again.', 'error');
                },
                complete: function() {
                    button.prop('disabled', false).text(originalText);
                }
            });
        },

        /**
         * Generate text report (same format as export)
         */
        generateTextReport: function() {
            // Helper function to create table separators
            function createTableSeparator(lengths) {
                let separator = '';
                for (let i = 0; i < lengths.length; i++) {
                    separator += '-'.repeat(lengths[i] + 2);
                    if (i < lengths.length - 1) separator += '-';
                }
                return separator + '\n';
            }

            // Helper function to pad string
            function padString(str, length) {
                return str + ' '.repeat(Math.max(0, length - str.length));
            }

            // Helper function to create table row
            function createTableRow(columns, lengths) {
                let row = '|';
                for (let i = 0; i < columns.length; i++) {
                    row += ' ' + padString(columns[i], lengths[i]) + ' |';
                }
                return row + '\n';
            }

            // Helper function to clean HTML
            function cleanHTML(value) {
                return String(value).replace(/<[^>]*>/g, '');
            }

            // Generate text report
            let reportText = '';

            // Iterate through all test results
            if (this.results.tests) {
                for (const testKey in this.results.tests) {
                    if (!this.results.tests.hasOwnProperty(testKey)) continue;

                    const testData = this.results.tests[testKey];
                    const testName = testData.name || testKey.replace(/_/g, ' ').toUpperCase();

                    // Special handling for DATABASE TABLES section
                    if (testKey === 'database_tables' && testData.raw_data && testData.raw_data.tables) {
                        const tables = testData.raw_data.tables;
                        const total = testData.raw_data.total;
                        const displayed = testData.raw_data.displayed;

                        reportText += '\n\n## ' + testName + ': Database table names, sizes, timestamps, and other metadata. ##\n\n';
                        
                        // Summary info first
                        testData.details.forEach(function(detail) {
                            if (detail.label && detail.value) {
                                reportText += detail.label + ': ' + cleanHTML(detail.value) + '\n';
                            }
                        });

                        if (tables && tables.length > 0) {
                            // Get all column keys from first table
                            const firstTable = tables[0];
                            const columns = Object.keys(firstTable);
                            
                            // Calculate column widths
                            const columnWidths = {};
                            columns.forEach(function(col) {
                                columnWidths[col] = col.length;
                                tables.forEach(function(table) {
                                    if (table[col]) {
                                        const len = String(table[col]).length;
                                        if (len > columnWidths[col]) columnWidths[col] = len;
                                    }
                                });
                            });

                            const widths = columns.map(function(col) { return columnWidths[col]; });

                            // Create table header
                            reportText += createTableSeparator(widths);
                            reportText += createTableRow(columns, widths);
                            reportText += createTableSeparator(widths);

                            // Add table data rows
                            tables.forEach(function(table, index) {
                                const row = columns.map(function(col) {
                                    return String(table[col] || '');
                                });
                                reportText += createTableRow(row, widths);
                                
                                // Show "and X more" if we hit the 250 limit
                                if (index >= 249 && total > displayed) {
                                    const remaining = total - displayed;
                                    const moreRow = columns.map(function(col, i) {
                                        return i === 0 ? 'and ' + remaining + ' more' : '';
                                    });
                                    reportText += createTableRow(moreRow, widths);
                                    return false; // break loop
                                }
                            });

                            reportText += createTableSeparator(widths);
                        }
                        
                        continue; // Skip regular rendering for this test
                    }

                    // Special handling for LOG FILES section
                    if (testKey === 'log_files' && testData.raw_data && testData.raw_data.log_files) {
                        const logFiles = testData.raw_data.log_files;

                        reportText += '\n\n## ' + testName + ': PHP error logs generated by your site, if enabled by your host. ##\n\n';

                        if (logFiles && logFiles.length > 0) {
                            // Create simple table with file paths
                            const maxWidth = 80;
                            let fileWidth = 4; // "File"
                            
                            logFiles.forEach(function(log) {
                                if (log.path && log.path.length > fileWidth) {
                                    fileWidth = Math.min(log.path.length, maxWidth);
                                }
                            });

                            const widths = [fileWidth];
                            reportText += createTableSeparator(widths);
                            reportText += createTableRow(['File'], widths);
                            reportText += createTableSeparator(widths);

                            logFiles.forEach(function(log) {
                                reportText += createTableRow([log.path || log.full_path], widths);
                            });

                            reportText += createTableSeparator(widths);
                        } else {
                            reportText += 'No log files found.\n';
                        }

                        continue; // Skip regular rendering for this test
                    }

                    // Regular rendering for other tests
                    // Calculate max widths for this table
                    let maxLabelWidth = testName.length;
                    let maxValueWidth = 25;

                    if (testData.details && testData.details.length > 0) {
                        testData.details.forEach(function(detail) {
                            if (detail.label) {
                                const labelLen = detail.label.length;
                                if (labelLen > maxLabelWidth) maxLabelWidth = labelLen;
                            }
                            if (detail.value) {
                                const valueLen = cleanHTML(detail.value).length;
                                if (valueLen > maxValueWidth) maxValueWidth = valueLen;
                            }
                        });
                    }

                    // Limit widths for readability
                    maxLabelWidth = Math.min(maxLabelWidth, 70);
                    maxValueWidth = Math.min(maxValueWidth, 80);

                    const columnWidths = [maxLabelWidth, maxValueWidth];

                    // Add section separator
                    reportText += '\n';
                    reportText += createTableSeparator(columnWidths);
                    reportText += createTableRow([testName, ''], columnWidths);
                    reportText += createTableSeparator(columnWidths);

                    // Add details as table rows
                    if (testData.details && testData.details.length > 0) {
                        testData.details.forEach(function(detail) {
                            if (detail.label && detail.value) {
                                const cleanValue = cleanHTML(detail.value);
                                
                                // Handle multi-line values
                                if (cleanValue.length > maxValueWidth) {
                                    // Split into chunks
                                    const chunks = [];
                                    for (let i = 0; i < cleanValue.length; i += maxValueWidth) {
                                        chunks.push(cleanValue.substr(i, maxValueWidth));
                                    }
                                    
                                    // First line with label
                                    reportText += createTableRow([detail.label, chunks[0] || ''], columnWidths);
                                    
                                    // Continue on next lines without label
                                    for (let j = 1; j < chunks.length; j++) {
                                        reportText += createTableRow(['', chunks[j]], columnWidths);
                                    }
                                } else {
                                    reportText += createTableRow([detail.label, cleanValue], columnWidths);
                                }
                            }
                        });
                    }

                    reportText += createTableSeparator(columnWidths);
                }
            }

            return reportText;
        },

        /**
         * Expand all diagnostics
         */
        expandAll: function() {
            $('.diagnostics-accordion-item').each(function() {
                if (!$(this).hasClass('active')) {
                    $(this).find('.diagnostics-accordion-title').click();
                }
            });
        },
        
        /**
         * Handle log file downloads
         */
        handleLogDownload: function(e) {
            e.preventDefault();
            const logPath = $(e.currentTarget).data('path');
            
            // Create a hidden form to download the file
            const form = $('<form>', {
                method: 'POST',
                action: ajaxurl,
                target: '_blank'
            });
            
            $('<input>').attr({
                type: 'hidden',
                name: 'action',
                value: 'vmpfence_download_log'
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'log_path',
                value: logPath
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'nonce',
                value: vmpfence_diagnostics.nonce
            }).appendTo(form);
            
            form.appendTo('body').submit().remove();
        },
        
        /**
         * Send test email
         */
        sendTestEmail: function(email) {
            const self = this;
            const button = $('#vmpfence-send-test-email');
            const originalText = button.text();
            
            button.prop('disabled', true).text('SENDING...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_send_test_email',
                    email: email,
                    nonce: vmpfence_diagnostics.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert('Test email sent successfully to ' + email);
                    } else {
                        alert('Failed to send test email: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function() {
                    alert('Failed to send test email. Please try again.');
                },
                complete: function() {
                    button.prop('disabled', false).text(originalText);
                }
            });
        },
        
        /**
         * Send test activity report
         */
        sendActivityReport: function(email) {
            const self = this;
            const button = $('#vmpfence-send-activity-report');
            const originalText = button.text();
            
            button.prop('disabled', true).text('SENDING...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_send_activity_report',
                    email: email,
                    nonce: vmpfence_diagnostics.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert('Test activity report sent successfully to ' + email);
                    } else {
                        alert('Failed to send activity report: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function() {
                    alert('Failed to send activity report. Please try again.');
                },
                complete: function() {
                    button.prop('disabled', false).text(originalText);
                }
            });
        },

        /**
         * Show status message
         */
        showMessage: function(message, type) {
            $('.diagnostics-status-message').remove();
            
            const cssClass = type === 'success' ? 'notice-success' : 'notice-error';
            const html = '<div class="notice ' + cssClass + ' diagnostics-status-message is-dismissible"><p>' + 
                         message + '</p></div>';
            
            $('.diagnostics-actions').before(html);

            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                $('.diagnostics-status-message').fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        if ($('#vmpfence-diagnostics-section').length > 0) {
            DiagnosticsTool.init();
            
            // Attach log download handler (delegated event for dynamically loaded content)
            $(document).on('click', '.vmpfence-download-log', DiagnosticsTool.handleLogDownload);
            
            // Attach email form handlers
            $(document).on('click', '#vmpfence-send-email-btn', function() {
                DiagnosticsTool.sendEmailReport();
            });
            
            $(document).on('click', '#vmpfence-cancel-email-btn', function() {
                $('#vmpfence-email-form').slideUp();
            });
            
            // Attach test email handlers
            $(document).on('click', '#vmpfence-send-test-email', function() {
                const email = $('#vmpfence-test-email-input').val().trim();
                if (!email) {
                    alert('Please enter an email address');
                    return;
                }
                
                DiagnosticsTool.sendTestEmail(email);
            });
            
            $(document).on('click', '#vmpfence-send-activity-report', function() {
                const email = $('#vmpfence-activity-report-email-input').val().trim();
                if (!email) {
                    alert('Please enter an email address');
                    return;
                }
                
                DiagnosticsTool.sendActivityReport(email);
            });
        }
    });

})(jQuery);
