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

async function validateTECDeployment() {
    console.log('🎯 TEC Enhanced Template Deployment Validation');
    console.log('===============================================');
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Navigate directly to the TEC Community Events form without login first
        console.log('🔍 Step 1: Testing public access to TEC form...');
        await page.goto('https://upskill-staging.measurequick.com/events/network/add');
        await page.waitForLoadState('networkidle');
        
        // Check for login redirect or form presence
        const currentUrl = page.url();
        console.log('📍 Current URL after navigation:', currentUrl);
        
        if (currentUrl.includes('login') || currentUrl.includes('wp-login')) {
            console.log('🔐 Login required - proceeding with authentication...');
            
            // If redirected to login, handle login
            await page.fill('input[name="log"]', 'test_trainer');
            await page.fill('input[name="pwd"]', 'TestTrainer123!');
            await page.click('input[type="submit"]');
            await page.waitForLoadState('networkidle');
            
            // Navigate to form again after login
            await page.goto('https://upskill-staging.measurequick.com/events/network/add');
            await page.waitForLoadState('networkidle');
        }
        
        console.log('🔍 Step 2: Validating enhanced template deployment...');
        
        // Check for enhanced template indicators
        const enhancedIndicators = await page.locator('.hvac-success-indicator').count();
        const enhancedForm = await page.locator('.hvac-tec-enhanced-form').count();
        
        console.log('📋 Enhanced Template Indicators:');
        console.log('   Success Indicator:', enhancedIndicators > 0 ? '✅' : '❌');
        console.log('   Enhanced Form:', enhancedForm > 0 ? '✅' : '❌');
        
        // Check for basic TEC form
        const basicForm = await page.locator('#tribe-community-events').count();
        const eventForm = await page.locator('form[id*="event"]').count();
        const anyForm = await page.locator('form').count();
        
        console.log('📋 Form Presence:');
        console.log('   TEC Community Form (#tribe-community-events):', basicForm > 0 ? '✅' : '❌');
        console.log('   Event Form (any):', eventForm > 0 ? '✅' : '❌');
        console.log('   Any Form:', anyForm > 0 ? '✅' : '❌');
        
        if (anyForm > 0) {
            console.log('🔍 Step 3: Checking for enhanced field sections...');
            
            // Check for our specific enhanced fields from the partials
            const excerptField = await page.locator('.hvac-excerpt-field').count();
            const categoriesField = await page.locator('.hvac-categories-field').count(); 
            const featuredImageField = await page.locator('.hvac-featured-image-field').count();
            const tagsField = await page.locator('.hvac-tags-field').count();
            
            console.log('📋 Enhanced Field Sections:');
            console.log('   Excerpt Field (.hvac-excerpt-field):', excerptField > 0 ? '✅' : '❌');
            console.log('   Categories Field (.hvac-categories-field):', categoriesField > 0 ? '✅' : '❌');
            console.log('   Featured Image Field (.hvac-featured-image-field):', featuredImageField > 0 ? '✅' : '❌');
            console.log('   Tags Field (.hvac-tags-field):', tagsField > 0 ? '✅' : '❌');
            
            const totalFields = excerptField + categoriesField + featuredImageField + tagsField;
            const successRate = (totalFields / 4) * 100;
            
            console.log('🎯 Enhanced Fields Success Rate:', `${successRate}%`);
            
            if (successRate === 100) {
                console.log('🎉 SUCCESS: 100% field population validation achieved!');
                console.log('✅ All enhanced template sections deployed and rendering correctly');
            } else if (successRate >= 75) {
                console.log('⚠️ PARTIAL SUCCESS: Enhanced template deployed but some fields missing');
            } else {
                console.log('❌ DEPLOYMENT ISSUE: Enhanced fields not rendering properly');
            }
            
            // Additional checks for template integration
            console.log('🔍 Step 4: Additional template validation...');
            
            // Check for standard TEC fields to ensure base functionality
            const titleField = await page.locator('input[name*="title"], input[id*="title"]').count();
            const contentField = await page.locator('textarea[name*="content"], textarea[id*="content"]').count();
            const dateField = await page.locator('input[name*="date"], input[id*="date"]').count();
            
            console.log('📋 Standard TEC Fields:');
            console.log('   Title Field:', titleField > 0 ? '✅' : '❌');
            console.log('   Content Field:', contentField > 0 ? '✅' : '❌');
            console.log('   Date Field:', dateField > 0 ? '✅' : '❌');
            
            const baseFieldsWorking = titleField > 0 && contentField > 0;
            console.log('🔧 Base Template Integration:', baseFieldsWorking ? '✅' : '❌');
            
            return {
                success: successRate === 100,
                successRate: successRate,
                enhancedFields: totalFields,
                baseFieldsWorking: baseFieldsWorking,
                templateDeployed: basicForm > 0 || eventForm > 0
            };
            
        } else {
            console.log('❌ CRITICAL: No forms found on the page');
            
            // Check if we're on the right page
            const pageContent = await page.content();
            const hasEvents = pageContent.includes('event') || pageContent.includes('Event');
            const hasCommunity = pageContent.includes('community') || pageContent.includes('Community');
            
            console.log('📋 Page Content Analysis:');
            console.log('   Contains "event/Event":', hasEvents ? '✅' : '❌');
            console.log('   Contains "community/Community":', hasCommunity ? '✅' : '❌');
            console.log('   Page length:', pageContent.length, 'characters');
            
            return {
                success: false,
                successRate: 0,
                enhancedFields: 0,
                baseFieldsWorking: false,
                templateDeployed: false,
                pageAnalysis: { hasEvents, hasCommunity, contentLength: pageContent.length }
            };
        }
        
    } catch (error) {
        console.error('❌ Validation failed:', error.message);
        return {
            success: false,
            error: error.message
        };
    } finally {
        await browser.close();
    }
}

// Run the validation
validateTECDeployment().then(result => {
    console.log('\n🎯 FINAL VALIDATION RESULTS:');
    console.log('==============================');
    console.log('Success:', result.success ? '✅' : '❌');
    console.log('Success Rate:', result.successRate + '%');
    console.log('Enhanced Fields:', result.enhancedFields + '/4');
    console.log('Base Template Working:', result.baseFieldsWorking ? '✅' : '❌');
    console.log('Template Deployed:', result.templateDeployed ? '✅' : '❌');
    
    if (result.success) {
        console.log('\n🎉 DEPLOYMENT VALIDATION COMPLETE!');
        console.log('✅ Enhanced TEC template fully functional');
        console.log('✅ 100% field population success rate achieved');
        console.log('✅ Ready for production deployment');
    } else {
        console.log('\n⚠️ DEPLOYMENT VALIDATION ISSUES DETECTED');
        console.log('❌ Further investigation required');
        if (result.error) {
            console.log('Error:', result.error);
        }
    }
});