/**
 * Test Current Login Flow
 * Verifies where user is redirected after login
 */

import { chromium } from '@playwright/test';

const BASE_URL = 'http://localhost:9000';
const TEST_EMAIL = 'gara2222ge@support.com';
const TEST_PASSWORD = 'eGj&tk!@%T8sFMOq#3QP';

async function testCurrentLogin() {
  console.log('=== Current Login Flow Test ===');
  console.log('');

  const browser = await chromium.launch({ headless: false, slowMo: 500 });
  const context = await browser.newContext();
  const page = await context.newPage();

  try {
    // Enable logging
    page.on('console', msg => {
      if (msg.text().includes('Login') || msg.text().includes('Dashboard') || msg.text().includes('error')) {
        console.log(`[Browser] ${msg.text()}`);
      }
    });

    // Track all navigations
    page.on('framenavigated', frame => {
      if (frame === page.mainFrame()) {
        console.log(`→ Navigated to: ${frame.url()}`);
      }
    });

    // Navigate to login
    console.log('Step 1: Navigate to login page');
    await page.goto(`${BASE_URL}/en/login`, { waitUntil: 'networkidle' });
    console.log(`✅ On: ${page.url()}`);
    console.log('');

    // Fill credentials
    console.log('Step 2: Enter credentials');
    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    await page.locator('input[type="password"]').fill(TEST_PASSWORD);
    console.log('✅ Credentials entered');
    console.log('');

    // Submit
    console.log('Step 3: Click login button');
    await page.locator('button[type="submit"]').click();
    console.log('✅ Button clicked, waiting for response...');
    console.log('');

    // Wait and track all navigation
    await page.waitForTimeout(10000);

    // Final URL
    const finalUrl = page.url();
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`FINAL URL: ${finalUrl}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('');

    // Take screenshot
    await page.screenshot({ path: 'current-login-flow.png', fullPage: true });
    console.log('Screenshot: current-login-flow.png');
    console.log('');

    // Analyze result
    if (finalUrl.includes('/dashboard')) {
      console.log('✅ SUCCESS: Redirected to dashboard');
    } else if (finalUrl.includes('/signup/success')) {
      console.log('❌ ERROR: Redirected to signup success page (wrong!)');
    } else if (finalUrl.includes('/signup')) {
      console.log('❌ ERROR: Redirected to signup page (wrong!)');
    } else if (finalUrl.includes('/login')) {
      console.log('⚠️  STAYED on login page (check for errors)');

      const errorElement = await page.locator('[class*="red"]').first();
      if (await errorElement.isVisible().catch(() => false)) {
        const errorText = await errorElement.textContent();
        console.log(`Error shown: ${errorText}`);
      }
    } else {
      console.log(`⚠️  Unexpected URL: ${finalUrl}`);
    }

    // Keep browser open for inspection
    console.log('');
    console.log('Keeping browser open for 5 seconds...');
    await page.waitForTimeout(5000);

  } catch (error) {
    console.error('Test error:', error);
  } finally {
    await browser.close();
  }
}

testCurrentLogin();
