#!/usr/bin/env node

/**
 * Simple test to access TEC event edit form
 * Tests the most direct path to editing an event
 */

const { chromium } = require('@playwright/test');
const fs = require('fs').promises;
const { execSync } = require('child_process');

// Configure XWayland display
process.env.DISPLAY = ':0';
try {
    const xauthFile = execSync('ls /run/user/1000/.mutter-Xwaylandauth.* 2>/dev/null | head -n1', { encoding: 'utf8' }).trim();
    if (xauthFile) {
        process.env.XAUTHORITY = xauthFile;
    }
} catch (e) {
    // Continue without XAUTHORITY
}

const CONFIG = {
    baseUrl: 'https://upskill-staging.measurequick.com',
    credentials: {
        username: 'test_admin',
        password: 'TestAdmin2025!'
    }
};

async function screenshot(page, name) {
    await fs.mkdir('screenshots/simple-access', { recursive: true });
    const path = `screenshots/simple-access/${name}-${Date.now()}.png`;
    await page.screenshot({ path, fullPage: true });
    console.log(`📸 Screenshot: ${path}`);
    return path;
}

async function runSimpleAccessTest() {
    console.log('🎯 SIMPLE TEC ACCESS TEST');
    console.log('=' .repeat(70));
    
    const browser = await chromium.launch({ 
        headless: false,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const page = await browser.newPage();
    
    try {
        // Direct approach - go straight to wp-admin
        console.log('\n📝 Logging in via wp-admin...');
        await page.goto(`${CONFIG.baseUrl}/wp-login.php`);
        await page.waitForLoadState('domcontentloaded');
        
        await screenshot(page, '01-login-page');
        
        // Standard WordPress login
        await page.fill('#user_login', CONFIG.credentials.username);
        await page.fill('#user_pass', CONFIG.credentials.password);
        await page.click('#wp-submit');
        
        // Wait for any redirect
        await page.waitForTimeout(3000);
        const currentUrl = page.url();
        console.log(`  Current URL after login: ${currentUrl}`);
        
        if (currentUrl.includes('wp-admin') || currentUrl.includes('dashboard')) {
            console.log('✅ Login successful');
        }
        
        await screenshot(page, '02-after-login');
        
        // Go directly to events list
        console.log('\n📝 Navigating to events list...');
        await page.goto(`${CONFIG.baseUrl}/wp-admin/edit.php?post_type=tribe_events`);
        await page.waitForLoadState('networkidle');
        
        await screenshot(page, '03-events-list');
        
        // Count events
        const eventRows = await page.$$('tbody#the-list tr');
        console.log(`✅ Found ${eventRows.length} events`);
        
        if (eventRows.length > 0) {
            // Get first event title
            const firstTitle = await eventRows[0].$eval('.row-title', el => el.textContent).catch(() => 'Unknown');
            console.log(`  First event: ${firstTitle}`);
            
            // Click edit
            console.log('\n📝 Opening event for editing...');
            const editLink = await page.$('tbody#the-list tr:first-child .row-actions .edit a');
            if (editLink) {
                await editLink.click();
                await page.waitForLoadState('networkidle');
                console.log('✅ Edit form opened');
                
                await screenshot(page, '04-edit-form');
                
                // Quick field check
                console.log('\n📝 Checking key fields...');
                const fields = {
                    'Title': '#title',
                    'Start Date': '#EventStartDate',
                    'End Date': '#EventEndDate',
                    'Cost': '#EventCost',
                    'URL': '#EventURL'
                };
                
                for (const [name, selector] of Object.entries(fields)) {
                    const element = await page.$(selector);
                    if (element && await element.isVisible()) {
                        const value = await element.inputValue().catch(() => '');
                        console.log(`  ✅ ${name}: ${value || '(empty)'}`);
                    } else {
                        console.log(`  ❌ ${name}: Not found`);
                    }
                }
            }
        }
        
    } catch (error) {
        console.error('\n❌ Error:', error.message);
        await screenshot(page, 'error');
    } finally {
        console.log('\n⏱️ Keeping browser open for 5 seconds...');
        await page.waitForTimeout(5000);
        await browser.close();
    }
}

// Run the test
console.log('Starting simple TEC access test...\n');
runSimpleAccessTest().then(() => {
    console.log('\n✅ Test complete');
}).catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});