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

/**
 * Test Create Event Page After Fix
 * 
 * This script verifies that the create-event page now works properly
 * after running the create-event-pages.sh script.
 */

const BASE_URL = 'https://upskill-staging.measurequick.com';
const CREATE_EVENT_URL = `${BASE_URL}/trainer/create-event/`;
const TEST_CREDENTIALS = {
    username: 'test_trainer',
    password: 'TestTrainer123!'
};

// ANSI color codes for terminal output
const colors = {
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m',
    reset: '\x1b[0m',
    bold: '\x1b[1m'
};

function log(message, color = 'reset') {
    console.log(`${colors[color]}${message}${colors.reset}`);
}

function logSection(title) {
    log('\n' + '='.repeat(60), 'cyan');
    log(`  ${title}`, 'bold');
    log('='.repeat(60), 'cyan');
}

function logSuccess(message) {
    log(`✅ ${message}`, 'green');
}

function logError(message) {
    log(`❌ ${message}`, 'red');
}

function logWarning(message) {
    log(`⚠️  ${message}`, 'yellow');
}

async function testCreateEventPage() {
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();

    // Capture console logs related to our functionality
    page.on('console', msg => {
        if (msg.text().includes('Create Event') || msg.text().includes('HVAC') || msg.text().includes('REST API') || msg.text().includes('TEC')) {
            log(`🖥️  CONSOLE: ${msg.text()}`, 'cyan');
        }
    });

    try {
        logSection('TESTING CREATE EVENT PAGE AFTER FIX');

        // Step 1: Authenticate
        log('\n1. Authenticating as test trainer', 'blue');
        await page.goto(`${BASE_URL}/trainer/login/`);
        await page.fill('#user_login', TEST_CREDENTIALS.username);
        await page.fill('#user_pass', TEST_CREDENTIALS.password);
        await page.click('#wp-submit');
        await page.waitForTimeout(2000);
        logSuccess('Authentication completed');

        // Step 2: Test create-event page access
        log('\n2. Testing create-event page access', 'blue');
        const response = await page.goto(CREATE_EVENT_URL, { waitUntil: 'networkidle' });
        log(`Response Status: ${response.status()}`);
        
        if (response.status() === 200) {
            logSuccess('Page loads successfully (200 OK)');
        } else {
            logError(`Page failed to load: ${response.status()}`);
            await page.screenshot({ path: './test-results/create-event-failed.png', fullPage: true });
            return;
        }

        // Step 3: Check page structure
        log('\n3. Verifying page structure', 'blue');
        
        const pageTitle = await page.title();
        log(`Page Title: ${pageTitle}`);
        
        const hasHVACWrapper = await page.locator('.hvac-create-event-wrapper').count() > 0;
        log(`HVAC wrapper present: ${hasHVACWrapper}`);
        
        const hasNavigation = await page.locator('.hvac-trainer-nav').count() > 0;
        log(`HVAC navigation present: ${hasNavigation}`);
        
        const hasCreateEventTitle = await page.locator('h1:has-text("Create New Event")').count() > 0;
        log(`Create Event title present: ${hasCreateEventTitle}`);

        // Step 4: Check for TEC form
        log('\n4. Checking The Events Calendar form', 'blue');
        
        const hasTECContainer = await page.locator('#tribe-community-events').count() > 0;
        log(`TEC container present: ${hasTECContainer}`);
        
        const hasTECForm = await page.locator('form[id*="tribe"]').count() > 0;
        log(`TEC form present: ${hasTECForm}`);
        
        const hasFormFields = await page.locator('input[name*="EventTitle"], input[name*="EventStartDate"]').count() > 0;
        log(`Form fields present: ${hasFormFields}`);

        // Step 5: Check REST API enhancement
        log('\n5. Checking REST API enhancement', 'blue');
        
        const restApiScriptLoaded = await page.evaluate(() => {
            return typeof HVACRestEventSubmission !== 'undefined';
        });
        log(`REST API script loaded: ${restApiScriptLoaded}`);

        // Look for inline script that loads REST API
        const hasInlineScript = await page.locator('script:has-text("REST API enhancement")').count() > 0;
        log(`Inline REST API script present: ${hasInlineScript}`);

        // Step 6: Test form interaction
        log('\n6. Testing form interaction', 'blue');
        
        if (hasTECForm) {
            try {
                // Try to interact with the event title field
                const titleField = page.locator('input[name*="EventTitle"], #EventTitle');
                if (await titleField.count() > 0) {
                    await titleField.fill('Test Event from Automated Script');
                    logSuccess('Successfully filled event title field');
                } else {
                    logWarning('Event title field not found');
                }
                
                // Check for description/content field
                const descField = page.locator('textarea[name*="post_content"], #post_content, .wp-editor-area');
                if (await descField.count() > 0) {
                    logSuccess('Event description field found');
                } else {
                    logWarning('Event description field not found');
                }
                
            } catch (error) {
                logWarning(`Form interaction test failed: ${error.message}`);
            }
        }

        // Step 7: Take screenshot
        await page.screenshot({ path: './test-results/create-event-success.png', fullPage: true });
        logSuccess('Screenshot saved to test-results/create-event-success.png');

        // Step 8: Verify REST API script in page source
        log('\n7. Checking page source for REST API script', 'blue');
        const content = await page.content();
        const hasRestApiScript = content.includes('hvac-rest-api-event-submission.js');
        log(`REST API script in page source: ${hasRestApiScript}`);
        
        const hasInlineRestApiCode = content.includes('HVACRestEventSubmission');
        log(`REST API initialization code present: ${hasInlineRestApiCode}`);

        // Step 9: Generate summary
        logSection('TEST SUMMARY');
        
        if (response.status() === 200 && hasHVACWrapper && (hasTECForm || hasTECContainer)) {
            logSuccess('🎉 CREATE EVENT PAGE IS NOW WORKING!');
            log('\nKey findings:', 'green');
            log(`• Page loads successfully (${response.status()})`, 'green');
            log(`• HVAC template wrapper: ${hasHVACWrapper}`, hasHVACWrapper ? 'green' : 'red');
            log(`• Navigation menu: ${hasNavigation}`, hasNavigation ? 'green' : 'yellow');
            log(`• TEC form container: ${hasTECContainer}`, hasTECContainer ? 'green' : 'red');
            log(`• TEC form: ${hasTECForm}`, hasTECForm ? 'green' : 'red');
            log(`• REST API enhancement: ${restApiScriptLoaded}`, restApiScriptLoaded ? 'green' : 'yellow');
            
            if (!hasTECForm && !hasTECContainer) {
                logWarning('\nNote: TEC form not rendering - check TEC Community Events plugin status');
            }
            
            if (!restApiScriptLoaded) {
                logWarning('\nNote: REST API enhancement not loading - check script enqueueing');
            }
            
        } else {
            logError('CREATE EVENT PAGE STILL HAS ISSUES');
            log('\nIssues found:', 'red');
            if (response.status() !== 200) log(`• Page status: ${response.status()}`, 'red');
            if (!hasHVACWrapper) log('• Missing HVAC template wrapper', 'red');
            if (!hasTECForm && !hasTECContainer) log('• Missing TEC form', 'red');
        }

    } catch (error) {
        logError(`Test failed: ${error.message}`);
        await page.screenshot({ path: './test-results/test-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

// Run the test
testCreateEventPage().catch(console.error);