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

test('FINAL: Complete login flow test', async ({ page }) => {
  console.log('1️⃣ Navigate to login');
  await page.goto('http://localhost:9000/en/login');

  // Dismiss cookie banner
  try {
    await page.click('text=Accept All', { timeout: 2000 });
  } catch (e) {}

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

  console.log('3️⃣ Submit login form');
  await page.click('button[type="submit"]');

  console.log('4️⃣ Wait for navigation (up to 15 seconds)...');

  // Wait for either dashboard or error
  try {
    await page.waitForURL('**/dashboard**', { timeout: 15000 });
    console.log('✅✅✅ SUCCESS! Redirected to dashboard');

    const url = page.url();
    const title = await page.textContent('h1').catch(() => 'No title');

    console.log('Final URL:', url);
    console.log('Page title:', title);

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

    expect(url).toContain('/dashboard');

  } catch (e) {
    console.log('❌ Timeout or error waiting for dashboard');

    const currentUrl = page.url();
    console.log('Current URL:', currentUrl);

    // Check for error message
    const errorBox = await page.locator('.bg-red-50').textContent().catch(() => null);
    if (errorBox) {
      console.log('Error message:', errorBox);
    }

    await page.screenshot({ path: '/tmp/login-failed-final.png', fullPage: true });
    throw new Error('Login failed - did not reach dashboard');
  }
});
