/**
 * HVAC jQuery Dependency Test Script
 * 
 * Comprehensive test to verify jQuery loading fixes on master trainer pages
 * Tests all problematic pages identified by the user:
 * - /master-trainer/master-dashboard/
 * - /master-trainer/announcements/ 
 * - /master-trainer/communication-templates/
 * - /master-trainer/import-export/
 */

const { chromium } = require('playwright');

async function testJQueryDependencyFixes() {
    console.log('🔧 HVAC jQuery Dependency Fixes Test Suite');
    console.log('=========================================');
    
    const browser = await chromium.launch({ 
        headless: process.env.HEADLESS !== 'false',
        slowMo: 100 
    });
    
    const context = await browser.newContext({
        // Accept self-signed certificates
        ignoreHTTPSErrors: true,
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    
    // Track console errors for jQuery issues
    const consoleErrors = [];
    const jqueryErrors = [];
    
    page.on('console', msg => {
        if (msg.type() === 'error') {
            const text = msg.text();
            consoleErrors.push(text);
            
            if (text.includes('jQuery is not defined') || 
                text.includes('$ is not defined') || 
                text.includes('jQuery') && text.includes('undefined')) {
                jqueryErrors.push(text);
                console.error(`❌ jQuery Error: ${text}`);
            }
        }
        
        if (msg.type() === 'log' && msg.text().includes('HVAC: jQuery successfully loaded')) {
            console.log(`✅ ${msg.text()}`);
        }
    });
    
    // Handle JavaScript errors
    page.on('pageerror', err => {
        const message = err.message;
        if (message.includes('jQuery') || message.includes('$')) {
            jqueryErrors.push(message);
            console.error(`❌ Page Error: ${message}`);
        }
    });
    
    const testPages = [
        {
            name: 'Master Dashboard',
            url: '/master-trainer/master-dashboard/',
            expectedElements: ['.hvac-master-dashboard', '.hvac-content'],
            requiredScripts: ['jquery', 'hvac-community-events']
        },
        {
            name: 'Master Announcements',
            url: '/master-trainer/announcements/',
            expectedElements: ['.hvac-announcements', '.hvac-content'],
            requiredScripts: ['jquery', 'hvac-announcements-admin', 'wp-util']
        },
        {
            name: 'Communication Templates',
            url: '/trainer/communication-templates/',
            expectedElements: ['.hvac-communication-templates', '.hvac-content'],
            requiredScripts: ['jquery', 'hvac-trainer-communication-templates']
        },
        {
            name: 'Import Export',
            url: '/master-trainer/import-export/',
            expectedElements: ['.hvac-import-export', '.hvac-content'],
            requiredScripts: ['jquery', 'hvac-import-export']
        }
    ];
    
    let testResults = [];
    
    for (const testPage of testPages) {
        console.log(`\n🧪 Testing: ${testPage.name}`);
        console.log(`📍 URL: ${testPage.url}`);
        
        try {
            // Clear error arrays for this test
            const pageStartErrors = jqueryErrors.length;
            
            // Navigate to the page
            const response = await page.goto(`http://localhost:8080${testPage.url}`, {
                waitUntil: 'domcontentloaded',
                timeout: 30000
            });
            
            if (!response.ok()) {
                throw new Error(`HTTP ${response.status()}: ${response.statusText()}`);
            }
            
            // Wait for page to stabilize
            await page.waitForTimeout(2000);
            
            // Check if jQuery is loaded and available
            const jqueryStatus = await page.evaluate(() => {
                return {
                    defined: typeof jQuery !== 'undefined',
                    version: typeof jQuery !== 'undefined' ? jQuery.fn.jquery : null,
                    dollarDefined: typeof $ !== 'undefined',
                    windowjQuery: typeof window.jQuery !== 'undefined'
                };
            });
            
            console.log(`   jQuery Status:`, jqueryStatus);
            
            // Check for required scripts
            const scriptStatus = await page.evaluate((requiredScripts) => {
                const scripts = Array.from(document.querySelectorAll('script[src]'));
                const loadedScripts = scripts.map(script => {
                    const src = script.src;
                    return requiredScripts.find(required => src.includes(required));
                }).filter(Boolean);
                
                return {
                    required: requiredScripts,
                    found: loadedScripts,
                    missing: requiredScripts.filter(required => !loadedScripts.includes(required))
                };
            }, testPage.requiredScripts);
            
            console.log(`   Script Status:`, scriptStatus);
            
            // Check for expected page elements
            const elementsFound = [];
            for (const selector of testPage.expectedElements) {
                try {
                    await page.waitForSelector(selector, { timeout: 5000 });
                    elementsFound.push(selector);
                } catch (e) {
                    console.warn(`   ⚠️ Element not found: ${selector}`);
                }
            }
            
            // Count jQuery errors for this page
            const pageErrors = jqueryErrors.length - pageStartErrors;
            
            const result = {
                page: testPage.name,
                url: testPage.url,
                passed: jqueryStatus.defined && jqueryStatus.dollarDefined && pageErrors === 0,
                jqueryLoaded: jqueryStatus.defined,
                jqueryVersion: jqueryStatus.version,
                elementsFound: elementsFound.length,
                elementsExpected: testPage.expectedElements.length,
                scriptsLoaded: scriptStatus.found.length,
                scriptsRequired: scriptStatus.required.length,
                jqueryErrors: pageErrors,
                warnings: []
            };
            
            if (!jqueryStatus.defined) {
                result.warnings.push('jQuery not defined');
            }
            
            if (pageErrors > 0) {
                result.warnings.push(`${pageErrors} jQuery-related errors`);
            }
            
            if (scriptStatus.missing.length > 0) {
                result.warnings.push(`Missing scripts: ${scriptStatus.missing.join(', ')}`);
            }
            
            testResults.push(result);
            
            if (result.passed) {
                console.log(`   ✅ Test PASSED`);
            } else {
                console.log(`   ❌ Test FAILED: ${result.warnings.join(', ')}`);
            }
            
        } catch (error) {
            console.error(`   💥 Test ERROR: ${error.message}`);
            testResults.push({
                page: testPage.name,
                url: testPage.url,
                passed: false,
                error: error.message,
                warnings: ['Page failed to load or crashed']
            });
        }
    }
    
    await browser.close();
    
    // Generate test report
    console.log('\n📊 TEST RESULTS SUMMARY');
    console.log('========================');
    
    const passedTests = testResults.filter(r => r.passed);
    const failedTests = testResults.filter(r => !r.passed);
    
    console.log(`✅ Passed: ${passedTests.length}/${testResults.length}`);
    console.log(`❌ Failed: ${failedTests.length}/${testResults.length}`);
    console.log(`🐛 Total jQuery Errors: ${jqueryErrors.length}`);
    
    if (failedTests.length > 0) {
        console.log('\n❌ FAILED TESTS:');
        failedTests.forEach(test => {
            console.log(`   ${test.page}: ${test.warnings?.join(', ') || test.error}`);
        });
    }
    
    if (jqueryErrors.length > 0) {
        console.log('\n🐛 JQUERY ERRORS:');
        jqueryErrors.forEach((error, index) => {
            console.log(`   ${index + 1}. ${error}`);
        });
    }
    
    console.log('\n🔧 RECOMMENDATIONS:');
    if (failedTests.length === 0 && jqueryErrors.length === 0) {
        console.log('   🎉 All tests passed! jQuery dependency fixes are working correctly.');
    } else {
        console.log('   📋 Issues found:');
        if (jqueryErrors.length > 0) {
            console.log('      - jQuery is still not loading properly on some pages');
            console.log('      - Check wp-config.php includes: define("HVAC_FORCE_LEGACY_SCRIPTS", true);');
            console.log('      - Verify WordPress jQuery is enabled');
        }
        if (failedTests.some(t => t.warnings?.includes('Missing scripts'))) {
            console.log('      - Some required scripts are not loading');
            console.log('      - Check script enqueuing in component classes');
        }
    }
    
    return {
        success: failedTests.length === 0 && jqueryErrors.length === 0,
        results: testResults,
        jqueryErrors: jqueryErrors
    };
}

if (require.main === module) {
    testJQueryDependencyFixes().catch(console.error);
}

module.exports = { testJQueryDependencyFixes };