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

async function testEditEventPageComplete() {
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    
    try {
        console.log('🔍 Complete Edit Event Page Test...');
        
        // Step 1: Login first to bypass authentication
        console.log('\n1. Logging in to bypass authentication...');
        await page.goto('https://upskill-staging.measurequick.com/wp-admin/');
        
        // Look for login form elements
        const hasLoginForm = await page.locator('#loginform, input[name="log"]').count() > 0;
        
        if (hasLoginForm) {
            console.log('   Found login form, logging in...');
            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('   ✅ Logged in successfully');
        } else {
            console.log('   Already logged in or no login form found');
        }
        
        // Step 2: Test edit-event page without event_id
        console.log('\n2. Testing edit-event page without event_id...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/');
        await page.waitForLoadState('networkidle');
        
        const pageData1 = await page.evaluate(() => {
            return {
                title: document.title,
                hasErrorNotice: document.querySelector('.hvac-error-notice') !== null,
                hasBackLink: document.querySelector('a[href*="event/manage"]') !== null,
                h1Text: document.querySelector('h1')?.textContent || 'No H1',
                bodyContent: document.body.textContent.includes('No event specified'),
                isLoginPage: document.title.includes('Login') || document.body.textContent.includes('username'),
                hasHvacWrapper: document.querySelector('.hvac-edit-event-wrapper') !== null
            };
        });
        
        console.log(`   Page Title: ${pageData1.title}`);
        console.log(`   Is Login Page: ${pageData1.isLoginPage ? '❌ (redirected)' : '✅ (correct page)'}`);
        console.log(`   H1 Text: ${pageData1.h1Text}`);
        console.log(`   Has Error Notice: ${pageData1.hasErrorNotice ? '✅' : '❌'}`);
        console.log(`   Has Back Link: ${pageData1.hasBackLink ? '✅' : '❌'}`);
        console.log(`   Has "No event specified": ${pageData1.bodyContent ? '✅' : '❌'}`);
        console.log(`   Has HVAC Wrapper: ${pageData1.hasHvacWrapper ? '✅' : '❌'}`);
        
        // Step 3: Test edit-event page with event_id
        console.log('\n3. Testing edit-event page with event_id=6078...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=6078');
        await page.waitForLoadState('networkidle');
        
        const pageData2 = await page.evaluate(() => {
            return {
                title: document.title,
                hasInfoNotice: document.querySelector('.hvac-form-notice') !== null,
                h1Text: document.querySelector('h1')?.textContent || 'No H1',
                bodyContent: document.body.textContent.includes('Editing Event ID'),
                hasForm: document.querySelectorAll('form').length > 0,
                isLoginPage: document.title.includes('Login') || document.body.textContent.includes('username'),
                hasHvacWrapper: document.querySelector('.hvac-edit-event-wrapper') !== null,
                hasTribeForm: document.querySelector('.tribe-community-events, form[id*="tribe"]') !== null
            };
        });
        
        console.log(`   Page Title: ${pageData2.title}`);
        console.log(`   Is Login Page: ${pageData2.isLoginPage ? '❌ (redirected)' : '✅ (correct page)'}`);
        console.log(`   H1 Text: ${pageData2.h1Text}`);
        console.log(`   Has Info Notice: ${pageData2.hasInfoNotice ? '✅' : '❌'}`);
        console.log(`   Has "Editing Event ID": ${pageData2.bodyContent ? '✅' : '❌'}`);
        console.log(`   Has Form: ${pageData2.hasForm ? '✅' : '❌'}`);
        console.log(`   Has HVAC Wrapper: ${pageData2.hasHvacWrapper ? '✅' : '❌'}`);
        console.log(`   Has Tribe Form: ${pageData2.hasTribeForm ? '✅' : '❌'}`);
        
        // Step 4: Check REST API script loading
        console.log('\n4. Checking REST API script loading...');
        await page.waitForTimeout(2000); // Wait for scripts to load
        
        const scriptData = await page.evaluate(() => {
            return {
                hvacEditEventId: typeof window.hvacEditEventId !== 'undefined' ? window.hvacEditEventId : 'undefined',
                hasRestApiScript: typeof HVACRestEventSubmission !== 'undefined',
                jqueryLoaded: typeof window.jQuery !== 'undefined',
                pluginScripts: Array.from(document.querySelectorAll('script[src*="hvac-community-events"]')).length
            };
        });
        
        console.log(`   window.hvacEditEventId: ${scriptData.hvacEditEventId}`);
        console.log(`   HVACRestEventSubmission: ${scriptData.hasRestApiScript ? '✅' : '❌'}`);
        console.log(`   jQuery loaded: ${scriptData.jqueryLoaded ? '✅' : '❌'}`);
        console.log(`   HVAC plugin scripts: ${scriptData.pluginScripts}`);
        
        // Step 5: Overall assessment
        console.log('\n5. Overall Assessment:');
        const test1Pass = !pageData1.isLoginPage && pageData1.hasErrorNotice && pageData1.bodyContent;
        const test2Pass = !pageData2.isLoginPage && pageData2.bodyContent && pageData2.hasForm;
        
        console.log(`   Test 1 (No event_id): ${test1Pass ? '✅ PASS' : '❌ FAIL'}`);
        console.log(`   Test 2 (With event_id): ${test2Pass ? '✅ PASS' : '❌ FAIL'}`);
        
        if (!test1Pass || !test2Pass) {
            console.log('\n🔧 DIAGNOSIS:');
            if (pageData1.isLoginPage || pageData2.isLoginPage) {
                console.log('   - Page is redirecting to login (authentication issue)');
                console.log('   - edit-event page may not exist or have wrong permissions');
            }
            if (!pageData1.hasHvacWrapper && !pageData2.hasHvacWrapper) {
                console.log('   - Custom template not being used');
                console.log('   - Page may not have correct template assignment');
            }
        } else {
            console.log('\n✅ SUCCESS: Edit Event page is working correctly!');
        }
        
        // Take final screenshot
        await page.screenshot({ 
            path: '/tmp/playwright-mcp-output/2025-08-12T21-21-19.151Z/edit-event-final-test.png',
            fullPage: true 
        });
        console.log('\n📸 Final screenshot saved.');
        
    } catch (error) {
        console.error('❌ Test failed:', error.message);
    } finally {
        await browser.close();
    }
}

testEditEventPageComplete();