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

test.describe('Login Test for gara2222ge@support.com', () => {
  test('should login and reach dashboard', async ({ page }) => {
    // Step 1: Navigate to login page
    console.log('Step 1: Navigating to login page...');
    await page.goto('http://localhost:9000/en/login');
    await page.waitForLoadState('networkidle');

    // Step 2: Take screenshot of login page
    await page.screenshot({ path: '/tmp/login-page.png' });
    console.log('✓ Login page screenshot saved to /tmp/login-page.png');

    // Step 3: Dismiss cookie banner if present
    const cookieBanner = page.locator('text=Accept All');
    if (await cookieBanner.isVisible({ timeout: 2000 }).catch(() => false)) {
      await cookieBanner.click();
      console.log('✓ Cookie banner dismissed');
    }

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

    // Step 4: Submit form
    console.log('Step 3: Submitting login form...');
    await page.click('button[type="submit"]');

    // Step 5: Wait for navigation
    console.log('Step 4: Waiting for navigation...');
    await page.waitForURL('**/*', { timeout: 10000 });

    // Step 6: Check current URL
    const currentUrl = page.url();
    console.log('Current URL after login:', currentUrl);

    // Step 7: Take screenshot of result page
    await page.screenshot({ path: '/tmp/after-login.png' });
    console.log('✓ After-login screenshot saved to /tmp/after-login.png');

    // Step 8: Verify we're on dashboard
    if (currentUrl.includes('/dashboard')) {
      console.log('✅ SUCCESS: User reached dashboard');

      // Get dashboard content
      const dashboardTitle = await page.textContent('h1').catch(() => 'No h1 found');
      console.log('Dashboard title:', dashboardTitle);

      expect(currentUrl).toContain('/dashboard');
    } else if (currentUrl.includes('/login')) {
      console.log('❌ FAILED: Still on login page');

      // Check for error messages
      const errorMessage = await page.textContent('.error, [role="alert"], .text-red-500').catch(() => null);
      if (errorMessage) {
        console.log('Error message:', errorMessage);
      }

      const pageContent = await page.content();
      console.log('Page HTML (first 500 chars):', pageContent.substring(0, 500));

      throw new Error('Login failed - still on login page');
    } else {
      console.log('⚠️ UNEXPECTED: Redirected to:', currentUrl);
      throw new Error('Unexpected redirect after login');
    }
  });
});
