/**
 * JavaScript Selector Syntax Fixes Validation Test
 * 
 * Tests the fixed selectors to ensure they work properly and 
 * validates the enhanced field population system improvements.
 * 
 * @version 1.0.0
 * @since August 12, 2025
 */

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

async function testJavaScriptSelectorFixes() {
    console.log('🧪 Testing JavaScript Selector Syntax Fixes...');
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Navigate to a page that loads our JavaScript files
        console.log('📄 Navigating to event creation page...');
        await page.goto('https://upskill-staging.measurequick.com/community/add-event/', {
            waitUntil: 'networkidle'
        });
        
        // Wait for JavaScript files to load
        await page.waitForTimeout(3000);
        
        console.log('🔍 Testing CSS selector syntax validation...');
        
        // Test 1: Validate all selectors compile without syntax errors
        const selectorValidationResults = await page.evaluate(() => {
            const results = {
                validSelectors: 0,
                invalidSelectors: 0,
                errors: []
            };
            
            // Test the fixed selectors
            const testSelectors = [
                // Fixed category selectors
                'input[name="tax_input\\[tribe_events_cat\\]\\[\\]"][type="checkbox"]',
                'select[name="tax_input\\[tribe_events_cat\\]\\[\\]"]',
                'select[name="tax_input\\[tribe_events_cat\\]"]',
                
                // Fixed tag selectors
                'input[name="tax_input\\[post_tag\\]"]',
                'input[name="tax_input\\[post_tag\\]\\[\\]"]',
                'select[name="tax_input\\[post_tag\\]\\[\\]"]',
                'input[name="newtag\\[post_tag\\]"]',
                
                // Additional TEC selectors
                'input[type="checkbox"][name*="tribe_events_cat"]',
                'input[type="checkbox"][name*="post_tag"]'
            ];
            
            testSelectors.forEach(selector => {
                try {
                    // Test if selector compiles without throwing an error
                    document.querySelector(selector);
                    results.validSelectors++;
                } catch (error) {
                    results.invalidSelectors++;
                    results.errors.push({
                        selector: selector,
                        error: error.message
                    });
                }
            });
            
            return results;
        });
        
        console.log('📊 Selector Validation Results:');
        console.log(`✅ Valid selectors: ${selectorValidationResults.validSelectors}`);
        console.log(`❌ Invalid selectors: ${selectorValidationResults.invalidSelectors}`);
        
        if (selectorValidationResults.errors.length > 0) {
            console.log('🚨 Selector Errors:');
            selectorValidationResults.errors.forEach(error => {
                console.log(`   - ${error.selector}: ${error.error}`);
            });
        }
        
        // Test 2: Check if enhanced field population system is loaded
        console.log('🔧 Testing enhanced field population system...');
        
        const systemLoadResults = await page.evaluate(() => {
            return {
                enhancedSystemLoaded: typeof window.HVACEnhancedFieldPopulation !== 'undefined',
                testFieldAccessAvailable: typeof window.HVACEnhancedFieldPopulation?.testFieldAccess === 'function',
                populateAllFieldsAvailable: typeof window.HVACEnhancedFieldPopulation?.populateAllFields === 'function',
                globalFunctionAvailable: typeof window.hvacEnhancedPopulateFields === 'function'
            };
        });
        
        console.log('📋 System Load Results:', systemLoadResults);
        
        // Test 3: Run field access test if available
        if (systemLoadResults.testFieldAccessAvailable) {
            console.log('🎯 Running field access test...');
            
            const fieldAccessResults = await page.evaluate(() => {
                return window.HVACEnhancedFieldPopulation.testFieldAccess();
            });
            
            console.log('📈 Field Access Results:');
            console.log(`   - Success: ${fieldAccessResults.success}`);
            console.log(`   - Access Rate: ${fieldAccessResults.access_rate}%`);
            console.log(`   - Found Fields: ${fieldAccessResults.found_fields}/${fieldAccessResults.total_fields}`);
            
            if (fieldAccessResults.missing_fields?.length > 0) {
                console.log('❌ Missing Fields:');
                fieldAccessResults.missing_fields.forEach(field => {
                    console.log(`   - ${field.field}:`);
                    console.log(`     Attempted: ${field.attempted_selectors.join(', ')}`);
                    if (field.errors.length > 0) {
                        console.log(`     Errors: ${field.errors.join(', ')}`);
                    }
                });
            }
        }
        
        // Test 4: Test category field detection specifically
        console.log('🏷️ Testing category field detection...');
        
        const categoryFieldTest = await page.evaluate(() => {
            const categorySelectors = [
                'input[name="tax_input\\[tribe_events_cat\\]\\[\\]"][type="checkbox"]',
                'select[name="tax_input\\[tribe_events_cat\\]\\[\\]"]',
                'select[name="tax_input\\[tribe_events_cat\\]"]',
                'input[type="checkbox"][name*="tribe_events_cat"]'
            ];
            
            const results = {
                foundElements: 0,
                totalSelectors: categorySelectors.length,
                foundSelectors: []
            };
            
            categorySelectors.forEach(selector => {
                try {
                    const elements = document.querySelectorAll(selector);
                    if (elements.length > 0) {
                        results.foundElements += elements.length;
                        results.foundSelectors.push({
                            selector: selector,
                            count: elements.length
                        });
                    }
                } catch (error) {
                    // Selector error already logged above
                }
            });
            
            return results;
        });
        
        console.log('🏷️ Category Field Detection:');
        console.log(`   - Found ${categoryFieldTest.foundElements} category elements`);
        console.log(`   - Using ${categoryFieldTest.foundSelectors.length}/${categoryFieldTest.totalSelectors} selectors`);
        categoryFieldTest.foundSelectors.forEach(result => {
            console.log(`     ✅ ${result.selector}: ${result.count} elements`);
        });
        
        // Test 5: Check for JavaScript console errors
        console.log('🚨 Checking for JavaScript console errors...');
        
        const consoleErrors = [];
        page.on('console', msg => {
            if (msg.type() === 'error') {
                consoleErrors.push(msg.text());
            }
        });
        
        // Trigger some JavaScript activity
        await page.evaluate(() => {
            // Try to access the enhanced field population system
            if (window.HVACEnhancedFieldPopulation) {
                window.HVACEnhancedFieldPopulation.testFieldAccess();
            }
        });
        
        await page.waitForTimeout(2000);
        
        console.log(`📊 Console Errors: ${consoleErrors.length}`);
        if (consoleErrors.length > 0) {
            console.log('🚨 JavaScript Errors Found:');
            consoleErrors.forEach((error, index) => {
                console.log(`   ${index + 1}. ${error}`);
            });
        }
        
        // Final Summary
        console.log('\n🎯 JavaScript Selector Fixes Validation Summary:');
        console.log('=' .repeat(60));
        
        const allTestsPassed = 
            selectorValidationResults.invalidSelectors === 0 &&
            systemLoadResults.enhancedSystemLoaded &&
            consoleErrors.length === 0;
        
        if (allTestsPassed) {
            console.log('✅ ALL TESTS PASSED - Selector fixes are working correctly!');
            console.log('✅ No syntax errors in CSS selectors');
            console.log('✅ Enhanced field population system loaded successfully');
            console.log('✅ No JavaScript console errors detected');
        } else {
            console.log('❌ SOME TESTS FAILED - Issues detected:');
            if (selectorValidationResults.invalidSelectors > 0) {
                console.log(`❌ ${selectorValidationResults.invalidSelectors} invalid selectors found`);
            }
            if (!systemLoadResults.enhancedSystemLoaded) {
                console.log('❌ Enhanced field population system not loaded');
            }
            if (consoleErrors.length > 0) {
                console.log(`❌ ${consoleErrors.length} JavaScript console errors detected`);
            }
        }
        
        console.log('=' .repeat(60));
        
        return {
            success: allTestsPassed,
            selectorValidation: selectorValidationResults,
            systemLoad: systemLoadResults,
            categoryFieldDetection: categoryFieldTest,
            jsErrors: consoleErrors.length
        };
        
    } catch (error) {
        console.error('🚨 Test execution error:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testJavaScriptSelectorFixes()
        .then(results => {
            console.log('\n📋 Final Test Results:', JSON.stringify(results, null, 2));
            process.exit(results.success ? 0 : 1);
        })
        .catch(error => {
            console.error('🚨 Test failed:', error);
            process.exit(1);
        });
}

module.exports = { testJavaScriptSelectorFixes };