/**
 * Debug test for custom event edit template loading
 * Tests multiple approaches to identify why template isn't loading
 */

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

async function debugTemplateLoading() {
    console.log('🔍 Debugging Custom Event Edit Template Loading...\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Login with correct credentials
        console.log('1️⃣ Logging in with JoeMedosch credentials...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        await page.fill('input[name="log"]', 'JoeMedosch@gmail.com');
        await page.fill('input[name="pwd"]', 'JoeTrainer2025@');
        
        const submitButton = await page.$('input[type="submit"]') || 
                             await page.$('button[type="submit"]') ||
                             await page.$('#wp-submit');
        if (submitButton) {
            await submitButton.click();
        }
        
        await page.waitForTimeout(3000);
        console.log('✅ Login submitted\n');
        
        // Step 2: Test different URL patterns
        console.log('2️⃣ Testing different URL patterns...\n');
        
        const urlPatterns = [
            '/trainer/event/edit/?event_id=6161',
            '/trainer/event/edit?event_id=6161',
            '/trainer/event/edit/',
            '/trainer/event/edit',
        ];
        
        for (const pattern of urlPatterns) {
            console.log(`Testing: ${pattern}`);
            await page.goto(`${baseUrl}${pattern}`);
            await page.waitForLoadState('networkidle');
            
            // Check what loaded
            const pageTitle = await page.title();
            const customForm = await page.$('.hvac-event-edit-wrapper');
            const tecForm = await page.$('.tribe-community-events');
            const content = await page.content();
            
            console.log(`  Title: ${pageTitle}`);
            console.log(`  Custom form: ${customForm ? '✅ Found' : '❌ Not found'}`);
            console.log(`  TEC form: ${tecForm ? '⚠️ Found' : '✅ Not found'}`);
            
            // Check for specific indicators
            if (content.includes('hvac-event-edit-wrapper')) {
                console.log('  ✅ Custom template HTML detected');
            }
            if (content.includes('404') || content.includes('Page not found')) {
                console.log('  ❌ 404 error');
            }
            if (content.includes('<!-- Custom Event Edit Template -->')) {
                console.log('  ✅ Template comment marker found');
            }
            
            console.log('');
        }
        
        // Step 3: Check page structure
        console.log('3️⃣ Checking page structure at /trainer/event/edit/?event_id=6161...\n');
        await page.goto(`${baseUrl}/trainer/event/edit/?event_id=6161`);
        await page.waitForLoadState('networkidle');
        
        // Check body classes
        const bodyClasses = await page.evaluate(() => document.body.className);
        console.log(`Body classes: ${bodyClasses}`);
        
        // Check for WordPress admin bar
        const adminBar = await page.$('#wpadminbar');
        console.log(`Admin bar: ${adminBar ? 'Present' : 'Not present'}`);
        
        // Check page ID
        const pageId = await page.evaluate(() => {
            const bodyClass = document.body.className;
            const match = bodyClass.match(/page-id-(\d+)/);
            return match ? match[1] : null;
        });
        console.log(`Page ID from body class: ${pageId || 'Not found'}`);
        
        // Check template
        const templateClass = await page.evaluate(() => {
            const bodyClass = document.body.className;
            const match = bodyClass.match(/page-template-([^ ]+)/);
            return match ? match[1] : null;
        });
        console.log(`Template class: ${templateClass || 'Not found'}`);
        
        // Step 4: Check page content structure
        console.log('\n4️⃣ Analyzing page content structure...\n');
        
        // Check for main content area
        const mainContent = await page.$('#main') || await page.$('.site-main') || await page.$('[role="main"]');
        if (mainContent) {
            console.log('✅ Main content area found');
            
            // Get the HTML of main content
            const mainHtml = await mainContent.evaluate(el => el.innerHTML.substring(0, 500));
            console.log('Main content preview:');
            console.log(mainHtml);
        } else {
            console.log('❌ Main content area not found');
        }
        
        // Step 5: Check for form elements
        console.log('\n5️⃣ Checking for form elements...\n');
        
        const formSelectors = {
            'Custom wrapper': '.hvac-event-edit-wrapper',
            'Form element': 'form.hvac-event-form',
            'Title field': '#post_title',
            'Start date': '#EventStartDate',
            'Submit button': 'button[type="submit"]',
            'Nonce field': 'input[name="hvac_event_nonce"]'
        };
        
        for (const [name, selector] of Object.entries(formSelectors)) {
            const element = await page.$(selector);
            console.log(`${name}: ${element ? '✅ Found' : '❌ Not found'}`);
        }
        
        // Step 6: Take screenshot for visual inspection
        console.log('\n6️⃣ Taking screenshot for inspection...\n');
        const timestamp = Date.now();
        await page.screenshot({ 
            path: `template-debug-${timestamp}.png`,
            fullPage: true 
        });
        console.log(`📸 Screenshot saved as template-debug-${timestamp}.png`);
        
        // Step 7: Check console errors
        console.log('\n7️⃣ Checking for console errors...\n');
        page.on('console', msg => {
            if (msg.type() === 'error') {
                console.log(`Console error: ${msg.text()}`);
            }
        });
        
        // Reload to catch any console errors
        await page.reload();
        await page.waitForTimeout(2000);
        
        console.log('\n✅ Debug test complete!');
        
    } catch (error) {
        console.error('\n❌ Debug test failed:', error.message);
        
        await page.screenshot({ 
            path: `template-debug-error-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('📸 Error screenshot saved');
        
        throw error;
    } finally {
        await browser.close();
    }
}

// Run debug test
debugTemplateLoading()
    .then(() => {
        console.log('\n✨ Debug test completed successfully!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n💥 Debug test failed:', error);
        process.exit(1);
    });