/**
 * Test The Events Calendar Community Events Forms
 */

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

async function loginAsTrainer(page) {
    console.log('🔐 Logging in as test trainer...');
    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('   ✅ Logged in successfully\n');
}

(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();
    
    // Capture console logs
    page.on('console', msg => {
        const text = msg.text();
        if (text.includes('TEC') || text.includes('tribe') || text.includes('community')) {
            console.log('   Console:', text.substring(0, 100));
        }
    });
    
    console.log('🔍 TESTING THE EVENTS CALENDAR COMMUNITY EVENTS FORMS');
    console.log('=' .repeat(50));
    console.log('Time:', new Date().toLocaleString());
    console.log('=' .repeat(50) + '\n');
    
    try {
        await loginAsTrainer(page);
        
        // Test Event Management page
        console.log('📝 TESTING EVENT MANAGEMENT PAGE');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const pageCheck = await page.evaluate(() => {
            const results = {
                pageTitle: document.title,
                hasForm: document.querySelector('form') !== null,
                formCount: document.querySelectorAll('form').length,
                hasAddNewButton: false,
                hasEventsList: false,
                visibleFields: [],
                formAction: null,
                hasTribesContent: false,
                errorMessages: []
            };
            
            // Check for Add New Event button
            const addNewButtons = document.querySelectorAll('a[href*="add"], .tribe-button-primary, .button-primary');
            results.hasAddNewButton = addNewButtons.length > 0;
            
            // Also check for buttons with text
            document.querySelectorAll('button, a.button').forEach(btn => {
                if (btn.textContent.toLowerCase().includes('add') || btn.textContent.toLowerCase().includes('new')) {
                    results.hasAddNewButton = true;
                }
            });
            
            // Check for events list
            const eventsList = document.querySelector('.tribe-events-community-list, .my-events-list, .tribe-community-events');
            results.hasEventsList = eventsList !== null;
            
            // Check for form fields
            const inputs = document.querySelectorAll('input[type="text"]:not([type="hidden"]), textarea, select');
            inputs.forEach(input => {
                if (input.offsetParent !== null) { // Is visible
                    results.visibleFields.push(input.name || input.id || 'unnamed');
                }
            });
            
            // Check form action
            const form = document.querySelector('form');
            if (form) {
                results.formAction = form.action;
            }
            
            // Check for tribe content
            results.hasTribesContent = document.body.innerHTML.includes('tribe-') || 
                                      document.body.innerHTML.includes('community-events');
            
            // Check for error messages
            const errors = document.querySelectorAll('.error, .notice-error, .tribe-error');
            errors.forEach(error => {
                results.errorMessages.push(error.textContent.trim());
            });
            
            return results;
        });
        
        console.log('   Page Title:', pageCheck.pageTitle);
        console.log('   Has Form:', pageCheck.hasForm ? `✅ YES (${pageCheck.formCount} forms)` : '❌ NO');
        console.log('   Has Add New Event Button:', pageCheck.hasAddNewButton ? '✅' : '❌');
        console.log('   Has Events List:', pageCheck.hasEventsList ? '✅' : '❌');
        console.log('   Visible Form Fields:', pageCheck.visibleFields.length);
        if (pageCheck.visibleFields.length > 0) {
            pageCheck.visibleFields.slice(0, 10).forEach(field => {
                console.log('     -', field);
            });
            if (pageCheck.visibleFields.length > 10) {
                console.log(`     ... and ${pageCheck.visibleFields.length - 10} more`);
            }
        }
        console.log('   Form Action:', pageCheck.formAction || 'None');
        console.log('   Has Tribe Content:', pageCheck.hasTribesContent ? '✅' : '❌');
        
        if (pageCheck.errorMessages.length > 0) {
            console.log('   ⚠️ Error Messages:');
            pageCheck.errorMessages.forEach(msg => {
                console.log('     -', msg);
            });
        }
        
        // Click Add New Event if button exists
        if (pageCheck.hasAddNewButton) {
            console.log('\n📝 TESTING ADD NEW EVENT FORM');
            console.log('-'.repeat(40));
            
            try {
                // Try different selectors for Add New button
                const addNewSelectors = [
                    'a[href*="add"]',
                    '.tribe-button-primary',
                    'a:has-text("Add New")',
                    'button:has-text("Add New")',
                    '.tribe-community-events-content a.button'
                ];
                
                let clicked = false;
                for (const selector of addNewSelectors) {
                    try {
                        await page.click(selector, { timeout: 5000 });
                        clicked = true;
                        console.log('   ✅ Clicked Add New Event button');
                        break;
                    } catch (e) {
                        // Try next selector
                    }
                }
                
                if (clicked) {
                    await page.waitForTimeout(3000);
                    
                    const formCheck = await page.evaluate(() => {
                        const results = {
                            hasEventTitle: false,
                            hasDescription: false,
                            hasExcerpt: false,
                            hasStartDate: false,
                            hasEndDate: false,
                            hasVenue: false,
                            hasOrganizer: false,
                            visibleFieldCount: 0,
                            formAction: null
                        };
                        
                        // Check specific fields
                        results.hasEventTitle = document.querySelector('input[name*="title"], #post_title, input[name="EventTitle"]') !== null;
                        results.hasDescription = document.querySelector('textarea[name*="description"], #post_content, .wp-editor-area') !== null;
                        results.hasExcerpt = document.querySelector('textarea[name*="excerpt"], #excerpt') !== null;
                        results.hasStartDate = document.querySelector('input[name*="StartDate"], input[name*="start"]') !== null;
                        results.hasEndDate = document.querySelector('input[name*="EndDate"], input[name*="end"]') !== null;
                        results.hasVenue = document.querySelector('select[name*="venue"], input[name*="Venue"]') !== null;
                        results.hasOrganizer = document.querySelector('select[name*="organizer"], input[name*="Organizer"]') !== null;
                        
                        // Count visible fields
                        const inputs = document.querySelectorAll('input:not([type="hidden"]), textarea, select');
                        inputs.forEach(input => {
                            if (input.offsetParent !== null) {
                                results.visibleFieldCount++;
                            }
                        });
                        
                        // Get form action
                        const form = document.querySelector('form');
                        if (form) {
                            results.formAction = form.action;
                        }
                        
                        return results;
                    });
                    
                    console.log('   Event Title Field:', formCheck.hasEventTitle ? '✅' : '❌');
                    console.log('   Description Field:', formCheck.hasDescription ? '✅' : '❌');
                    console.log('   Excerpt Field:', formCheck.hasExcerpt ? '✅' : '❌');
                    console.log('   Start Date Field:', formCheck.hasStartDate ? '✅' : '❌');
                    console.log('   End Date Field:', formCheck.hasEndDate ? '✅' : '❌');
                    console.log('   Venue Field:', formCheck.hasVenue ? '✅' : '❌');
                    console.log('   Organizer Field:', formCheck.hasOrganizer ? '✅' : '❌');
                    console.log('   Total Visible Fields:', formCheck.visibleFieldCount);
                    console.log('   Form Action:', formCheck.formAction || 'None');
                }
            } catch (error) {
                console.log('   ❌ Could not test Add New Event form:', error.message);
            }
        }
        
        // Final diagnosis
        console.log('\n💡 DIAGNOSIS:');
        if (pageCheck.visibleFields.length === 0 && !pageCheck.hasEventsList) {
            console.log('   ❌ TEC Community Events forms are NOT rendering properly');
            console.log('   The page appears empty or the shortcode is not working');
        } else if (pageCheck.visibleFields.length > 0) {
            console.log('   ✅ TEC Community Events forms are rendering');
            console.log('   Forms have visible fields and appear functional');
        } else if (pageCheck.hasEventsList) {
            console.log('   ✅ TEC Community Events list is showing');
            console.log('   User can see their events');
        }
        
        if (!pageCheck.hasTribesContent) {
            console.log('   ⚠️ No Tribe/Community Events content detected');
            console.log('   The plugin may not be active or shortcode not processed');
        }
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
    } finally {
        await browser.close();
        console.log('\n✅ Test complete');
    }
})();