/**
 * Test TEC Form After Fix
 * 
 * Quick test to see if TEC form is now rendering after deployment
 */

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

async function testTecFormAfterFix() {
    console.log('🧪 Testing TEC Form After Fix...');
    console.log('='.repeat(60));
    
    const browser = await chromium.launch({ 
        headless: true,
        slowMo: 500
    });
    
    try {
        const context = await browser.newContext({
            viewport: { width: 1400, height: 900 }
        });
        
        const page = await context.newPage();
        
        // Login as trainer
        console.log('📝 Logging in...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForTimeout(2000);
        
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        // Navigate to manage event page
        console.log('📝 Navigating to manage event page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.waitForTimeout(3000);
        
        // Check for TEC form elements
        const formCheck = await page.evaluate(() => {
            const checks = {
                hasTecForm: false,
                hasEventTitle: false,
                hasEventDescription: false,
                hasSubmitButton: false,
                errorMessage: '',
                formSelectors: []
            };
            
            // Check for TEC form
            const formSelectors = [
                '#tribe-community-events',
                '#tribe-community-events-form',
                '.tribe-community-events',
                'form[name="community-event"]',
                '.tribe-events-community-form'
            ];
            
            formSelectors.forEach(selector => {
                const elem = document.querySelector(selector);
                if (elem) {
                    checks.hasTecForm = true;
                    checks.formSelectors.push(selector);
                }
            });
            
            // Check for essential fields
            checks.hasEventTitle = !!document.querySelector('input[name="post_title"], #post_title, input[name="EventTitle"]');
            checks.hasEventDescription = !!document.querySelector('textarea[name="post_content"], #tcepostcontent, #post_content');
            checks.hasSubmitButton = !!document.querySelector('button[type="submit"], input[type="submit"], .tribe-button-primary');
            
            // Check for error messages
            const content = document.querySelector('.hvac-page-content');
            if (content) {
                const text = content.textContent;
                if (text.includes('Event management requires')) {
                    checks.errorMessage = 'TEC Community Events not installed';
                } else if (text.includes('permission')) {
                    checks.errorMessage = 'Permission denied';
                } else if (text.trim() === '') {
                    checks.errorMessage = 'Empty content';
                }
            }
            
            // Check if REST API script loaded
            checks.hasRestApiScript = typeof HVACRestEventSubmission !== 'undefined';
            
            return checks;
        });
        
        console.log('\n📊 TEC Form Check Results:');
        console.log('='.repeat(60));
        console.log(`✅ TEC Form Present: ${formCheck.hasTecForm ? 'YES' : 'NO'}`);
        console.log(`✅ Event Title Field: ${formCheck.hasEventTitle ? 'YES' : 'NO'}`);
        console.log(`✅ Event Description Field: ${formCheck.hasEventDescription ? 'YES' : 'NO'}`);
        console.log(`✅ Submit Button: ${formCheck.hasSubmitButton ? 'YES' : 'NO'}`);
        console.log(`✅ REST API Script: ${formCheck.hasRestApiScript ? 'YES' : 'NO'}`);
        
        if (formCheck.formSelectors.length > 0) {
            console.log(`\n📋 TEC Form Selectors Found:`);
            formCheck.formSelectors.forEach(sel => console.log(`  - ${sel}`));
        }
        
        if (formCheck.errorMessage) {
            console.log(`\n❌ Error: ${formCheck.errorMessage}`);
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/tec-form-after-fix.png',
            fullPage: true 
        });
        
        // Final verdict
        const success = formCheck.hasTecForm && formCheck.hasEventTitle && formCheck.hasEventDescription;
        
        console.log('\n' + '='.repeat(60));
        if (success) {
            console.log('🎉 SUCCESS! TEC Form is now rendering!');
            console.log('✅ Form fields are accessible');
            console.log('✅ Ready for REST API enhancement');
            
            // Test if excerpt field was added by REST API
            const hasExcerpt = await page.$('#event_excerpt');
            if (hasExcerpt) {
                console.log('✅ REST API excerpt field added!');
            } else {
                console.log('⚠️ REST API excerpt field not yet added');
            }
        } else {
            console.log('❌ TEC Form still not rendering properly');
            console.log('💡 Check if TEC Community Events is installed and active');
        }
        
        return {
            success: success,
            formCheck: formCheck
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testTecFormAfterFix()
        .then(result => {
            console.log('\n🏁 Test Complete');
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Test runner failed:', error);
            process.exit(1);
        });
}

module.exports = { testTecFormAfterFix };