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

const BASE_URL = 'https://upskill-staging.measurequick.com';

async function testAllFeatures() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1920, height: 1080 } });
  const page = await context.newPage();
  
  console.log('🧪 Testing HVAC Trainer Features on Staging\n');
  console.log('=' . repeat(50));
  
  const results = {
    passed: 0,
    failed: 0,
    tests: []
  };
  
  function logTest(name, passed, details = '') {
    const status = passed ? '✅ PASS' : '❌ FAIL';
    console.log(`${status} ${name}`);
    if (details) console.log(`   ${details}`);
    results.tests.push({ name, passed, details });
    if (passed) results.passed++;
    else results.failed++;
  }
  
  try {
    // Test 1: Registration Form
    console.log('\n📝 Testing Registration Form');
    console.log('-' . repeat(30));
    await page.goto(`${BASE_URL}/trainer-registration/`);
    await page.waitForLoadState('networkidle');
    
    const hasPersonalInfo = await page.locator('h3:has-text("Personal Information")').isVisible();
    const hasOrgInfo = await page.locator('h3:has-text("Training Organization Information")').isVisible();
    const hasVenueInfo = await page.locator('h3:has-text("Training Venue Information")').isVisible();
    const hasOrgLogo = await page.locator('label:has-text("Organization Logo")').isVisible();
    const hasHQFields = await page.locator('#hq_city').isVisible();
    
    logTest('Personal Information section exists', hasPersonalInfo);
    logTest('Training Organization Information section exists', hasOrgInfo);
    logTest('Training Venue Information section exists', hasVenueInfo);
    logTest('Organization Logo field exists', hasOrgLogo);
    logTest('Headquarters fields exist', hasHQFields);
    
    await page.screenshot({ path: 'screenshots/test-01-registration.png', fullPage: true });
    
    // Test 2: Login
    console.log('\n🔐 Testing Authentication');
    console.log('-' . repeat(30));
    await page.goto(`${BASE_URL}/training-login/`);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'TestTrainer123!');
    await page.click('#wp-submit');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(3000);
    
    const isLoggedIn = page.url().includes('/trainer/');
    logTest('Login successful', isLoggedIn, `Redirected to: ${page.url()}`);
    
    // Test 3: Trainer Pages
    console.log('\n📄 Testing Trainer Pages');
    console.log('-' . repeat(30));
    
    const pages = [
      { name: 'Trainer Dashboard', url: '/trainer/dashboard/' },
      { name: 'Venues List', url: '/trainer/venue/list/' },
      { name: 'Venue Manage', url: '/trainer/venue/manage/' },
      { name: 'Profile View', url: '/trainer/profile/' },
      { name: 'Profile Edit', url: '/trainer/profile/edit/' },
      { name: 'Organizers List', url: '/trainer/organizer/list/' },
      { name: 'Organizer Manage', url: '/trainer/organizer/manage/' }
    ];
    
    for (const pageInfo of pages) {
      await page.goto(`${BASE_URL}${pageInfo.url}`);
      await page.waitForLoadState('networkidle');
      
      const finalUrl = page.url();
      const isAccessible = !finalUrl.includes('login');
      const title = await page.title();
      
      logTest(`${pageInfo.name} accessible`, isAccessible, 
        isAccessible ? `Title: ${title}` : 'Redirected to login');
      
      if (isAccessible && pageInfo.name.includes('List')) {
        await page.screenshot({ 
          path: `screenshots/test-${pageInfo.name.toLowerCase().replace(/\s+/g, '-')}.png`, 
          fullPage: true 
        });
      }
    }
    
    // Test 4: Form Functionality
    console.log('\n📋 Testing Form Functionality');
    console.log('-' . repeat(30));
    
    // Test venue creation form
    await page.goto(`${BASE_URL}/trainer/venue/manage/`);
    await page.waitForLoadState('networkidle');
    
    const hasVenueForm = await page.locator('#hvac-venue-form').count() > 0;
    const hasVenueName = await page.locator('#venue_name').count() > 0;
    const hasSubmitButton = await page.locator('button[type="submit"]').count() > 0;
    
    logTest('Venue form exists', hasVenueForm);
    logTest('Venue name field exists', hasVenueName);
    logTest('Submit button exists', hasSubmitButton);
    
    // Test 5: Navigation and UI Elements
    console.log('\n🧭 Testing Navigation Elements');
    console.log('-' . repeat(30));
    
    await page.goto(`${BASE_URL}/trainer/dashboard/`);
    await page.waitForLoadState('networkidle');
    
    // Check for navigation menu
    const hasNavMenu = await page.locator('.hvac-trainer-nav').count() > 0;
    const hasBreadcrumb = await page.locator('.hvac-breadcrumb').count() > 0;
    
    // Check page structure
    const hasHeader = await page.locator('h1, h2').first().count() > 0;
    const hasContent = await page.locator('.entry-content, .page-content, main').count() > 0;
    
    logTest('Navigation menu present', hasNavMenu);
    logTest('Breadcrumb present', hasBreadcrumb);
    logTest('Page has header', hasHeader);
    logTest('Page has content area', hasContent);
    
    // Test 6: AJAX Functionality
    console.log('\n⚡ Testing AJAX Features');
    console.log('-' . repeat(30));
    
    // Check if AJAX scripts are loaded
    const hasAjaxVar = await page.evaluate(() => typeof hvac_ajax !== 'undefined');
    logTest('AJAX variables loaded', hasAjaxVar);
    
  } catch (error) {
    console.error('\n❌ Test Error:', error.message);
    await page.screenshot({ path: 'screenshots/test-error.png', fullPage: true });
  } finally {
    // Summary
    console.log('\n' + '=' . repeat(50));
    console.log('📊 TEST SUMMARY');
    console.log('=' . repeat(50));
    console.log(`Total Tests: ${results.passed + results.failed}`);
    console.log(`✅ Passed: ${results.passed}`);
    console.log(`❌ Failed: ${results.failed}`);
    console.log(`Success Rate: ${Math.round((results.passed / (results.passed + results.failed)) * 100)}%`);
    
    if (results.failed > 0) {
      console.log('\n❌ Failed Tests:');
      results.tests.filter(t => !t.passed).forEach(t => {
        console.log(`  - ${t.name}`);
        if (t.details) console.log(`    ${t.details}`);
      });
    }
    
    await browser.close();
  }
}

testAllFeatures().catch(console.error);