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

async function testDirectTECAccess() {
    console.log('🎯 Testing Direct TEC Form Access After Login');
    console.log('==============================================');
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Step 1: Login first
        console.log('🔐 Step 1: Logging in...');
        await page.goto('https://upskill-staging.measurequick.com/training-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');
        console.log('✅ Login successful');
        
        // Step 2: Navigate directly to TEC form after login
        console.log('🔍 Step 2: Navigating to TEC form after login...');
        await page.goto('https://upskill-staging.measurequick.com/events/network/add');
        await page.waitForLoadState('networkidle');
        
        const currentUrl = page.url();
        console.log('📍 Final URL:', currentUrl);
        
        // Step 3: Check if we're on the right page now
        const title = await page.title();
        console.log('📋 Page Title:', title);
        
        // Step 4: Look for forms and enhanced template indicators
        const formCount = await page.locator('form').count();
        const tecForm = await page.locator('#tribe-community-events').count();
        const enhancedIndicator = await page.locator('.hvac-success-indicator').count();
        const enhancedForm = await page.locator('.hvac-tec-enhanced-form').count();
        
        console.log('📋 Form Analysis:');
        console.log('   Total Forms:', formCount);
        console.log('   TEC Community Form:', tecForm);
        console.log('   Enhanced Indicator:', enhancedIndicator);
        console.log('   Enhanced Form:', enhancedForm);
        
        // Step 5: Check for enhanced fields specifically
        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 Fields:');
        console.log('   Excerpt Field:', excerptField);
        console.log('   Categories Field:', categoriesField);
        console.log('   Featured Image Field:', featuredImageField);
        console.log('   Tags Field:', tagsField);
        
        const totalEnhancedFields = excerptField + categoriesField + featuredImageField + tagsField;
        const successRate = (totalEnhancedFields / 4) * 100;
        
        console.log('🎯 Enhanced Fields Success Rate:', successRate + '%');
        
        // Step 6: Look for standard TEC fields to verify base functionality
        const titleField = await page.locator('input[name*="EventTitle"], input[name*="title"]').count();
        const contentField = await page.locator('textarea[name*="EventContent"], textarea[name*="content"]').count();
        const dateField = await page.locator('input[name*="EventStartDate"], input[name*="date"]').count();
        
        console.log('📋 Standard TEC Fields:');
        console.log('   Title Field:', titleField);
        console.log('   Content Field:', contentField);
        console.log('   Date Field:', dateField);
        
        const baseFieldsWorking = titleField > 0 && contentField > 0;
        
        // Step 7: Check page content for template indicators
        const pageContent = await page.content();
        const hasTemplateComments = pageContent.includes('HVAC Enhanced') || pageContent.includes('Enhanced Template');
        const hasPartialIncludes = pageContent.includes('excerpt-field.php') || pageContent.includes('categories-field.php');
        
        console.log('📋 Template Analysis:');
        console.log('   Template Comments:', hasTemplateComments ? '✅' : '❌');
        console.log('   Partial Includes:', hasPartialIncludes ? '✅' : '❌');
        
        // Step 8: Final assessment
        console.log('\n🎯 ASSESSMENT RESULTS:');
        console.log('======================');
        
        if (currentUrl.includes('/events/network/add')) {
            console.log('✅ Successfully accessing TEC Community Events form');
            
            if (totalEnhancedFields === 4) {
                console.log('🎉 SUCCESS: 100% enhanced field population achieved!');
                console.log('✅ All enhanced template sections rendering correctly');
                return { success: true, successRate: 100 };
            } else if (totalEnhancedFields > 0) {
                console.log('⚠️ PARTIAL: Enhanced template partially deployed');
                console.log(`📊 ${totalEnhancedFields}/4 enhanced fields detected`);
                return { success: false, successRate: successRate, partialDeployment: true };
            } else if (baseFieldsWorking) {
                console.log('📋 Base TEC form working, but enhanced template not loading');
                console.log('🔧 Enhanced template deployed but not being used by WordPress');
                return { success: false, successRate: 0, baseWorking: true };
            } else {
                console.log('❌ No functional form detected');
                return { success: false, successRate: 0, baseWorking: false };
            }
        } else {
            console.log('❌ Redirected away from TEC form URL');
            console.log('🔧 Access permissions or configuration issue');
            return { success: false, successRate: 0, redirected: true, finalUrl: currentUrl };
        }
        
    } catch (error) {
        console.error('❌ Test failed:', error.message);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

testDirectTECAccess().then(result => {
    console.log('\n🏁 FINAL VALIDATION SUMMARY:');
    console.log('============================');
    console.log('Overall Success:', result.success ? '✅' : '❌');
    console.log('Success Rate:', result.successRate + '%');
    
    if (result.success) {
        console.log('\n🎉 DEPLOYMENT COMPLETE AND VALIDATED!');
        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 STATUS:');
        if (result.partialDeployment) {
            console.log('⚠️ Enhanced template partially working');
            console.log('🔍 Some enhanced fields rendering correctly');
        } else if (result.baseWorking) {
            console.log('📋 Base TEC form functional');
            console.log('🔧 Enhanced template needs activation/configuration');
        } else if (result.redirected) {
            console.log('🔄 Access control issue - users being redirected');
            console.log('🔍 Check TEC Community Events permissions');
        } else {
            console.log('❌ Fundamental deployment issues detected');
        }
    }
});