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

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

async function testLogin() {
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext({ viewport: { width: 1920, height: 1080 } });
  const page = await context.newPage();
  
  console.log('Testing login with new test user...\n');
  
  try {
    // Navigate to login page
    console.log('1. Navigating to login page...');
    await page.goto(`${BASE_URL}/training-login/`);
    await page.waitForLoadState('networkidle');
    
    // Check what login fields are available
    const loginFormSelectors = [
      '#user_login',
      '#user_pass',
      '#wp-submit',
      'input[name="log"]',
      'input[name="pwd"]'
    ];
    
    console.log('2. Checking available form fields:');
    for (const selector of loginFormSelectors) {
      const exists = await page.locator(selector).count() > 0;
      console.log(`   ${selector}: ${exists ? '✓ FOUND' : '✗ NOT FOUND'}`);
    }
    
    // Take screenshot of login page
    await page.screenshot({ path: 'screenshots/test-login-page.png' });
    
    // Try to login using the most common selectors
    console.log('\n3. Attempting login...');
    
    // Try filling by name attribute first
    const usernameInput = page.locator('input[name="log"]').or(page.locator('#user_login'));
    const passwordInput = page.locator('input[name="pwd"]').or(page.locator('#user_pass'));
    const submitButton = page.locator('#wp-submit').or(page.locator('button[type="submit"]'));
    
    await usernameInput.fill('test_trainer');
    await passwordInput.fill('TestTrainer123!');
    await page.screenshot({ path: 'screenshots/test-login-filled.png' });
    
    await submitButton.click();
    console.log('   Login form submitted');
    
    // Wait for navigation
    console.log('4. Waiting for redirect...');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(5000);
    
    const currentUrl = page.url();
    console.log(`   Current URL: ${currentUrl}`);
    
    // Check if we're logged in
    if (currentUrl.includes('/trainer/') || currentUrl.includes('dashboard')) {
      console.log('   ✓ Login successful!');
      
      // Check for navigation and breadcrumbs
      const hasNav = await page.locator('.hvac-trainer-nav').count() > 0;
      const hasBreadcrumb = await page.locator('.hvac-breadcrumb').count() > 0;
      
      console.log(`\n5. Checking page elements:`);
      console.log(`   Navigation menu: ${hasNav ? '✓ FOUND' : '✗ NOT FOUND'}`);
      console.log(`   Breadcrumbs: ${hasBreadcrumb ? '✓ FOUND' : '✗ NOT FOUND'}`);
      
      await page.screenshot({ path: 'screenshots/test-login-success.png', fullPage: true });
    } else {
      console.log('   ✗ Login failed - still on login page');
      
      // Check for error messages
      const errorMessages = await page.locator('.error, .login-error, #login_error').allTextContents();
      if (errorMessages.length > 0) {
        console.log('   Error messages found:');
        errorMessages.forEach(msg => console.log(`     - ${msg.trim()}`));
      }
      
      await page.screenshot({ path: 'screenshots/test-login-failed.png' });
    }
    
  } catch (error) {
    console.error('\nError during test:', error.message);
    await page.screenshot({ path: 'screenshots/test-login-error.png' });
  } finally {
    await browser.close();
  }
}

testLogin().catch(console.error);