#!/usr/bin/env node

const { chromium } = require('@playwright/test');

process.env.DISPLAY = ':0';

(async () => {
    console.log('Testing manage event form population...\n');
    
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox'] 
    });
    const page = await browser.newPage();
    
    try {
        // Login
        console.log('1. Logging in...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'test_admin');
        await page.fill('#user_pass', 'TestAdmin2025!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        // Go to manage event page with event_id
        console.log('2. Going to manage event page with event_id=6161...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/?event_id=6161');
        await page.waitForLoadState('networkidle');
        
        // Check if hvac_event_comprehensive object exists
        const hasComprehensiveData = await page.evaluate(() => {
            return typeof hvac_event_comprehensive !== 'undefined';
        });
        
        console.log('\n3. Checking for comprehensive data object:');
        console.log('   Has hvac_event_comprehensive:', hasComprehensiveData);
        
        if (hasComprehensiveData) {
            const eventData = await page.evaluate(() => hvac_event_comprehensive);
            console.log('\n4. Event data structure:');
            console.log('   Event ID:', eventData.event_id);
            console.log('   Has event_data:', !!eventData.event_data);
            
            if (eventData.event_data) {
                console.log('   Core data:', eventData.event_data.core);
                console.log('   Venue data:', eventData.event_data.venue);
                console.log('   Organizer data:', eventData.event_data.organizer);
            }
        }
        
        // Check actual form fields
        console.log('\n5. Checking form fields:');
        const fields = await page.evaluate(() => {
            const results = {};
            
            // Try multiple selectors for title
            const titleSelectors = [
                '#title',
                'input[name="post_title"]',
                '#event-title',
                'input[name="EventTitle"]'
            ];
            
            for (const selector of titleSelectors) {
                const field = document.querySelector(selector);
                if (field) {
                    results.title = {
                        found: true,
                        selector: selector,
                        value: field.value
                    };
                    break;
                }
            }
            
            if (!results.title) {
                results.title = { found: false };
            }
            
            // Try multiple selectors for description
            const descSelectors = [
                '#description',
                'textarea[name="post_content"]',
                '#event-description',
                'textarea[name="EventDescription"]'
            ];
            
            for (const selector of descSelectors) {
                const field = document.querySelector(selector);
                if (field) {
                    results.description = {
                        found: true,
                        selector: selector,
                        value: field.value
                    };
                    break;
                }
            }
            
            if (!results.description) {
                results.description = { found: false };
            }
            
            // Check for TEC shortcode
            const shortcodeDiv = document.querySelector('[data-tribe-shortcode]');
            results.hasTECShortcode = !!shortcodeDiv;
            
            // Check for any tribe forms
            const tribeForms = document.querySelectorAll('form[id*="tribe"], form[class*="tribe"]');
            results.tribeForms = tribeForms.length;
            
            return results;
        });
        
        console.log('   Title field:', fields.title);
        console.log('   Description field:', fields.description);
        console.log('   Has TEC shortcode:', fields.hasTECShortcode);
        console.log('   Tribe forms found:', fields.tribeForms);
        
        // Check if the comprehensive JS ran
        console.log('\n6. Checking if population script ran:');
        const populationStatus = await page.evaluate(() => {
            // Check if there's any indication the script tried to run
            const notifications = document.querySelectorAll('.hvac-field-notification');
            return {
                notifications: notifications.length,
                consoleErrors: window.hvacErrors || []
            };
        });
        
        console.log('   Field notifications:', populationStatus.notifications);
        
    } catch (error) {
        console.error('Error:', error.message);
    } finally {
        console.log('\nKeeping browser open for 10 seconds...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
})();