/**
 * Test Event Manage Page
 * 
 * Verifies what shortcode is being used and whether the TEC form renders
 */

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

async function testEventManagePage() {
    console.log('🧪 Testing Event Manage Page...');
    console.log('='.repeat(60));
    
    const browser = await chromium.launch({ 
        headless: true,
        slowMo: 500
    });
    
    try {
        const context = await browser.newContext({
            viewport: { width: 1400, height: 900 }
        });
        
        const page = await context.newPage();
        
        // Enable console logging
        page.on('console', msg => {
            const text = msg.text();
            if (text.includes('[HVAC') || text.includes('TEC')) {
                console.log(`🔧 ${text}`);
            }
        });
        
        // Step 1: Login as trainer
        console.log('\n📝 Step 1: Logging in as trainer...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForTimeout(2000);
        
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        console.log('✅ Logged in');
        
        // Step 2: Navigate to event manage page
        console.log('\n📝 Step 2: Navigating to event manage page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.waitForTimeout(3000);
        
        // Step 3: Analyze what's on the page
        console.log('\n📝 Step 3: Analyzing page content...');
        
        const pageAnalysis = await page.evaluate(() => {
            const analysis = {
                pageTitle: document.title,
                bodyClasses: document.body.className,
                hasHvacShortcode: false,
                hasTecForm: false,
                hasNoEventsMessage: false,
                formSelectors: [],
                contentSnippet: '',
                scripts: [],
                errorMessages: []
            };
            
            // Check for HVAC shortcode in content
            const content = document.querySelector('.hvac-page-content');
            if (content) {
                analysis.contentSnippet = content.innerHTML.substring(0, 500);
                analysis.hasHvacShortcode = content.innerHTML.includes('hvac_manage_event');
            }
            
            // Check for TEC form elements
            const formSelectors = [
                '#tribe-community-events',
                '#tribe-community-events-form',
                '.tribe-community-events',
                '[name="community-event"]',
                '.tribe-events-community-form',
                '#tribe-events-community-submission'
            ];
            
            formSelectors.forEach(selector => {
                const elem = document.querySelector(selector);
                if (elem) {
                    analysis.hasTecForm = true;
                    analysis.formSelectors.push(selector);
                }
            });
            
            // Check for "no events" or error messages
            const bodyText = document.body.textContent;
            if (bodyText.includes('No events') || bodyText.includes('no events')) {
                analysis.hasNoEventsMessage = true;
            }
            
            // Check for error messages
            const errorPatterns = [
                'Event management requires',
                'permission',
                'not found',
                '404'
            ];
            
            errorPatterns.forEach(pattern => {
                if (bodyText.toLowerCase().includes(pattern.toLowerCase())) {
                    analysis.errorMessages.push(pattern);
                }
            });
            
            // Check loaded scripts
            const scripts = document.querySelectorAll('script[src]');
            scripts.forEach(script => {
                const src = script.src;
                if (src.includes('hvac') || src.includes('tribe') || src.includes('event')) {
                    analysis.scripts.push(src.split('/').pop());
                }
            });
            
            return analysis;
        });
        
        console.log('\n📊 Page Analysis Results:');
        console.log('='.repeat(60));
        console.log(`Page Title: ${pageAnalysis.pageTitle}`);
        console.log(`Has HVAC Shortcode: ${pageAnalysis.hasHvacShortcode}`);
        console.log(`Has TEC Form: ${pageAnalysis.hasTecForm}`);
        console.log(`Has No Events Message: ${pageAnalysis.hasNoEventsMessage}`);
        
        if (pageAnalysis.formSelectors.length > 0) {
            console.log(`TEC Form Selectors Found: ${pageAnalysis.formSelectors.join(', ')}`);
        }
        
        if (pageAnalysis.errorMessages.length > 0) {
            console.log(`Error Messages: ${pageAnalysis.errorMessages.join(', ')}`);
        }
        
        console.log(`\nRelevant Scripts Loaded:`);
        pageAnalysis.scripts.forEach(script => {
            console.log(`  - ${script}`);
        });
        
        console.log(`\nContent Snippet:`);
        console.log(pageAnalysis.contentSnippet);
        
        // Step 4: Check if it's showing event list instead of form
        console.log('\n📝 Step 4: Checking for event list vs form...');
        
        const hasEventList = await page.evaluate(() => {
            // Check for event list elements
            const listSelectors = [
                '.tribe-events-list',
                '.hvac-events-list',
                '.event-list',
                'table.events',
                '.hvac-event-row'
            ];
            
            for (const selector of listSelectors) {
                if (document.querySelector(selector)) {
                    return true;
                }
            }
            
            // Check for "My Events" or similar header
            const headers = document.querySelectorAll('h1, h2, h3');
            for (const header of headers) {
                if (header.textContent.toLowerCase().includes('my events') || 
                    header.textContent.toLowerCase().includes('your events')) {
                    return true;
                }
            }
            
            return false;
        });
        
        if (hasEventList) {
            console.log('⚠️ Page is showing event LIST, not event creation FORM');
            console.log('💡 This means the shortcode is rendering the list view');
            
            // Look for "Add Event" button
            const addEventButton = await page.$('a:has-text("Add Event"), button:has-text("Add Event"), a:has-text("Create Event")');
            if (addEventButton) {
                console.log('✅ Found "Add Event" button - clicking it...');
                await addEventButton.click();
                await page.waitForTimeout(3000);
                
                // Check if we're now on the form
                const nowHasForm = await page.$('#tribe-community-events-form, .tribe-community-events form');
                if (nowHasForm) {
                    console.log('✅ Now on event creation form!');
                } else {
                    console.log('❌ Still not on form after clicking Add Event');
                }
            } else {
                console.log('❌ No "Add Event" button found');
            }
        }
        
        // Step 5: Try direct TEC URLs
        console.log('\n📝 Step 5: Testing direct TEC URLs...');
        
        const tecUrls = [
            'https://upskill-staging.measurequick.com/events/community/add',
            'https://upskill-staging.measurequick.com/trainer/event/manage/?action=add'
        ];
        
        for (const url of tecUrls) {
            console.log(`\nTrying: ${url}`);
            await page.goto(url);
            await page.waitForTimeout(2000);
            
            const hasForm = await page.$('#tribe-community-events-form, .tribe-community-events form');
            if (hasForm) {
                console.log('✅ Form found at this URL!');
                
                // Check if REST API script loaded
                const restApiLoaded = await page.evaluate(() => {
                    return typeof HVACRestEventSubmission !== 'undefined';
                });
                
                console.log(`REST API Script: ${restApiLoaded ? '✅ Loaded' : '❌ Not loaded'}`);
                break;
            } else {
                console.log('❌ No form at this URL');
            }
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/event-manage-page-analysis.png',
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
        return {
            success: pageAnalysis.hasTecForm,
            analysis: pageAnalysis
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testEventManagePage()
        .then(result => {
            console.log('\n🏁 Event Manage Page Test Complete');
            
            if (!result.success) {
                console.log('\n💡 Recommendations:');
                console.log('1. Check if [hvac_manage_event] shortcode is on the page');
                console.log('2. Verify TEC Community Events plugin is active');
                console.log('3. Check user permissions for event submission');
                console.log('4. Consider using direct TEC URLs for event creation');
            }
            
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Test runner failed:', error);
            process.exit(1);
        });
}

module.exports = { testEventManagePage };