/**
 * Test script for verifying the new create/edit event pages with authentication
 * Tests REST API enhancement and field population
 */

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

async function loginAsTrainer(page) {
    console.log('🔐 Logging in as test trainer...');
    
    // Go to login page
    await page.goto('https://upskill-staging.measurequick.com/trainer/training-login/', {
        waitUntil: 'networkidle',
        timeout: 30000
    });
    
    // Fill login form
    await page.fill('#username, #user_login, input[name="log"]', 'test_trainer');
    await page.fill('#password, #user_pass, input[name="pwd"]', 'TestTrainer123!');
    
    // Submit form
    await page.click('input[type="submit"], button[type="submit"]');
    
    // Wait for navigation
    await page.waitForTimeout(3000);
    
    console.log('   Logged in successfully');
}

(async () => {
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    console.log('🔍 Testing Create/Edit Event Pages with Authentication...\n');
    
    try {
        // Login first
        await loginAsTrainer(page);
        
        // Test 1: Check if create-event page exists and renders correctly
        console.log('\n📝 Test 1: Checking create-event page (authenticated)...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const createPageTitle = await page.title();
        console.log(`   Page title: ${createPageTitle}`);
        
        // Check page content
        const pageContent = await page.evaluate(() => {
            return {
                hasH1: document.querySelector('h1')?.textContent,
                hasNotice: document.querySelector('.hvac-form-notice')?.textContent?.trim(),
                hasNavMenu: !!document.querySelector('.hvac-nav-menu, .hvac-trainer-navigation'),
                bodyClasses: document.body.className
            };
        });
        
        console.log(`   H1 Title: "${pageContent.hasH1}"`);
        console.log(`   Notice: ${pageContent.hasNotice ? '"' + pageContent.hasNotice + '"' : 'Not found'}`);
        console.log(`   Navigation menu: ${pageContent.hasNavMenu ? '✅' : '❌'}`);
        console.log(`   Body classes: ${pageContent.bodyClasses}`);
        
        // Check if TEC form is present
        const formCheck = await page.evaluate(() => {
            return {
                hasTribeForm: !!document.querySelector('#tribe-community-events'),
                hasTribeContainer: !!document.querySelector('.tribe-events-community'),
                hasFormTag: !!document.querySelector('form'),
                formAction: document.querySelector('form')?.action,
                formMethod: document.querySelector('form')?.method
            };
        });
        
        console.log('\n   Form presence check:');
        console.log(`     - #tribe-community-events: ${formCheck.hasTribeForm ? '✅' : '❌'}`);
        console.log(`     - .tribe-events-community: ${formCheck.hasTribeContainer ? '✅' : '❌'}`);
        console.log(`     - <form> tag: ${formCheck.hasFormTag ? '✅' : '❌'}`);
        if (formCheck.formAction) {
            console.log(`     - Form action: ${formCheck.formAction}`);
            console.log(`     - Form method: ${formCheck.formMethod}`);
        }
        
        // Check if REST API script is loaded
        const restApiCheck = await page.evaluate(() => {
            return {
                scriptLoaded: typeof window.HVACRestEventSubmission !== 'undefined',
                jQueryLoaded: typeof window.jQuery !== 'undefined',
                hvacAjaxDefined: typeof window.hvac_ajax !== 'undefined'
            };
        });
        
        console.log('\n   Script loading check:');
        console.log(`     - REST API script: ${restApiCheck.scriptLoaded ? '✅' : '❌'}`);
        console.log(`     - jQuery loaded: ${restApiCheck.jQueryLoaded ? '✅' : '❌'}`);
        console.log(`     - hvac_ajax defined: ${restApiCheck.hvacAjaxDefined ? '✅' : '❌'}`);
        
        // Check if excerpt field was added
        const excerptFieldCheck = await page.evaluate(() => {
            const excerptField = document.querySelector('#event_excerpt');
            const excerptSection = document.querySelector('.tribe-section-excerpt');
            
            return {
                hasField: !!excerptField,
                hasSection: !!excerptSection,
                fieldType: excerptField?.tagName,
                fieldName: excerptField?.name
            };
        });
        
        console.log('\n   Excerpt field check:');
        console.log(`     - Excerpt field exists: ${excerptFieldCheck.hasField ? '✅' : '❌'}`);
        console.log(`     - Excerpt section exists: ${excerptFieldCheck.hasSection ? '✅' : '❌'}`);
        if (excerptFieldCheck.hasField) {
            console.log(`     - Field type: ${excerptFieldCheck.fieldType}`);
            console.log(`     - Field name: ${excerptFieldCheck.fieldName}`);
        }
        
        // Check TEC specific elements
        const tecElements = await page.evaluate(() => {
            return {
                postTitle: !!document.querySelector('#post_title, input[name="post_title"]'),
                postContent: !!document.querySelector('#tcepostcontent, #post_content, textarea[name="post_content"]'),
                startDate: !!document.querySelector('input[name="EventStartDate"]'),
                endDate: !!document.querySelector('input[name="EventEndDate"]'),
                startTime: !!document.querySelector('input[name="EventStartTime"]'),
                endTime: !!document.querySelector('input[name="EventEndTime"]'),
                venueSelect: !!document.querySelector('#saved_tribe_venue'),
                organizerSelect: !!document.querySelector('#saved_tribe_organizer'),
                submitButton: !!document.querySelector('button[type="submit"], input[type="submit"]')
            };
        });
        
        console.log('\n   TEC form fields:');
        Object.entries(tecElements).forEach(([field, present]) => {
            console.log(`     - ${field}: ${present ? '✅' : '❌'}`);
        });
        
        // Test 2: Check if edit-event page works
        console.log('\n📝 Test 2: Checking edit-event page (authenticated)...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        // Check for error message
        const editPageNoId = await page.evaluate(() => {
            return {
                hasErrorNotice: !!document.querySelector('.hvac-error-notice'),
                errorText: document.querySelector('.hvac-error-notice p')?.textContent,
                hasBackLink: !!document.querySelector('a[href*="/trainer/event/manage/"]')
            };
        });
        
        console.log(`   Shows error notice: ${editPageNoId.hasErrorNotice ? '✅' : '❌'}`);
        if (editPageNoId.errorText) {
            console.log(`   Error message: "${editPageNoId.errorText}"`);
        }
        console.log(`   Has back link: ${editPageNoId.hasBackLink ? '✅' : '❌'}`);
        
        // Test 3: Check edit page with event_id
        console.log('\n📝 Test 3: Testing edit page with event_id parameter...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=5678', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const editPageWithId = await page.evaluate(() => {
            return {
                hasFormNotice: !!document.querySelector('.hvac-form-notice'),
                noticeText: document.querySelector('.hvac-form-notice p')?.textContent,
                hvacEditEventId: window.hvacEditEventId,
                hasTribeForm: !!document.querySelector('#tribe-community-events'),
                hasForm: !!document.querySelector('form')
            };
        });
        
        console.log(`   Shows form notice: ${editPageWithId.hasFormNotice ? '✅' : '❌'}`);
        if (editPageWithId.noticeText) {
            console.log(`   Notice text: "${editPageWithId.noticeText}"`);
        }
        console.log(`   window.hvacEditEventId: ${editPageWithId.hvacEditEventId}`);
        console.log(`   TEC form present: ${editPageWithId.hasTribeForm ? '✅' : '❌'}`);
        console.log(`   Form tag present: ${editPageWithId.hasForm ? '✅' : '❌'}`);
        
        // Summary
        console.log('\n📊 Summary:');
        const createPageWorks = formCheck.hasTribeForm || formCheck.hasFormTag;
        const restApiLoads = restApiCheck.scriptLoaded;
        const excerptFieldAdded = excerptFieldCheck.hasField;
        const editPageHandlesNoId = editPageNoId.hasErrorNotice;
        const editPageSetsId = editPageWithId.hvacEditEventId === 5678;
        
        console.log(`   ${createPageWorks ? '✅' : '❌'} Create page renders TEC form`);
        console.log(`   ${restApiLoads ? '✅' : '❌'} REST API script loads`);
        console.log(`   ${excerptFieldAdded ? '✅' : '❌'} Excerpt field added`);
        console.log(`   ${editPageHandlesNoId ? '✅' : '❌'} Edit page handles missing event_id`);
        console.log(`   ${editPageSetsId ? '✅' : '❌'} Edit page sets hvacEditEventId`);
        
        const allPassed = createPageWorks && restApiLoads && excerptFieldAdded && 
                         editPageHandlesNoId && editPageSetsId;
        
        console.log(`\n${allPassed ? '✅ All tests passed!' : '⚠️  Some features not working as expected'}`);
        
        // Additional diagnostics if not all passed
        if (!allPassed) {
            console.log('\n🔍 Diagnostics:');
            if (!createPageWorks) {
                console.log('   - TEC form not rendering: Check if TEC Community Events is active');
                console.log('   - Check if shortcode [tribe_community_events] is being processed');
            }
            if (!restApiLoads) {
                console.log('   - REST API script not loading: Check HVAC_Scripts_Styles class');
                console.log('   - Verify script enqueueing for create/edit pages');
            }
            if (!excerptFieldAdded) {
                console.log('   - Excerpt field not added: REST API script may not be initializing');
                console.log('   - Check console for JavaScript errors');
            }
        }
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
        
        // Take screenshot on error
        await page.screenshot({ 
            path: 'authenticated-pages-error.png',
            fullPage: true 
        });
        console.log('📸 Screenshot saved as authenticated-pages-error.png');
    } finally {
        await browser.close();
    }
})();