/**
 * Debug Shortcode Output
 * 
 * See exactly what the hvac_manage_event shortcode is outputting
 */

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

async function debugShortcodeOutput() {
    console.log('🔍 Debugging Shortcode Output...');
    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();
        
        // Login as trainer
        console.log('\n📝 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');
        
        // Navigate to manage event page
        console.log('\n📝 Navigating to manage event page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.waitForTimeout(3000);
        
        // Get the actual content
        const pageContent = await page.evaluate(() => {
            const analysis = {
                pageContentHTML: '',
                pageContentText: '',
                hasShortcodeComment: false,
                errorMessages: [],
                formElements: []
            };
            
            // Get the main content area
            const contentDiv = document.querySelector('.hvac-page-content');
            if (contentDiv) {
                analysis.pageContentHTML = contentDiv.innerHTML;
                analysis.pageContentText = contentDiv.textContent.trim();
                
                // Check for WordPress shortcode comments
                if (contentDiv.innerHTML.includes('wp:shortcode')) {
                    analysis.hasShortcodeComment = true;
                }
            }
            
            // Check for any error messages
            const errorSelectors = ['.error', '.notice', '.hvac-error', '.tribe-error'];
            errorSelectors.forEach(selector => {
                const error = document.querySelector(selector);
                if (error) {
                    analysis.errorMessages.push(error.textContent.trim());
                }
            });
            
            // Check for form elements
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                analysis.formElements.push({
                    id: form.id || 'no-id',
                    action: form.action,
                    classes: form.className
                });
            });
            
            return analysis;
        });
        
        console.log('\n📊 Page Content Analysis:');
        console.log('='.repeat(60));
        
        console.log('\n📝 Content Text:');
        console.log(pageContent.pageContentText || '(EMPTY)');
        
        console.log('\n📝 Content HTML (first 1000 chars):');
        console.log(pageContent.pageContentHTML.substring(0, 1000) || '(EMPTY)');
        
        if (pageContent.hasShortcodeComment) {
            console.log('\n⚠️ Found WordPress shortcode HTML comment - shortcode might not be processed');
        }
        
        if (pageContent.errorMessages.length > 0) {
            console.log('\n❌ Error Messages Found:');
            pageContent.errorMessages.forEach(msg => console.log(`  - ${msg}`));
        }
        
        if (pageContent.formElements.length > 0) {
            console.log('\n📋 Forms Found:');
            pageContent.formElements.forEach(form => {
                console.log(`  - ID: ${form.id}, Action: ${form.action}`);
            });
        }
        
        // Check if shortcode exists in WordPress
        console.log('\n📝 Checking if shortcode is registered...');
        
        const shortcodeCheck = await page.evaluate(() => {
            // Try to check if the shortcode would output something
            const testDiv = document.createElement('div');
            testDiv.innerHTML = '[hvac_manage_event]';
            document.body.appendChild(testDiv);
            
            // See if it got processed (would change if shortcode exists)
            const wasProcessed = testDiv.innerHTML !== '[hvac_manage_event]';
            document.body.removeChild(testDiv);
            
            return wasProcessed;
        });
        
        console.log(`Shortcode processed by browser: ${shortcodeCheck ? '✅ Yes' : '❌ No'}`);
        
        // Check what's in the raw page source
        const pageSource = await page.content();
        const hasHvacShortcode = pageSource.includes('[hvac_manage_event]');
        const hasTribeShortcode = pageSource.includes('[tribe_community_events');
        
        console.log(`\n📋 Shortcodes in page source:`);
        console.log(`  [hvac_manage_event]: ${hasHvacShortcode ? '✅ Found' : '❌ Not found'}`);
        console.log(`  [tribe_community_events]: ${hasTribeShortcode ? '✅ Found' : '❌ Not found'}`);
        
        // Now check with event_id parameter
        console.log('\n📝 Testing with event_id parameter...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/?event_id=6078');
        await page.waitForTimeout(2000);
        
        const withEventId = await page.evaluate(() => {
            const content = document.querySelector('.hvac-page-content');
            return {
                hasContent: content && content.textContent.trim().length > 0,
                contentSnippet: content ? content.textContent.substring(0, 200) : ''
            };
        });
        
        console.log(`\nWith event_id=6078:`);
        console.log(`  Has content: ${withEventId.hasContent ? '✅ Yes' : '❌ No'}`);
        if (withEventId.contentSnippet) {
            console.log(`  Content: ${withEventId.contentSnippet}`);
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/shortcode-output-debug.png',
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
        // Final diagnosis
        console.log('\n' + '='.repeat(60));
        console.log('🔬 DIAGNOSIS:');
        console.log('='.repeat(60));
        
        if (!hasHvacShortcode && !hasTribeShortcode) {
            console.log('❌ No shortcode found in page content');
            console.log('💡 Solution: Add [hvac_manage_event] to page content');
        } else if (pageContent.pageContentText.includes('Event management requires')) {
            console.log('❌ TEC Community Events plugin not active');
            console.log('💡 Solution: Install/activate The Events Calendar Community Events');
        } else if (pageContent.pageContentHTML.includes('<!-- wp:shortcode -->')) {
            console.log('❌ Shortcode saved as Gutenberg block comment');
            console.log('💡 Solution: Update page to use plain shortcode text');
        } else if (pageContent.pageContentText === '') {
            console.log('❌ Shortcode returning empty content');
            console.log('💡 Possible issues:');
            console.log('  - TEC Community shortcode not working');
            console.log('  - Permissions issue');
            console.log('  - Need to check TEC settings');
        } else {
            console.log('⚠️ Unknown issue - content exists but no form');
            console.log('Content snippet:', pageContent.pageContentText.substring(0, 200));
        }
        
        return {
            success: false,
            hasContent: pageContent.pageContentText.length > 0,
            hasShortcode: hasHvacShortcode || hasTribeShortcode
        };
        
    } catch (error) {
        console.error('❌ Debug failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

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

module.exports = { debugShortcodeOutput };