import { test, expect } from '@playwright/test';

test.describe('Login Debug Test', () => {
  test('debug login flow with console and network logs', async ({ page }) => {
    // Capture console logs
    const consoleLogs: string[] = [];
    page.on('console', msg => {
      const text = `[${msg.type()}] ${msg.text()}`;
      consoleLogs.push(text);
      console.log(text);
    });

    // Capture network errors
    page.on('requestfailed', request => {
      console.log('❌ Failed request:', request.url(), request.failure()?.errorText);
    });

    // Capture responses
    const responses: any[] = [];
    page.on('response', async response => {
      const url = response.url();
      if (url.includes('/api/') || url.includes('auth')) {
        const info = {
          url,
          status: response.status(),
          statusText: response.statusText(),
        };
        responses.push(info);
        console.log('📡 Response:', info.url, info.status);
      }
    });

    // Navigate to login
    console.log('Navigating to login page...');
    await page.goto('http://localhost:9000/en/login', { waitUntil: 'networkidle' });

    // Dismiss cookie banner
    try {
      await page.click('text=Accept All', { timeout: 2000 });
      console.log('✓ Cookie banner dismissed');
    } catch (e) {
      console.log('No cookie banner to dismiss');
    }

    // Fill credentials
    console.log('Filling credentials...');
    await page.fill('#identifier', 'gara2222ge@support.com');
    await page.fill('#password', 'eGj&tk!@%T8sFMOq#3QP');

    console.log('Submitting form...');
    await page.click('button[type="submit"]');

    // Wait and observe
    console.log('Waiting 5 seconds to observe behavior...');
    await page.waitForTimeout(5000);

    // Check URL
    const finalUrl = page.url();
    console.log('Final URL:', finalUrl);

    // Check for error message
    const errorBox = page.locator('.bg-red-50, [role="alert"]');
    if (await errorBox.isVisible().catch(() => false)) {
      const errorText = await errorBox.textContent();
      console.log('❌ Error message found:', errorText);
    } else {
      console.log('No visible error message');
    }

    // Take final screenshot
    await page.screenshot({ path: '/tmp/login-debug-final.png', fullPage: true });
    console.log('Screenshot saved to /tmp/login-debug-final.png');

    // Print summary
    console.log('\n=== SUMMARY ===');
    console.log('Console logs:', consoleLogs.length);
    console.log('API responses:', responses.length);
    console.log('Final URL:', finalUrl);
    console.log('Success:', finalUrl.includes('/dashboard') ? 'YES ✅' : 'NO ❌');
  });
});
