#!/usr/bin/env node

/**
 * Test HVAC Custom Event Pages
 * Focus on our working integrated pages
 */

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

const BASE_URL = 'https://upskill-staging.measurequick.com';
const CREDENTIALS = {
    email: 'test_trainer@example.com',
    password: 'TestTrainer123!'
};

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

async function testEventCreation(page) {
    console.log('\n📝 Testing Event Creation Page...');
    
    await page.goto(`${BASE_URL}/trainer/events/create/`);
    await page.waitForLoadState('networkidle', { timeout: 15000 });
    
    await takeScreenshot(page, 'create-page');
    
    // Check page content
    const pageText = await page.locator('body').textContent();
    
    // Check for iframe
    const iframe = await page.$('iframe#tec-create-frame, iframe');
    if (iframe) {
        console.log('✅ Found TEC iframe');
        
        // Try to interact with iframe content
        try {
            const frame = await iframe.contentFrame();
            await frame.waitForLoadState('domcontentloaded');
            
            // Look for form elements in iframe
            const titleField = await frame.$('input[name="post_title"], #EventTitle, input[type="text"]');
            if (titleField) {
                console.log('✅ Found title field in iframe');
                await titleField.fill('Test Event from HVAC Page');
                console.log('✅ Filled title field');
            } else {
                console.log('❌ No title field found in iframe');
            }
            
            await takeScreenshot(page, 'iframe-content');
        } catch (error) {
            console.log('⚠️ Could not access iframe content:', error.message);
        }
    } else if (pageText.includes('[tribe_community_events]')) {
        console.log('❌ Shortcode not rendering');
    } else {
        // Look for form elements directly on page
        const forms = await page.$$('form');
        console.log(`Found ${forms.length} forms on page`);
        
        if (forms.length > 0) {
            console.log('✅ Form elements present');
            
            // Try to fill form
            const titleField = await page.$('input[name="post_title"], #EventTitle, input[name="EventTitle"]');
            if (titleField) {
                await titleField.fill('Test Event Direct');
                console.log('✅ Filled title field directly');
            }
        }
    }
}

async function testEventList(page) {
    console.log('\n📋 Testing Event List Page...');
    
    await page.goto(`${BASE_URL}/trainer/events/`);
    await page.waitForLoadState('domcontentloaded');
    
    await takeScreenshot(page, 'events-list');
    
    // Check for events
    const events = await page.$$('.tribe-event, .type-tribe_events, article, tr, .event-item');
    console.log(`Found ${events.length} event elements`);
    
    if (events.length > 0) {
        console.log('✅ Events displayed');
        
        // Look for edit links
        const editLinks = await page.$$('a[href*="edit"]');
        console.log(`Found ${editLinks.length} edit links`);
        
        if (editLinks.length > 0) {
            // Click first edit link
            const firstEdit = editLinks[0];
            const editHref = await firstEdit.getAttribute('href');
            console.log(`First edit link: ${editHref}`);
            
            await firstEdit.click();
            await page.waitForLoadState('networkidle');
            await takeScreenshot(page, 'edit-page');
            
            console.log('✅ Navigated to edit page');
        }
    } else {
        // Check if it's showing "no events" message
        const pageText = await page.locator('body').textContent();
        if (pageText.includes('No events') || pageText.includes('no events')) {
            console.log('⚠️ No events message (expected if no events created)');
        } else {
            console.log('❌ No events found and no message');
        }
    }
}

async function createTestEvent(page) {
    console.log('\n🆕 Attempting to Create Test Event...');
    
    await page.goto(`${BASE_URL}/trainer/events/create/`);
    await page.waitForLoadState('networkidle');
    
    // Check if we're in an iframe situation
    const iframe = await page.$('iframe');
    
    if (iframe) {
        console.log('Working with iframe...');
        const frame = await iframe.contentFrame();
        
        // Wait for frame to load
        await frame.waitForLoadState('domcontentloaded');
        
        // Try different selectors for the title field
        const selectors = [
            'input[name="post_title"]',
            '#EventTitle',
            'input[name="EventTitle"]',
            'input[placeholder*="title"]',
            'input[type="text"]:first-of-type'
        ];
        
        for (const selector of selectors) {
            const field = await frame.$(selector);
            if (field) {
                console.log(`Found field with selector: ${selector}`);
                await field.fill(`HVAC Test Event ${Date.now()}`);
                console.log('✅ Filled title');
                break;
            }
        }
        
        // Try to find and click submit
        const submitBtn = await frame.$('button[type="submit"], input[type="submit"], .tribe-button-primary');
        if (submitBtn) {
            console.log('Found submit button, clicking...');
            await submitBtn.click();
            await page.waitForTimeout(5000);
            
            const currentUrl = page.url();
            console.log(`After submit URL: ${currentUrl}`);
            
            if (currentUrl.includes('list') || currentUrl.includes('success')) {
                console.log('✅ Event created!');
            }
        }
    } else {
        console.log('No iframe, working directly with page...');
        // Direct form interaction
        const titleField = await page.$('input[name="post_title"], #EventTitle');
        if (titleField) {
            await titleField.fill(`Direct Test Event ${Date.now()}`);
            console.log('✅ Filled title directly');
            
            const submitBtn = await page.$('button[type="submit"], input[type="submit"]');
            if (submitBtn) {
                await submitBtn.click();
                await page.waitForTimeout(5000);
                console.log('Submitted form');
            }
        }
    }
    
    await takeScreenshot(page, 'after-create-attempt');
}

async function runTests() {
    console.log('🚀 HVAC Custom Event Pages Test\n');
    console.log('=' .repeat(50));
    
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    
    try {
        // Login
        console.log('🔐 Logging in...');
        await page.goto(`${BASE_URL}/wp-login.php`);
        await page.fill('#user_login', CREDENTIALS.email);
        await page.fill('#user_pass', CREDENTIALS.password);
        await page.click('#wp-submit');
        await page.waitForURL(/dashboard/);
        console.log('✅ Logged in');
        
        // Test each page
        await testEventCreation(page);
        await testEventList(page);
        await createTestEvent(page);
        
    } catch (error) {
        console.error('❌ Error:', error.message);
        await takeScreenshot(page, 'error');
    } finally {
        await browser.close();
    }
    
    console.log('\n' + '=' .repeat(50));
    console.log('✅ Test Complete!');
    console.log('Check screenshots/ directory for visual results');
}

runTests();