/**
 * Test direct access to see what content is returned
 */

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

async function testDirectAccess() {
    console.log('🔍 Testing Direct Access to Edit Page...\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 = 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Login first
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        
        const submitButton = await page.$('input[type="submit"]');
        if (submitButton) {
            await Promise.all([
                page.waitForNavigation({ waitUntil: 'networkidle' }),
                submitButton.click()
            ]);
        }
        
        console.log('✅ Logged in\n');
        
        // Step 2: Go directly to edit page
        console.log('2️⃣ Navigating to edit page...');
        const targetUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        console.log('   Target URL:', targetUrl);
        await page.goto(targetUrl);
        await page.waitForLoadState('networkidle');
        
        const finalUrl = page.url();
        console.log('   Final URL:', finalUrl);
        if (finalUrl !== targetUrl) {
            console.log('   ⚠️ URL redirect detected!');
        }
        
        // Step 3: Analyze page content
        console.log('3️⃣ Analyzing page content...\n');
        
        // Get page HTML
        const html = await page.content();
        
        // Check for various markers
        const checks = [
            { marker: '<!-- Custom Event Edit Template Loaded Successfully -->', name: 'Custom template marker' },
            { marker: 'hvac-event-edit-wrapper', name: 'Event edit wrapper class' },
            { marker: 'hvac-event-form', name: 'Event form class' },
            { marker: 'HVAC_Custom_Event_Edit', name: 'PHP class reference' },
            { marker: 'hvac_event_nonce', name: 'Event nonce field' },
            { marker: 'EventStartDate', name: 'Event start date field' },
            { marker: 'post_title', name: 'Post title field' },
            { marker: 'tribe-community-events', name: 'TEC form (should NOT be present)' }
        ];
        
        for (const check of checks) {
            const found = html.includes(check.marker);
            console.log(`   ${found ? '✅' : '❌'} ${check.name}`);
        }
        
        // Check what's in the main content area
        console.log('\n4️⃣ Main content area:');
        const mainContent = await page.$eval('#main, .site-main, [role="main"], .ast-container', 
            el => el ? el.innerHTML.substring(0, 500) : 'Main content not found'
        ).catch(() => 'Could not get main content');
        
        console.log(mainContent);
        
        // Take screenshot
        await page.screenshot({ 
            path: `direct-access-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-direct-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

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