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

async function testAuthFlow() {
  console.log('🧪 Starting Playwright authentication flow test...');
  
  const browser = await chromium.launch({ 
    headless: false,
    slowMo: 1000 // Slow down for easier observation
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 }
  });
  
  const page = await context.newPage();
  
  // Enable console logging
  page.on('console', msg => console.log(`[PAGE] ${msg.text()}`));
  page.on('pageerror', err => console.error(`[PAGE ERROR] ${err}`));
  
  try {
    console.log('\n📋 Test Plan:');
    console.log('1. Navigate to homepage');
    console.log('2. Click login button');
    console.log('3. Enter credentials');
    console.log('4. Check if dashboard loads properly');
    console.log('5. Check for any flashing or redirects');
    
    // Step 1: Navigate to homepage
    console.log('\n🏠 Step 1: Navigating to homepage...');
    await page.goto('http://localhost:3000', { waitUntil: 'networkidle' });
    
    console.log(`Current URL: ${page.url()}`);
    const title = await page.title();
    console.log(`Page title: ${title}`);
    
    // Take screenshot
    await page.screenshot({ path: 'homepage.png' });
    console.log('Screenshot saved: homepage.png');
    
    // Step 2: Find and click login button
    console.log('\n🔑 Step 2: Looking for login button...');
    
    // Look for login button (try multiple selectors)
    const loginSelectors = [
      'a[href="/login-new"]',
      'a[href="/login"]', 
      'text="Sign In"',
      'text="Login"',
      'button:has-text("Sign In")',
      'button:has-text("Login")'
    ];
    
    let loginButton = null;
    for (const selector of loginSelectors) {
      try {
        loginButton = await page.waitForSelector(selector, { timeout: 2000 });
        if (loginButton) {
          console.log(`Found login button with selector: ${selector}`);
          break;
        }
      } catch (e) {
        // Continue to next selector
      }
    }
    
    if (!loginButton) {
      console.error('❌ No login button found!');
      
      // Get all links for debugging
      const allLinks = await page.$$eval('a', links => 
        links.map(link => ({ text: link.textContent, href: link.href }))
      );
      console.log('All links on page:', allLinks);
      
      await browser.close();
      return;
    }
    
    // Click login button
    console.log('Clicking login button...');
    await loginButton.click();
    
    // Wait for navigation
    await page.waitForLoadState('networkidle');
    console.log(`After login click, URL: ${page.url()}`);
    
    // Take screenshot of login page
    await page.screenshot({ path: 'login-page.png' });
    console.log('Screenshot saved: login-page.png');
    
    // Step 3: Fill login form
    console.log('\n✍️ Step 3: Filling login form...');
    
    // Wait for login form
    await page.waitForSelector('#login-form', { timeout: 5000 });
    
    // Fill in credentials (using admin credentials)
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'Skittles@420');
    
    console.log('Filled login credentials');
    
    // Take screenshot before submitting
    await page.screenshot({ path: 'login-form-filled.png' });
    console.log('Screenshot saved: login-form-filled.png');
    
    // Submit form
    console.log('Submitting login form...');
    
    // Try different button selectors (new login page vs old login page)
    const buttonSelectors = ['#login-btn', 'button[type="submit"]', 'button:has-text("Sign In")', 'button:has-text("Sign in")'];
    
    let submitButton = null;
    for (const selector of buttonSelectors) {
      try {
        submitButton = await page.waitForSelector(selector, { timeout: 2000 });
        if (submitButton) {
          console.log(`Found submit button with selector: ${selector}`);
          break;
        }
      } catch (e) {
        // Continue to next selector
      }
    }
    
    if (!submitButton) {
      console.error('❌ No submit button found!');
      return;
    }
    
    await submitButton.click();
    
    // Wait for either dashboard or error
    console.log('\n⏱️ Step 4: Waiting for response...');
    
    // Set up response listener
    page.on('response', response => {
      console.log(`[RESPONSE] ${response.status()} ${response.url()}`);
    });
    
    // Wait for either success or error
    try {
      // Wait for dashboard or stay on login with error
      await page.waitForTimeout(3000); // Give it 3 seconds
      
      const currentUrl = page.url();
      console.log(`Current URL after login: ${currentUrl}`);
      
      if (currentUrl.includes('/dashboard')) {
        console.log('✅ Successfully redirected to dashboard!');
        
        // Check for any flashing or loading states
        console.log('\n🔍 Step 5: Checking for flashing issues...');
        
        // Wait a bit more to see if there are any redirects or flashes
        await page.waitForTimeout(2000);
        
        const finalUrl = page.url();
        console.log(`Final URL: ${finalUrl}`);
        
        // Take screenshot of dashboard
        await page.screenshot({ path: 'dashboard.png' });
        console.log('Screenshot saved: dashboard.png');
        
        // Check if EventHeader and QuickStats are loading
        const eventHeaderExists = await page.$('.auth-content') !== null;
        const quickStatsExists = await page.$('#tickets-sold') !== null;
        
        console.log(`EventHeader visible: ${eventHeaderExists}`);
        console.log(`QuickStats visible: ${quickStatsExists}`);
        
        // Wait and check for any auth errors in console
        await page.waitForTimeout(3000);
        
        console.log('✅ Test completed successfully!');
        
      } else if (currentUrl.includes('/login')) {
        console.log('❌ Still on login page - checking for errors...');
        
        // Look for error message
        const errorMessage = await page.$('#error-message');
        if (errorMessage) {
          const errorText = await errorMessage.textContent();
          console.log(`Error message: ${errorText}`);
        }
        
        // Take screenshot of error
        await page.screenshot({ path: 'login-error.png' });
        console.log('Screenshot saved: login-error.png');
        
      } else {
        console.log(`❓ Unexpected URL: ${currentUrl}`);
        await page.screenshot({ path: 'unexpected-page.png' });
      }
      
    } catch (error) {
      console.error('❌ Error during login flow:', error);
      await page.screenshot({ path: 'error-state.png' });
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error);
    await page.screenshot({ path: 'test-failure.png' });
  } finally {
    console.log('\n📊 Test Summary:');
    console.log('Check the screenshots for visual verification');
    console.log('Available screenshots:');
    console.log('- homepage.png');
    console.log('- login-page.png'); 
    console.log('- login-form-filled.png');
    console.log('- dashboard.png (if successful)');
    console.log('- login-error.png (if login failed)');
    
    await browser.close();
  }
}

// Run the test
testAuthFlow().catch(console.error);