/**
 * Direct TEC Form Access Test
 * 
 * Test the TEC form directly to validate enhanced template deployment
 * without login complexity
 */

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

async function testDirectTECAccess() {
    console.log('🎯 Direct TEC Form Access Test');
    console.log('==============================');
    
    const browser = await chromium.launch({ 
        headless: false,
        slowMo: 500,
        args: ['--no-sandbox', '--disable-dev-shm-usage']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    try {
        console.log('📋 Step 1: Test public access to TEC form');
        
        // Navigate directly to TEC form
        await page.goto('https://upskill-staging.measurequick.com/events/network/add');
        await page.waitForLoadState('networkidle');
        
        const currentUrl = page.url();
        console.log('📍 Current URL:', currentUrl);
        
        if (currentUrl.includes('login') || currentUrl.includes('wp-login')) {
            console.log('🔐 Login required - trying authentication...');
            
            // Handle login if redirected
            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 back to form
            await page.goto('https://upskill-staging.measurequick.com/events/network/add');
            await page.waitForLoadState('networkidle');
        }
        
        console.log('📋 Step 2: Check for enhanced template indicators');
        
        // Check for enhanced template
        const enhancedIndicator = await page.locator('.hvac-success-indicator').count();
        const enhancedForm = await page.locator('.hvac-tec-enhanced-form').count();
        const basicForm = await page.locator('#tribe-community-events').count();
        const anyForm = await page.locator('form').count();
        
        console.log('📊 Template Detection Results:');
        console.log('   Enhanced Indicator (.hvac-success-indicator):', enhancedIndicator > 0 ? '✅' : '❌');
        console.log('   Enhanced Form (.hvac-tec-enhanced-form):', enhancedForm > 0 ? '✅' : '❌');
        console.log('   Basic TEC Form (#tribe-community-events):', basicForm > 0 ? '✅' : '❌');
        console.log('   Any Form Present:', anyForm > 0 ? '✅' : '❌');
        
        if (anyForm > 0) {
            console.log('📋 Step 3: Check for field sections');
            
            // Check for field sections
            const excerptField = await page.locator('.hvac-excerpt-field, #hvac-excerpt-section').count();
            const categoriesField = await page.locator('.hvac-categories-field, #hvac-categories-section').count();
            const featuredImageField = await page.locator('.hvac-featured-image-field, #hvac-featured-image-section').count();
            const tagsField = await page.locator('.hvac-tags-field, #hvac-tags-section').count();
            
            console.log('📊 Enhanced Field Sections:');
            console.log('   Excerpt Field:', excerptField > 0 ? '✅' : '❌');
            console.log('   Categories Field:', categoriesField > 0 ? '✅' : '❌');
            console.log('   Featured Image Field:', featuredImageField > 0 ? '✅' : '❌');
            console.log('   Tags Field:', tagsField > 0 ? '✅' : '❌');
            
            const totalEnhanced = excerptField + categoriesField + featuredImageField + tagsField;
            const enhancedSuccessRate = (totalEnhanced / 4) * 100;
            
            console.log(`🎯 Enhanced Fields Success Rate: ${enhancedSuccessRate}%`);
            
            console.log('📋 Step 4: Check for standard TEC fields');
            
            // Check for standard fields
            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 venueField = await page.locator('input[name*="venue"], select[name*="venue"]').count();
            const organizerField = await page.locator('input[name*="organizer"], select[name*="organizer"]').count();
            const dateField = await page.locator('input[name*="date"], input[id*="date"]').count();
            const costField = await page.locator('input[name*="cost"], input[id*="cost"]').count();
            
            console.log('📊 Standard TEC Fields:');
            console.log('   Title Field:', titleField > 0 ? '✅' : '❌');
            console.log('   Content Field:', contentField > 0 ? '✅' : '❌');
            console.log('   Venue Field:', venueField > 0 ? '✅' : '❌');
            console.log('   Organizer Field:', organizerField > 0 ? '✅' : '❌');
            console.log('   Date Field:', dateField > 0 ? '✅' : '❌');
            console.log('   Cost Field:', costField > 0 ? '✅' : '❌');
            
            const standardFields = titleField + contentField + venueField + organizerField + dateField + costField;
            const standardSuccessRate = (standardFields / 6) * 100;
            
            console.log(`📊 Standard Fields Success Rate: ${standardSuccessRate}%`);
            
            console.log('📋 Step 5: Test a basic field population');
            
            // Try to populate the title field
            let populationTest = false;
            try {
                const titleElement = await page.locator('input[name*="title"], input[id*="title"]').first();
                if (await titleElement.count() > 0) {
                    await titleElement.fill('Enhanced Template Test Event');
                    const value = await titleElement.inputValue();
                    populationTest = value === 'Enhanced Template Test Event';
                    console.log('✅ Title field population test:', populationTest ? 'SUCCESS' : 'FAILED');
                }
            } catch (error) {
                console.log('❌ Title field population test: ERROR -', error.message);
            }
            
            // Take a screenshot
            await page.screenshot({ 
                path: 'test-results/direct-tec-form-test.png',
                fullPage: true 
            });
            console.log('📸 Screenshot saved: test-results/direct-tec-form-test.png');
            
            console.log('\n🎯 DIRECT TEC ACCESS RESULTS:');
            console.log('==============================');
            console.log('Enhanced Template Present:', enhancedIndicator > 0 ? '✅' : '❌');
            console.log('Enhanced Fields Success Rate:', enhancedSuccessRate + '%');
            console.log('Standard Fields Success Rate:', standardSuccessRate + '%');
            console.log('Basic Population Test:', populationTest ? '✅' : '❌');
            
            const overallSuccess = enhancedIndicator > 0 && standardSuccessRate >= 75;
            console.log('Overall Assessment:', overallSuccess ? '✅ SUCCESS' : '⚠️ NEEDS IMPROVEMENT');
            
            if (enhancedSuccessRate === 100) {
                console.log('\n🎉 TARGET ACHIEVED: 100% enhanced field deployment!');
            } else if (enhancedSuccessRate >= 75) {
                console.log('\n⚠️ PARTIAL SUCCESS: Most enhanced fields deployed');
            } else {
                console.log('\n❌ DEPLOYMENT ISSUE: Enhanced fields not properly rendered');
            }
            
            return {
                success: overallSuccess,
                enhancedSuccessRate,
                standardSuccessRate,
                populationTest,
                enhancedIndicator: enhancedIndicator > 0
            };
            
        } else {
            console.log('❌ CRITICAL: No forms detected on the page');
            
            // Check page content
            const pageContent = await page.content();
            const hasEvent = pageContent.includes('event') || pageContent.includes('Event');
            const hasCommunity = pageContent.includes('community') || pageContent.includes('Community');
            
            console.log('📊 Page Content Analysis:');
            console.log('   Contains "event":', hasEvent ? '✅' : '❌');
            console.log('   Contains "community":', hasCommunity ? '✅' : '❌');
            console.log('   Page size:', pageContent.length, 'characters');
            
            return {
                success: false,
                error: 'No forms detected',
                pageAnalysis: { hasEvent, hasCommunity, size: pageContent.length }
            };
        }
        
    } catch (error) {
        console.error('❌ Direct TEC access test failed:', error.message);
        
        // Take error screenshot
        await page.screenshot({ 
            path: 'test-results/direct-tec-error.png',
            fullPage: true 
        });
        
        return {
            success: false,
            error: error.message
        };
    } finally {
        await browser.close();
    }
}

// Run the test
testDirectTECAccess().then(result => {
    console.log('\n📋 FINAL ASSESSMENT:');
    console.log('===================');
    
    if (result.success) {
        console.log('✅ Enhanced TEC template deployment: SUCCESS');
        console.log('✅ Ready for 100% field population testing');
        console.log('✅ Production deployment recommended');
    } else {
        console.log('❌ Enhanced TEC template deployment: ISSUES DETECTED');
        console.log('⚠️ Further investigation required');
        if (result.error) {
            console.log('Error:', result.error);
        }
    }
});