/**
 * Comprehensive TEC Community Events Testing
 */

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();
    
    console.log('🔍 COMPREHENSIVE TEC COMMUNITY EVENTS TESTING');
    console.log('=' .repeat(50));
    console.log('Time:', new Date().toLocaleString());
    console.log('=' .repeat(50) + '\n');
    
    try {
        await loginAsTrainer(page);
        
        // Test 1: Our Manage Event Page
        console.log('📝 TEST 1: HVAC MANAGE EVENT PAGE');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const managePageCheck = await page.evaluate(() => {
            const results = {
                hasNavigation: document.querySelector('.hvac-trainer-menu') !== null,
                hasEventManagementHeader: document.body.innerHTML.includes('Event Management'),
                hasAddNewButton: document.querySelector('a[href="/events/network/add/"]') !== null,
                hasViewEventsButton: document.querySelector('a[href="/events/network/"]') !== null,
                buttonTexts: [],
                links: []
            };
            
            // Get button texts
            document.querySelectorAll('.hvac-event-actions a').forEach(link => {
                results.buttonTexts.push(link.textContent.trim());
                results.links.push(link.href);
            });
            
            return results;
        });
        
        console.log('   Has HVAC Navigation:', managePageCheck.hasNavigation ? '✅' : '❌');
        console.log('   Has Event Management Header:', managePageCheck.hasEventManagementHeader ? '✅' : '❌');
        console.log('   Has Add New Event Button:', managePageCheck.hasAddNewButton ? '✅' : '❌');
        console.log('   Has View Events Button:', managePageCheck.hasViewEventsButton ? '✅' : '❌');
        console.log('   Button Texts:', managePageCheck.buttonTexts.join(', '));
        console.log('   Links Found:', managePageCheck.links.length);
        
        // Test 2: TEC Add Event Page
        console.log('\n📝 TEST 2: TEC ADD EVENT PAGE (/events/network/add/)');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/events/network/add/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const addEventCheck = await page.evaluate(() => {
            const results = {
                pageTitle: document.title,
                hasForm: document.querySelector('form') !== null,
                formId: document.querySelector('form')?.id || 'no-id',
                formAction: document.querySelector('form')?.action || 'no-action',
                fields: {
                    title: false,
                    description: false,
                    excerpt: false,
                    startDate: false,
                    endDate: false,
                    venue: false,
                    organizer: false,
                    category: false,
                    tags: false,
                    featured: false
                },
                totalVisibleFields: 0,
                fieldNames: []
            };
            
            // Check for specific fields
            results.fields.title = document.querySelector('input[name*="title"], input[name*="Title"], #post_title') !== null;
            results.fields.description = document.querySelector('textarea[name*="content"], textarea[name*="Description"], #tcepostcontent, .wp-editor-area') !== null;
            results.fields.excerpt = document.querySelector('textarea[name*="excerpt"], textarea[name*="Excerpt"], #excerpt') !== null;
            results.fields.startDate = document.querySelector('input[name*="StartDate"], input[name*="start"], input[id*="StartDate"]') !== null;
            results.fields.endDate = document.querySelector('input[name*="EndDate"], input[name*="end"], input[id*="EndDate"]') !== null;
            results.fields.venue = document.querySelector('select[name*="venue"], select[name*="Venue"], input[name*="venue"]') !== null;
            results.fields.organizer = document.querySelector('select[name*="organizer"], select[name*="Organizer"], input[name*="organizer"]') !== null;
            results.fields.category = document.querySelector('select[name*="category"], input[name*="category"], .tribe-section-taxonomy') !== null;
            results.fields.tags = document.querySelector('input[name*="tags"], input[name*="Tags"], #tax-input-post_tag') !== null;
            results.fields.featured = document.querySelector('input[name*="featured"], input[type="checkbox"][name*="Featured"]') !== null;
            
            // Count all visible fields
            const inputs = document.querySelectorAll('input:not([type="hidden"]), textarea, select');
            inputs.forEach(input => {
                if (input.offsetParent !== null) {
                    results.totalVisibleFields++;
                    if (input.name) {
                        results.fieldNames.push(input.name);
                    }
                }
            });
            
            return results;
        });
        
        console.log('   Page Title:', addEventCheck.pageTitle);
        console.log('   Has Form:', addEventCheck.hasForm ? '✅' : '❌');
        console.log('   Form ID:', addEventCheck.formId);
        console.log('   Form Action:', addEventCheck.formAction);
        console.log('\n   Field Detection:');
        console.log('   - Title Field:', addEventCheck.fields.title ? '✅' : '❌');
        console.log('   - Description Field:', addEventCheck.fields.description ? '✅' : '❌');
        console.log('   - Excerpt Field:', addEventCheck.fields.excerpt ? '✅' : '❌');
        console.log('   - Start Date Field:', addEventCheck.fields.startDate ? '✅' : '❌');
        console.log('   - End Date Field:', addEventCheck.fields.endDate ? '✅' : '❌');
        console.log('   - Venue Field:', addEventCheck.fields.venue ? '✅' : '❌');
        console.log('   - Organizer Field:', addEventCheck.fields.organizer ? '✅' : '❌');
        console.log('   - Category Field:', addEventCheck.fields.category ? '✅' : '❌');
        console.log('   - Tags Field:', addEventCheck.fields.tags ? '✅' : '❌');
        console.log('   - Featured Checkbox:', addEventCheck.fields.featured ? '✅' : '❌');
        console.log('\n   Total Visible Fields:', addEventCheck.totalVisibleFields);
        
        if (addEventCheck.fieldNames.length > 0) {
            console.log('   Sample Field Names (first 10):');
            addEventCheck.fieldNames.slice(0, 10).forEach(name => {
                console.log('     -', name);
            });
        }
        
        // Test 3: TEC Events List Page
        console.log('\n📝 TEST 3: TEC EVENTS LIST PAGE (/events/network/)');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/events/network/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const listPageCheck = await page.evaluate(() => {
            const results = {
                pageTitle: document.title,
                hasEventsList: false,
                eventCount: 0,
                hasAddNewButton: false,
                hasEditButtons: false,
                tableHeaders: [],
                errorMessages: []
            };
            
            // Check for events list/table
            const eventsList = document.querySelector('.tribe-community-events-list, .my-events-list, table.events-community-list, .tribe-events-community-list');
            results.hasEventsList = eventsList !== null;
            
            // Count events
            const eventRows = document.querySelectorAll('tr.type-tribe_events, .tribe-events-community-list-event, .my-events-list-event');
            results.eventCount = eventRows.length;
            
            // Check for Add New button
            const addButtons = document.querySelectorAll('a[href*="add"]');
            results.hasAddNewButton = addButtons.length > 0;
            
            // Check for Edit buttons
            const editButtons = document.querySelectorAll('a[href*="edit"], .edit-event');
            results.hasEditButtons = editButtons.length > 0;
            
            // Get table headers
            const headers = document.querySelectorAll('th');
            headers.forEach(header => {
                results.tableHeaders.push(header.textContent.trim());
            });
            
            // 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:', listPageCheck.pageTitle);
        console.log('   Has Events List:', listPageCheck.hasEventsList ? '✅' : '❌');
        console.log('   Event Count:', listPageCheck.eventCount);
        console.log('   Has Add New Button:', listPageCheck.hasAddNewButton ? '✅' : '❌');
        console.log('   Has Edit Buttons:', listPageCheck.hasEditButtons ? '✅' : '❌');
        
        if (listPageCheck.tableHeaders.length > 0) {
            console.log('   Table Headers:', listPageCheck.tableHeaders.join(', '));
        }
        
        if (listPageCheck.errorMessages.length > 0) {
            console.log('   ⚠️ Error Messages:');
            listPageCheck.errorMessages.forEach(msg => {
                console.log('     -', msg);
            });
        }
        
        // Test 4: Field Population Success Rate
        console.log('\n📝 TEST 4: FIELD POPULATION SUCCESS RATE');
        console.log('-'.repeat(40));
        
        const criticalFields = ['title', 'description', 'excerpt', 'startDate', 'endDate', 'venue', 'organizer'];
        const foundFields = criticalFields.filter(field => addEventCheck.fields[field]);
        const successRate = (foundFields.length / criticalFields.length) * 100;
        
        console.log('   Critical Fields Found:', foundFields.length + '/' + criticalFields.length);
        console.log('   Field Population Success Rate:', successRate.toFixed(1) + '%');
        console.log('   Missing Critical Fields:', criticalFields.filter(field => !addEventCheck.fields[field]).join(', ') || 'None');
        
        // Final Summary
        console.log('\n' + '='.repeat(50));
        console.log('📊 FINAL TEST SUMMARY');
        console.log('='.repeat(50));
        
        const allTestsPassed = 
            managePageCheck.hasAddNewButton && 
            managePageCheck.hasViewEventsButton &&
            addEventCheck.hasForm &&
            addEventCheck.totalVisibleFields > 0;
        
        if (allTestsPassed) {
            console.log('✅ TEC Community Events is WORKING');
            console.log('   - Manage page has proper links to TEC pages');
            console.log('   - Add Event form is accessible at /events/network/add/');
            console.log('   - Events list is accessible at /events/network/');
            console.log('   - Field population success rate:', successRate.toFixed(1) + '%');
        } else {
            console.log('❌ TEC Community Events has ISSUES');
            if (!managePageCheck.hasAddNewButton) {
                console.log('   - Missing Add New Event button on manage page');
            }
            if (!addEventCheck.hasForm) {
                console.log('   - No form found on Add Event page');
            }
            if (addEventCheck.totalVisibleFields === 0) {
                console.log('   - No visible fields on Add Event form');
            }
            if (successRate < 100) {
                console.log('   - Missing critical fields:', criticalFields.filter(field => !addEventCheck.fields[field]).join(', '));
            }
        }
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
    } finally {
        await browser.close();
        console.log('\n✅ Testing complete');
    }
})();