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

(async () => {
    console.log('🔍 Comprehensive Event Pages Testing - Staging Site');
    console.log('Testing Create/Edit Event pages after shortcode conflict fix\n');

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

    try {
        // Test credentials
        const baseUrl = 'https://upskill-staging.measurequick.com';
        const username = 'test_trainer';
        const password = 'TestTrainer123!';

        console.log('📝 Step 1: Login to staging site...');
        await page.goto(`${baseUrl}/trainer/login/`);
        await page.waitForSelector('#user_login');
        
        await page.fill('#user_login', username);
        await page.fill('#user_pass', password);
        await page.click('#wp-submit');
        
        await page.waitForURL('**/trainer/dashboard/**');
        console.log('✅ Login successful\n');

        // Test 1: Create Event Page
        console.log('🧪 Test 1: Create Event Page');
        await page.goto(`${baseUrl}/trainer/create-event/`);
        await page.waitForTimeout(3000);

        // Check for shortcode debug output
        const createPageContent = await page.textContent('body');
        const hasCreateContent = createPageContent.includes('Create New Event');
        const hasTECForm = createPageContent.includes('Event Details') || 
                          createPageContent.includes('Event Title') ||
                          createPageContent.includes('tribe-events');
        
        console.log(`   Page Title Present: ${hasCreateContent ? '✅' : '❌'}`);
        console.log(`   TEC Form Present: ${hasTECForm ? '✅' : '❌'}`);
        
        // Check console for debugging messages
        const consoleLogs = [];
        page.on('console', msg => {
            if (msg.text().includes('Create Event') || msg.text().includes('REST API')) {
                consoleLogs.push(msg.text());
            }
        });

        // Check for error messages
        const hasError = createPageContent.includes('plugin is required but not active') ||
                        createPageContent.includes('shortcode not');
        console.log(`   Error Messages: ${hasError ? '❌ Found' : '✅ None'}`);

        // Take screenshot
        await page.screenshot({ path: 'create-event-page-test.png', fullPage: true });
        console.log('   Screenshot saved: create-event-page-test.png\n');

        // Test 2: Edit Event Page (without event ID)
        console.log('🧪 Test 2: Edit Event Page (no event ID)');
        await page.goto(`${baseUrl}/trainer/edit-event/`);
        await page.waitForTimeout(3000);

        const editPageContent = await page.textContent('body');
        const hasEditTitle = editPageContent.includes('Edit Event');
        const hasNoEventError = editPageContent.includes('No event specified') ||
                               editPageContent.includes('Please select an event');
        
        console.log(`   Page Title Present: ${hasEditTitle ? '✅' : '❌'}`);
        console.log(`   No Event ID Error: ${hasNoEventError ? '✅ Expected' : '❌'}`);
        
        await page.screenshot({ path: 'edit-event-page-no-id-test.png', fullPage: true });
        console.log('   Screenshot saved: edit-event-page-no-id-test.png\n');

        // Test 3: Edit Event Page (with event ID)
        console.log('🧪 Test 3: Edit Event Page (with event ID)');
        // First, try to find an existing event
        await page.goto(`${baseUrl}/trainer/event/manage/`);
        await page.waitForTimeout(2000);
        
        // Look for event links
        const eventLinks = await page.$$eval('a[href*="event_id="]', links => 
            links.map(link => link.href.match(/event_id=(\d+)/)?.[1]).filter(Boolean)
        );
        
        if (eventLinks.length > 0) {
            const eventId = eventLinks[0];
            console.log(`   Found event ID: ${eventId}`);
            
            await page.goto(`${baseUrl}/trainer/edit-event/?event_id=${eventId}`);
            await page.waitForTimeout(3000);
            
            const editWithIdContent = await page.textContent('body');
            const hasEditForm = editWithIdContent.includes('Event Details') ||
                               editWithIdContent.includes('Event Title') ||
                               editWithIdContent.includes('tribe-events');
            const hasEventId = editWithIdContent.includes(`Event ID: ${eventId}`);
            
            console.log(`   Edit Form Present: ${hasEditForm ? '✅' : '❌'}`);
            console.log(`   Event ID Display: ${hasEventId ? '✅' : '❌'}`);
            
            await page.screenshot({ path: 'edit-event-page-with-id-test.png', fullPage: true });
            console.log('   Screenshot saved: edit-event-page-with-id-test.png');
        } else {
            console.log('   ⚠️  No existing events found for testing');
        }

        // Test 4: Check which shortcode implementation is running
        console.log('\n🧪 Test 4: Shortcode Implementation Check');
        
        // Go back to create page and check console logs
        await page.goto(`${baseUrl}/trainer/create-event/`);
        await page.waitForTimeout(2000);
        
        const pageHTML = await page.content();
        const hasShortcodesClass = pageHTML.includes('HVAC_Shortcodes') || 
                                  pageHTML.includes('render_create_event');
        const hasEditShortcodeClass = pageHTML.includes('Edit Event Shortcode') ||
                                     pageHTML.includes('hvacEditEventId');
        
        console.log(`   HVAC_Shortcodes indicators: ${hasShortcodesClass ? '🔍 Found' : '❌ None'}`);
        console.log(`   HVAC_Edit_Event_Shortcode indicators: ${hasEditShortcodeClass ? '🔍 Found' : '❌ None'}`);

        // Test 5: Direct shortcode testing (if possible)
        console.log('\n🧪 Test 5: Plugin Status Check');
        
        // Check if we can access our debug script
        try {
            await page.goto(`${baseUrl}/wp-content/plugins/hvac-community-events/test-tec-staging.php`);
            await page.waitForTimeout(2000);
            
            const debugContent = await page.textContent('body');
            
            if (debugContent.includes('TEC Community Events Test')) {
                console.log('   ✅ Debug script accessible');
                
                const tecActive = debugContent.includes('TEC Main: ✓ Active');
                const tecCEActive = debugContent.includes('TEC Community: ✓ Active');
                const shortcodeExists = debugContent.includes('[tribe_community_events]: ✓ Registered');
                
                console.log(`   TEC Main Plugin: ${tecActive ? '✅ Active' : '❌ Inactive'}`);
                console.log(`   TEC Community Events: ${tecCEActive ? '✅ Active' : '❌ Inactive'}`);
                console.log(`   TEC Shortcode: ${shortcodeExists ? '✅ Registered' : '❌ Not Registered'}`);
                
                await page.screenshot({ path: 'debug-script-output.png', fullPage: true });
                console.log('   Screenshot saved: debug-script-output.png');
            } else {
                console.log('   ❌ Debug script not accessible or not working');
            }
        } catch (error) {
            console.log('   ⚠️  Could not access debug script');
        }

        console.log('\n📊 Summary of Findings:');
        console.log('='.repeat(50));
        
        if (consoleLogs.length > 0) {
            console.log('Console Debug Messages:');
            consoleLogs.forEach(log => console.log(`   - ${log}`));
        }

        console.log('\n🎯 Next Steps:');
        console.log('1. Check screenshots for visual confirmation');
        console.log('2. If TEC form is still not showing, check plugin activation');
        console.log('3. Look for JavaScript console errors in browser');
        console.log('4. Verify shortcode conflict resolution took effect');

    } catch (error) {
        console.error('❌ Test failed:', error.message);
    } finally {
        await browser.close();
    }
})();