/**
 * Test TEC Shortcode Directly
 * 
 * Tests if the TEC shortcode works when called directly
 */

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

async function testTecShortcodeDirect() {
    console.log('🧪 Testing TEC Shortcode Directly...');
    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();
        
        // 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: Check if TEC is installed by looking for Events menu
        console.log('\n📝 Step 2: Checking for Events in navigation...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/dashboard/');
        await page.waitForTimeout(2000);
        
        const hasEventsLink = await page.evaluate(() => {
            const links = document.querySelectorAll('a');
            for (const link of links) {
                const text = link.textContent.toLowerCase();
                const href = link.href.toLowerCase();
                if ((text.includes('event') || href.includes('event')) && 
                    (text.includes('add') || text.includes('create') || text.includes('manage'))) {
                    console.log(`Found event link: ${link.textContent} - ${link.href}`);
                    return true;
                }
            }
            return false;
        });
        
        console.log(`Events link found: ${hasEventsLink ? '✅ Yes' : '❌ No'}`);
        
        // Step 3: Try TEC default community events URLs
        console.log('\n📝 Step 3: Testing TEC default URLs...');
        
        const tecDefaultUrls = [
            '/events/community/list/',
            '/events/community/add/',
            '/community/events/',
            '/submit-event/',
            '/my-events/'
        ];
        
        for (const path of tecDefaultUrls) {
            const url = `https://upskill-staging.measurequick.com${path}`;
            console.log(`\nTrying: ${url}`);
            
            await page.goto(url, { waitUntil: 'networkidle' });
            await page.waitForTimeout(1000);
            
            // Check response
            const response = await page.evaluate(() => {
                const status = {
                    is404: document.body.textContent.includes('404') || 
                           document.title.includes('404'),
                    hasForm: !!document.querySelector('#tribe-community-events-form, .tribe-community-events form'),
                    hasEventList: !!document.querySelector('.tribe-events-list, .tribe-events-community-list'),
                    bodyText: document.body.textContent.substring(0, 200)
                };
                return status;
            });
            
            if (response.is404) {
                console.log('  ❌ 404 Not Found');
            } else if (response.hasForm) {
                console.log('  ✅ TEC Form Found!');
                
                // Take screenshot
                await page.screenshot({ 
                    path: `/home/ben/dev/upskill-event-manager/test-results/tec-form-found-${Date.now()}.png`,
                    fullPage: true 
                });
                
                return {
                    success: true,
                    workingUrl: url
                };
            } else if (response.hasEventList) {
                console.log('  📋 Event List Found');
            } else {
                console.log('  ⚠️ Page exists but no TEC content');
            }
        }
        
        // Step 4: Check if TEC plugin is listed in page source
        console.log('\n📝 Step 4: Checking for TEC plugin in page source...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        
        const tecCheck = await page.evaluate(() => {
            const checks = {
                hasTribeScripts: false,
                hasTribeStyles: false,
                hasTribeClasses: false,
                scripts: [],
                styles: []
            };
            
            // Check for Tribe scripts
            document.querySelectorAll('script[src]').forEach(script => {
                if (script.src.includes('tribe') || script.src.includes('events-calendar')) {
                    checks.hasTribeScripts = true;
                    checks.scripts.push(script.src.split('/').pop());
                }
            });
            
            // Check for Tribe styles
            document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
                if (link.href.includes('tribe') || link.href.includes('events-calendar')) {
                    checks.hasTribeStyles = true;
                    checks.styles.push(link.href.split('/').pop());
                }
            });
            
            // Check for Tribe classes in body
            checks.hasTribeClasses = document.body.className.includes('tribe');
            
            return checks;
        });
        
        console.log('\n📊 TEC Plugin Check:');
        console.log(`Has Tribe Scripts: ${tecCheck.hasTribeScripts ? '✅' : '❌'}`);
        console.log(`Has Tribe Styles: ${tecCheck.hasTribeStyles ? '✅' : '❌'}`);
        console.log(`Has Tribe Classes: ${tecCheck.hasTribeClasses ? '✅' : '❌'}`);
        
        if (tecCheck.scripts.length > 0) {
            console.log('Tribe Scripts:', tecCheck.scripts.join(', '));
        }
        if (tecCheck.styles.length > 0) {
            console.log('Tribe Styles:', tecCheck.styles.join(', '));
        }
        
        // Step 5: Check error messages on manage page
        console.log('\n📝 Step 5: Checking for error messages...');
        
        const errorCheck = await page.evaluate(() => {
            const content = document.querySelector('.hvac-page-content');
            if (content) {
                const text = content.textContent;
                if (text.includes('Event management requires')) {
                    return 'TEC_NOT_INSTALLED';
                }
                if (text.includes('permission')) {
                    return 'PERMISSION_DENIED';
                }
                if (text.includes('shortcode')) {
                    return 'SHORTCODE_ERROR';
                }
                if (text.trim() === '') {
                    return 'EMPTY_CONTENT';
                }
                return 'UNKNOWN';
            }
            return 'NO_CONTENT_DIV';
        });
        
        console.log(`\n⚠️ Error Status: ${errorCheck}`);
        
        if (errorCheck === 'TEC_NOT_INSTALLED') {
            console.log('❌ The Events Calendar Community Events is NOT installed/active');
            console.log('💡 This is why the form is not showing!');
        } else if (errorCheck === 'EMPTY_CONTENT') {
            console.log('❌ The shortcode is not outputting any content');
            console.log('💡 The shortcode might not be on the page');
        }
        
        // Final summary
        console.log('\n' + '='.repeat(60));
        console.log('📊 TEC Shortcode Test Summary:');
        console.log('='.repeat(60));
        
        if (!tecCheck.hasTribeScripts && !tecCheck.hasTribeStyles) {
            console.log('❌ The Events Calendar is NOT active on the site');
            console.log('\n💡 Solution: Install and activate The Events Calendar Community Events plugin');
        } else if (errorCheck === 'EMPTY_CONTENT') {
            console.log('❌ The page has no content (shortcode not present)');
            console.log('\n💡 Solution: Add [hvac_manage_event] shortcode to page ID 5344');
        } else {
            console.log('⚠️ TEC is installed but form not rendering');
            console.log('\n💡 Possible issues:');
            console.log('  - Community Events add-on not active');
            console.log('  - User permissions issue');
            console.log('  - TEC configuration issue');
        }
        
        return {
            success: false,
            errorCheck: errorCheck,
            tecInstalled: tecCheck.hasTribeScripts || tecCheck.hasTribeStyles
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testTecShortcodeDirect()
        .then(result => {
            console.log('\n🏁 TEC Shortcode Test Complete');
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Test runner failed:', error);
            process.exit(1);
        });
}

module.exports = { testTecShortcodeDirect };