/**
 * Test the CORRECT TEC Community Events 5.x plugin
 */

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('🚀 TESTING CORRECT TEC COMMUNITY EVENTS 5.x');
    console.log('=' .repeat(50));
    console.log('Time:', new Date().toLocaleString());
    console.log('=' .repeat(50) + '\n');
    
    try {
        await loginAsTrainer(page);
        
        // Test 1: Check the standard TEC Community Events URL
        console.log('📝 TEST 1: STANDARD TEC COMMUNITY URL');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/events/community/add', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const standardUrlCheck = await page.evaluate(() => {
            return {
                url: window.location.pathname,
                hasForm: !!document.querySelector('form#tribe-community-events'),
                hasTitleField: !!document.querySelector('input[name="post_title"], #title'),
                hasContentField: !!document.querySelector('textarea[name="post_content"], #tcepostcontent'),
                hasDateFields: !!document.querySelector('input[name="EventStartDate"], .tribe-datepicker'),
                formCount: document.querySelectorAll('form').length,
                inputCount: document.querySelectorAll('input:not([type="hidden"])').length,
                textareaCount: document.querySelectorAll('textarea').length
            };
        });
        
        console.log('   URL:', standardUrlCheck.url);
        console.log('   Has TEC form:', standardUrlCheck.hasForm ? '✅' : '❌');
        console.log('   Title field:', standardUrlCheck.hasTitleField ? '✅' : '❌');
        console.log('   Content field:', standardUrlCheck.hasContentField ? '✅' : '❌');
        console.log('   Date fields:', standardUrlCheck.hasDateFields ? '✅' : '❌');
        console.log('   Total forms:', standardUrlCheck.formCount);
        console.log('   Visible inputs:', standardUrlCheck.inputCount);
        console.log('   Textareas:', standardUrlCheck.textareaCount);
        
        // Test 2: Check edit URL with event ID
        console.log('\n📝 TEST 2: TEC EDIT EVENT URL');
        console.log('-'.repeat(40));
        
        // First, let's check if there are any existing events
        await page.goto('https://upskill-staging.measurequick.com/events/community/list', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const eventsList = await page.evaluate(() => {
            const events = [];
            document.querySelectorAll('.tribe-community-events-list a[href*="event_id"]').forEach(link => {
                const href = link.getAttribute('href');
                const match = href.match(/event_id=(\d+)/);
                if (match) {
                    events.push({
                        id: match[1],
                        title: link.textContent.trim()
                    });
                }
            });
            return events;
        });
        
        console.log('   Found events:', eventsList.length);
        if (eventsList.length > 0) {
            console.log('   First event ID:', eventsList[0].id);
            
            // Try to edit the first event
            await page.goto(`https://upskill-staging.measurequick.com/events/community/edit?event_id=${eventsList[0].id}`, {
                waitUntil: 'networkidle',
                timeout: 30000
            });
            
            const editCheck = await page.evaluate(() => {
                return {
                    hasForm: !!document.querySelector('form#tribe-community-events'),
                    titleValue: document.querySelector('input[name="post_title"], #title')?.value || '',
                    hasContent: !!document.querySelector('textarea[name="post_content"], #tcepostcontent')?.value
                };
            });
            
            console.log('   Edit form present:', editCheck.hasForm ? '✅' : '❌');
            console.log('   Title populated:', editCheck.titleValue ? '✅' : '❌');
            console.log('   Content populated:', editCheck.hasContent ? '✅' : '❌');
        }
        
        // Test 3: Check our custom pages with correct shortcode
        console.log('\n📝 TEST 3: OUR CUSTOM PAGES');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const managePageCheck = await page.evaluate(() => {
            return {
                url: window.location.pathname,
                hasForm: !!document.querySelector('form'),
                formId: document.querySelector('form')?.id || 'none',
                hasSubmitButton: !!document.querySelector('input[type="submit"], button[type="submit"]'),
                visibleInputs: document.querySelectorAll('input:not([type="hidden"]):not([type="submit"])').length
            };
        });
        
        console.log('   Manage page URL:', managePageCheck.url);
        console.log('   Has form:', managePageCheck.hasForm ? '✅' : '❌');
        console.log('   Form ID:', managePageCheck.formId);
        console.log('   Submit button:', managePageCheck.hasSubmitButton ? '✅' : '❌');
        console.log('   Visible input fields:', managePageCheck.visibleInputs);
        
        // Test 4: Check what shortcodes are available
        console.log('\n📝 TEST 4: AVAILABLE SHORTCODES');
        console.log('-'.repeat(40));
        
        const shortcodeTest = await page.evaluate(() => {
            // Check if TEC Community Events shortcodes are registered
            const tests = {
                tribe_community_events: typeof window.tribe_community_events !== 'undefined',
                tribe_ce: typeof window.tribe_ce !== 'undefined',
                hasTribeGlobal: typeof window.tribe !== 'undefined'
            };
            
            // Check for TEC scripts
            const scripts = [];
            document.querySelectorAll('script[src*="tribe"], script[src*="events"]').forEach(script => {
                const src = script.src;
                if (src.includes('community')) {
                    scripts.push(src.split('/').pop());
                }
            });
            
            return {
                ...tests,
                communityScripts: scripts
            };
        });
        
        console.log('   tribe_community_events global:', shortcodeTest.tribe_community_events ? '✅' : '❌');
        console.log('   tribe_ce global:', shortcodeTest.tribe_ce ? '✅' : '❌');
        console.log('   tribe global object:', shortcodeTest.hasTribeGlobal ? '✅' : '❌');
        console.log('   Community scripts loaded:', shortcodeTest.communityScripts.length);
        if (shortcodeTest.communityScripts.length > 0) {
            shortcodeTest.communityScripts.forEach(script => {
                console.log('     -', script);
            });
        }
        
        // Take screenshots
        await page.goto('https://upskill-staging.measurequick.com/events/community/add');
        await page.screenshot({ path: 'tec-community-add.png', fullPage: true });
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.screenshot({ path: 'trainer-manage-event.png', fullPage: true });
        
        console.log('\n📸 Screenshots saved:');
        console.log('   - tec-community-add.png');
        console.log('   - trainer-manage-event.png');
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
    } finally {
        await browser.close();
        console.log('\n✅ Test complete');
    }
})();