/**
 * Comprehensive verification script for create-event and edit-event pages
 * Tests all functionality after fixes have been applied
 */

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

// Colors for console output
const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    red: '\x1b[31m',
    yellow: '\x1b[33m',
    blue: '\x1b[36m',
    bold: '\x1b[1m'
};

async function loginAsTrainer(page) {
    console.log(`${colors.blue}🔐 Logging in as test trainer...${colors.reset}`);
    
    await page.goto('https://upskill-staging.measurequick.com/trainer/training-login/', {
        waitUntil: 'networkidle',
        timeout: 30000
    });
    
    await page.fill('#username, #user_login, input[name="log"]', 'test_trainer');
    await page.fill('#password, #user_pass, input[name="pwd"]', 'TestTrainer123!');
    await page.click('input[type="submit"], button[type="submit"]');
    await page.waitForTimeout(3000);
    
    console.log(`${colors.green}   ✅ Logged in successfully${colors.reset}`);
}

async function testCreateEventPage(page) {
    console.log(`\n${colors.bold}${colors.blue}📝 Testing CREATE EVENT Page${colors.reset}`);
    console.log('=' .repeat(50));
    
    const results = {
        pageLoads: false,
        hasNavigation: false,
        hasTitle: false,
        hasContent: false,
        restApiLoads: false,
        excerptFieldAdded: false,
        tecFormPresent: false
    };
    
    try {
        // Navigate to create event page
        const response = await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        results.pageLoads = response.status() === 200;
        console.log(`   Page loads (200 OK): ${results.pageLoads ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check for navigation menu
        results.hasNavigation = await page.locator('.hvac-nav-menu, .hvac-trainer-navigation, .hvac-menu-container').count() > 0;
        console.log(`   Navigation menu: ${results.hasNavigation ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check page title
        const pageTitle = await page.locator('h1').first().textContent().catch(() => '');
        results.hasTitle = pageTitle.includes('Create Event') || pageTitle.includes('Add New Event');
        console.log(`   Page title correct: ${results.hasTitle ? colors.green + '✅' : colors.red + '❌'}${colors.reset} ("${pageTitle}")`);
        
        // Check for any content (shortcode output or TEC form)
        const hasShortcodeContent = await page.locator('.hvac-create-event-wrapper, .hvac-page-content').count() > 0;
        const hasTecContainer = await page.locator('#tribe-community-events, .tribe-events-community').count() > 0;
        results.hasContent = hasShortcodeContent || hasTecContainer;
        console.log(`   Content rendered: ${results.hasContent ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check if REST API script loaded
        results.restApiLoads = await page.evaluate(() => {
            return typeof window.HVACRestEventSubmission !== 'undefined';
        });
        console.log(`   REST API script: ${results.restApiLoads ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check if excerpt field was added
        results.excerptFieldAdded = await page.locator('#event_excerpt, .tribe-section-excerpt').count() > 0;
        console.log(`   Excerpt field: ${results.excerptFieldAdded ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check for TEC form elements
        const tecElements = await page.evaluate(() => {
            return {
                form: !!document.querySelector('form[id*="tribe"], form[class*="tribe"]'),
                titleField: !!document.querySelector('#post_title, input[name="post_title"]'),
                contentField: !!document.querySelector('#tcepostcontent, textarea[name="post_content"]'),
                dateFields: !!document.querySelector('input[name*="EventStart"], input[name*="EventEnd"]')
            };
        });
        results.tecFormPresent = Object.values(tecElements).some(v => v);
        console.log(`   TEC form elements: ${results.tecFormPresent ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check for TEC plugin message
        const pageContent = await page.content();
        if (pageContent.includes('Event management requires The Events Calendar Community Events')) {
            console.log(`   ${colors.yellow}⚠️  TEC Community Events plugin not active${colors.reset}`);
        }
        
    } catch (error) {
        console.log(`   ${colors.red}❌ Error: ${error.message}${colors.reset}`);
    }
    
    // Summary for create page
    const allPassed = Object.values(results).filter(v => v).length;
    const total = Object.values(results).length;
    console.log(`\n   ${colors.bold}Summary: ${allPassed}/${total} checks passed${colors.reset}`);
    
    return results;
}

async function testEditEventPage(page) {
    console.log(`\n${colors.bold}${colors.blue}📝 Testing EDIT EVENT Page${colors.reset}`);
    console.log('=' .repeat(50));
    
    const results = {
        pageLoads: false,
        showsErrorNoId: false,
        hasBackLink: false,
        acceptsEventId: false,
        setsWindowVar: false,
        showsEditForm: false
    };
    
    try {
        // Test 1: Page without event_id
        console.log(`\n   ${colors.bold}Test 1: Without event_id${colors.reset}`);
        const response = await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        results.pageLoads = response.status() === 200;
        console.log(`   Page loads (200 OK): ${results.pageLoads ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check for error message
        const errorMessage = await page.locator('.hvac-error-notice, .error-message, .notice-error').count() > 0;
        const errorText = await page.locator('.hvac-error-notice p, .error-message, .notice-error').first().textContent().catch(() => '');
        results.showsErrorNoId = errorMessage && errorText.toLowerCase().includes('no event');
        console.log(`   Shows error message: ${results.showsErrorNoId ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        if (errorText) {
            console.log(`   Error text: "${errorText}"`);
        }
        
        // Check for back link
        results.hasBackLink = await page.locator('a[href*="/manage"], a[href*="/dashboard"]').count() > 0;
        console.log(`   Has back link: ${results.hasBackLink ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Test 2: Page with event_id
        console.log(`\n   ${colors.bold}Test 2: With event_id=5678${colors.reset}`);
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=5678', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        results.acceptsEventId = response.status() === 200;
        console.log(`   Page accepts event_id: ${results.acceptsEventId ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check if window.hvacEditEventId is set
        const windowVar = await page.evaluate(() => window.hvacEditEventId);
        results.setsWindowVar = windowVar === 5678;
        console.log(`   Sets window.hvacEditEventId: ${results.setsWindowVar ? colors.green + '✅' : colors.red + '❌'}${colors.reset} (value: ${windowVar})`);
        
        // Check for edit form or notice
        const hasEditNotice = await page.locator('.hvac-form-notice, .hvac-edit-notice').count() > 0;
        const hasEditForm = await page.locator('form[id*="tribe"], form[class*="tribe"], #tribe-community-events').count() > 0;
        results.showsEditForm = hasEditNotice || hasEditForm;
        console.log(`   Shows edit form/notice: ${results.showsEditForm ? colors.green + '✅' : colors.red + '❌'}${colors.reset}`);
        
        // Check notice text if present
        if (hasEditNotice) {
            const noticeText = await page.locator('.hvac-form-notice p, .hvac-edit-notice').first().textContent();
            console.log(`   Notice: "${noticeText}"`);
        }
        
    } catch (error) {
        console.log(`   ${colors.red}❌ Error: ${error.message}${colors.reset}`);
    }
    
    // Summary for edit page
    const allPassed = Object.values(results).filter(v => v).length;
    const total = Object.values(results).length;
    console.log(`\n   ${colors.bold}Summary: ${allPassed}/${total} checks passed${colors.reset}`);
    
    return results;
}

async function checkTECPlugin(page) {
    console.log(`\n${colors.bold}${colors.blue}🔌 Checking TEC Plugin Status${colors.reset}`);
    console.log('=' .repeat(50));
    
    // Try to access TEC community events URL
    const tecUrls = [
        'https://upskill-staging.measurequick.com/events/community/add',
        'https://upskill-staging.measurequick.com/events/community/list'
    ];
    
    for (const url of tecUrls) {
        try {
            const response = await page.goto(url, {
                waitUntil: 'networkidle',
                timeout: 15000
            });
            
            const status = response.status();
            console.log(`   ${url.split('.com')[1]}: ${status === 200 ? colors.green + '✅ Active' : colors.yellow + '⚠️  ' + status}${colors.reset}`);
        } catch (error) {
            console.log(`   ${url.split('.com')[1]}: ${colors.red}❌ Error${colors.reset}`);
        }
    }
}

(async () => {
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    console.log(`${colors.bold}${colors.blue}🚀 COMPREHENSIVE EVENT PAGES VERIFICATION${colors.reset}`);
    console.log('=' .repeat(50));
    console.log(`Target: https://upskill-staging.measurequick.com`);
    console.log(`Time: ${new Date().toLocaleString()}`);
    console.log('=' .repeat(50));
    
    try {
        // Login
        await loginAsTrainer(page);
        
        // Test both pages
        const createResults = await testCreateEventPage(page);
        const editResults = await testEditEventPage(page);
        
        // Check TEC plugin
        await checkTECPlugin(page);
        
        // Final Summary
        console.log(`\n${colors.bold}${colors.blue}📊 FINAL VERIFICATION RESULTS${colors.reset}`);
        console.log('=' .repeat(50));
        
        const createPassed = Object.values(createResults).filter(v => v).length;
        const editPassed = Object.values(editResults).filter(v => v).length;
        const totalTests = Object.values(createResults).length + Object.values(editResults).length;
        const totalPassed = createPassed + editPassed;
        
        console.log(`${colors.bold}Create Event Page: ${createPassed}/${Object.values(createResults).length} passed${colors.reset}`);
        console.log(`${colors.bold}Edit Event Page: ${editPassed}/${Object.values(editResults).length} passed${colors.reset}`);
        console.log(`${colors.bold}Overall: ${totalPassed}/${totalTests} tests passed${colors.reset}`);
        
        // Critical checks
        const criticalChecks = {
            'Pages load without 404': createResults.pageLoads && editResults.pageLoads,
            'Navigation appears': createResults.hasNavigation,
            'Content renders': createResults.hasContent,
            'Edit page error handling': editResults.showsErrorNoId,
            'Edit page accepts event_id': editResults.acceptsEventId
        };
        
        console.log(`\n${colors.bold}Critical Checks:${colors.reset}`);
        Object.entries(criticalChecks).forEach(([check, passed]) => {
            console.log(`   ${check}: ${passed ? colors.green + '✅ PASS' : colors.red + '❌ FAIL'}${colors.reset}`);
        });
        
        const allCriticalPassed = Object.values(criticalChecks).every(v => v);
        
        console.log(`\n${colors.bold}${allCriticalPassed ? colors.green + '✅ VERIFICATION SUCCESSFUL' : colors.yellow + '⚠️  PARTIAL SUCCESS'}${colors.reset}`);
        
        if (!allCriticalPassed) {
            console.log(`\n${colors.yellow}Note: Some features require TEC Community Events plugin to be active${colors.reset}`);
        }
        
        // Take final screenshots
        await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/');
        await page.screenshot({ path: 'create-event-final.png', fullPage: true });
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=5678');
        await page.screenshot({ path: 'edit-event-final.png', fullPage: true });
        
        console.log(`\n${colors.blue}📸 Screenshots saved: create-event-final.png, edit-event-final.png${colors.reset}`);
        
    } catch (error) {
        console.error(`${colors.red}❌ Critical error: ${error.message}${colors.reset}`);
    } finally {
        await browser.close();
        console.log(`\n${colors.blue}✨ Verification complete${colors.reset}\n`);
    }
})();