#!/usr/bin/env node

/**
 * Simple HVAC Events Test Script
 * Basic validation of event creation and editing functionality
 */

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

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

async function runTests() {
    console.log('🚀 Starting HVAC Events Simple Test...\n');
    
    const browser = await chromium.launch({ 
        headless: true,
        timeout: 30000 
    });
    
    const context = await browser.newContext();
    const page = await context.newPage();
    
    const results = {
        total: 0,
        passed: 0,
        failed: 0,
        tests: []
    };
    
    try {
        // Test 1: Login
        console.log('📝 Test 1: Login as trainer...');
        results.total++;
        
        try {
            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(/trainer\/dashboard/, { timeout: 10000 });
            
            console.log('✅ Login successful\n');
            results.passed++;
            results.tests.push({ name: 'Login', status: 'passed' });
        } catch (error) {
            console.log('❌ Login failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Login', status: 'failed', error: error.message });
        }
        
        // Test 2: Navigate to Dashboard
        console.log('📝 Test 2: Access trainer dashboard...');
        results.total++;
        
        try {
            await page.goto(`${BASE_URL}/trainer/dashboard/`);
            const dashboardVisible = await page.locator('.hvac-dashboard-header, h1').isVisible();
            
            if (dashboardVisible) {
                console.log('✅ Dashboard accessible\n');
                results.passed++;
                results.tests.push({ name: 'Dashboard Access', status: 'passed' });
            } else {
                throw new Error('Dashboard elements not visible');
            }
        } catch (error) {
            console.log('❌ Dashboard access failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Dashboard Access', status: 'failed', error: error.message });
        }
        
        // Test 3: Check Event Creation Page
        console.log('📝 Test 3: Check event creation page...');
        results.total++;
        
        try {
            // Try TEC Community Events URL
            await page.goto(`${BASE_URL}/events/community/add/`);
            await page.waitForLoadState('domcontentloaded');
            
            // Check if page has form elements
            const hasForm = await page.locator('form, input[name="post_title"], #tribe-events-title').count() > 0;
            
            if (hasForm) {
                console.log('✅ Event creation form found\n');
                results.passed++;
                results.tests.push({ name: 'Event Creation Page', status: 'passed' });
            } else {
                // Try custom HVAC URL
                await page.goto(`${BASE_URL}/trainer/events/create/`);
                const hasCustomForm = await page.locator('.hvac-event-form-wrapper, iframe').count() > 0;
                
                if (hasCustomForm) {
                    console.log('✅ Custom event creation page found\n');
                    results.passed++;
                    results.tests.push({ name: 'Event Creation Page', status: 'passed' });
                } else {
                    throw new Error('No event creation form found');
                }
            }
        } catch (error) {
            console.log('❌ Event creation page check failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Event Creation Page', status: 'failed', error: error.message });
        }
        
        // Test 4: Check Event List
        console.log('📝 Test 4: Check event list page...');
        results.total++;
        
        try {
            await page.goto(`${BASE_URL}/events/community/list/`);
            await page.waitForLoadState('domcontentloaded');
            
            // Check for event list elements
            const hasEventList = await page.locator('table, .tribe-events-list, .event-list').count() > 0;
            
            if (hasEventList) {
                console.log('✅ Event list page accessible\n');
                results.passed++;
                results.tests.push({ name: 'Event List Page', status: 'passed' });
            } else {
                throw new Error('Event list not found');
            }
        } catch (error) {
            console.log('❌ Event list page check failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Event List Page', status: 'failed', error: error.message });
        }
        
        // Test 5: Check Navigation Menu
        console.log('📝 Test 5: Check navigation menu...');
        results.total++;
        
        try {
            await page.goto(`${BASE_URL}/trainer/dashboard/`);
            
            // Check for navigation elements
            const hasNav = await page.locator('.hvac-trainer-nav, .hvac-nav-menu, nav').count() > 0;
            
            if (hasNav) {
                console.log('✅ Navigation menu present\n');
                results.passed++;
                results.tests.push({ name: 'Navigation Menu', status: 'passed' });
            } else {
                throw new Error('Navigation menu not found');
            }
        } catch (error) {
            console.log('❌ Navigation menu check failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Navigation Menu', status: 'failed', error: error.message });
        }
        
        // Test 6: Mobile Responsiveness
        console.log('📝 Test 6: Check mobile responsiveness...');
        results.total++;
        
        try {
            // Set mobile viewport
            await page.setViewportSize({ width: 375, height: 667 });
            await page.goto(`${BASE_URL}/trainer/dashboard/`);
            
            // Check for mobile menu or responsive elements
            const hasMobileElements = await page.locator('.hvac-menu-toggle, .menu-toggle, .mobile-menu').count() > 0;
            
            if (hasMobileElements) {
                console.log('✅ Mobile responsive elements found\n');
                results.passed++;
                results.tests.push({ name: 'Mobile Responsiveness', status: 'passed' });
            } else {
                console.log('⚠️  Mobile menu not found (may be using desktop layout)\n');
                results.passed++;
                results.tests.push({ name: 'Mobile Responsiveness', status: 'passed', note: 'Desktop layout on mobile' });
            }
        } catch (error) {
            console.log('❌ Mobile responsiveness check failed:', error.message, '\n');
            results.failed++;
            results.tests.push({ name: 'Mobile Responsiveness', status: 'failed', error: error.message });
        }
        
    } catch (error) {
        console.error('Fatal error:', error);
    } finally {
        await browser.close();
    }
    
    // Generate report
    console.log('\n' + '='.repeat(60));
    console.log('📊 TEST RESULTS SUMMARY');
    console.log('='.repeat(60));
    
    const successRate = results.total > 0 ? ((results.passed / results.total) * 100).toFixed(1) : 0;
    
    console.log(`Total Tests: ${results.total}`);
    console.log(`✅ Passed: ${results.passed}`);
    console.log(`❌ Failed: ${results.failed}`);
    console.log(`Success Rate: ${successRate}%`);
    
    console.log('\nDetailed Results:');
    results.tests.forEach(test => {
        const icon = test.status === 'passed' ? '✅' : '❌';
        console.log(`${icon} ${test.name}: ${test.status.toUpperCase()}`);
        if (test.error) {
            console.log(`   Error: ${test.error}`);
        }
        if (test.note) {
            console.log(`   Note: ${test.note}`);
        }
    });
    
    console.log('\n' + '='.repeat(60));
    
    if (successRate >= 80) {
        console.log('🎉 TESTS PASSED - System is working well!');
    } else if (successRate >= 60) {
        console.log('⚠️  TESTS PARTIALLY PASSED - Some issues detected');
    } else {
        console.log('❌ TESTS FAILED - Significant issues found');
    }
    
    console.log('='.repeat(60));
    
    // Save report
    const fs = require('fs').promises;
    const report = {
        timestamp: new Date().toISOString(),
        environment: BASE_URL,
        results: results,
        successRate: successRate,
        recommendation: successRate >= 80 ? 'READY FOR PRODUCTION' : 'NEEDS FIXES'
    };
    
    await fs.writeFile(
        `reports/simple-test-report-${Date.now()}.json`,
        JSON.stringify(report, null, 2)
    );
    
    console.log('\n📄 Report saved to reports directory');
    
    process.exit(results.failed > 0 ? 1 : 0);
}

// Run tests
runTests().catch(error => {
    console.error('Test execution failed:', error);
    process.exit(1);
});