#!/usr/bin/env node

/**
 * Test TEC Community Events with Authentication
 * Tests our custom integrated pages and actual TEC URLs
 */

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

const BASE_URL = 'https://upskill-staging.measurequick.com';
const CREDENTIALS = {
    email: 'test_trainer@example.com',
    password: 'TestTrainer123!'
};

async function runTest() {
    console.log('🚀 Testing TEC Community Events with Authentication\n');
    
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    
    try {
        // 1. Login first
        console.log('1️⃣ Logging in as trainer...');
        await page.goto(`${BASE_URL}/wp-login.php`);
        await page.fill('#user_login', CREDENTIALS.email);
        await page.fill('#user_pass', CREDENTIALS.password);
        await page.click('#wp-submit');
        await page.waitForURL(/dashboard/, { timeout: 10000 });
        console.log('✅ Logged in successfully\n');
        
        // 2. Test our custom HVAC integrated pages
        console.log('2️⃣ Testing HVAC integrated pages...');
        
        const hvacPages = [
            { url: '/trainer/events/create/', name: 'HVAC Create Event' },
            { url: '/trainer/events/', name: 'HVAC Events List' },
            { url: '/trainer/events/my-events/', name: 'HVAC My Events' }
        ];
        
        for (const testPage of hvacPages) {
            await page.goto(`${BASE_URL}${testPage.url}`);
            await page.waitForLoadState('domcontentloaded');
            const status = await page.locator('body').evaluate(el => {
                if (el.textContent.includes('404') || el.textContent.includes('not found')) {
                    return '404';
                }
                return 'OK';
            });
            console.log(`${testPage.name}: ${status === 'OK' ? '✅' : '❌'} ${status}`);
        }
        
        console.log('');
        
        // 3. Test standard TEC Community URLs (while authenticated)
        console.log('3️⃣ Testing TEC Community Events URLs (authenticated)...');
        
        const tecPages = [
            { url: '/community/', name: 'Community Main' },
            { url: '/community/add/', name: 'Add Event' },
            { url: '/community/list/', name: 'My Events List' },
            { url: '/events/community/', name: 'Events Community' },
            { url: '/events/community/add/', name: 'Events Add' },
            { url: '/events/community/list/', name: 'Events List' }
        ];
        
        for (const testPage of tecPages) {
            await page.goto(`${BASE_URL}${testPage.url}`);
            await page.waitForLoadState('domcontentloaded');
            
            // Check page status
            const status = await page.locator('body').evaluate(el => {
                const text = el.textContent.toLowerCase();
                if (text.includes('404') || text.includes('not found')) {
                    return '404';
                } else if (text.includes('login') || text.includes('sign in')) {
                    return 'Login Required';
                } else if (text.includes('event') || text.includes('community')) {
                    return 'OK';
                }
                return 'Unknown';
            });
            
            console.log(`${testPage.name}: ${status === 'OK' ? '✅' : '❌'} ${status}`);
            
            // If OK, check for form elements
            if (status === 'OK' && testPage.url.includes('add')) {
                const hasForm = await page.locator('form, input[type="text"], [tribe_community_events]').count() > 0;
                console.log(`  └─ Has form elements: ${hasForm ? '✅' : '❌'}`);
            }
        }
        
        console.log('');
        
        // 4. Check if we can see the dashboard
        console.log('4️⃣ Checking trainer dashboard...');
        await page.goto(`${BASE_URL}/trainer/dashboard/`);
        const dashboardOk = await page.locator('.hvac-dashboard-header, h1').first().isVisible();
        console.log(`Trainer Dashboard: ${dashboardOk ? '✅ Accessible' : '❌ Not found'}`);
        
        console.log('');
        
        // 5. Try to create an event via our custom page
        console.log('5️⃣ Testing event creation on custom page...');
        await page.goto(`${BASE_URL}/trainer/events/create/`);
        await page.waitForLoadState('networkidle');
        
        // Check what's on the page
        const pageContent = await page.locator('body').textContent();
        if (pageContent.includes('404')) {
            console.log('❌ Custom create page returns 404');
        } else if (pageContent.includes('iframe')) {
            console.log('✅ Custom page with iframe found');
            
            // Check iframe content
            const iframe = await page.$('iframe#tec-create-frame');
            if (iframe) {
                console.log('✅ TEC iframe present');
            }
        } else if (pageContent.includes('[tribe_community_events]')) {
            console.log('⚠️  Shortcode not rendering - may need TEC configuration');
        } else {
            console.log('✅ Page loaded (check content)');
        }
        
    } catch (error) {
        console.error('❌ Error:', error.message);
    } finally {
        await browser.close();
    }
    
    console.log('\n📊 Summary:');
    console.log('- You are authenticated as a trainer');
    console.log('- Check which URLs are working above');
    console.log('- If TEC URLs return 404, Community Events pages may need creation');
    console.log('- If shortcodes show as text, TEC may need configuration');
}

runTest();