/**
 * Manual Login Test Script
 * Tests the complete login flow manually using the actual user credentials
 */

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 testLogin() {
  console.log('=== Manual Login Test ===');
  console.log(`Testing login for: ${TEST_EMAIL}`);
  console.log('');

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

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

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

    // Fill credentials
    console.log('2. Filling in credentials...');
    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    await page.locator('input[type="password"]').fill(TEST_PASSWORD);
    console.log('✅ Credentials filled');

    // Click submit
    console.log('3. Clicking login button...');
    await page.locator('button[type="submit"]').click();

    // Wait for navigation to dashboard
    console.log('4. Waiting for navigation to dashboard...');
    try {
      await page.waitForURL('**/dashboard', { timeout: 15000 });
      console.log('✅ Navigated to dashboard!');
    } catch (e) {
      console.log('⚠️ Timeout waiting for dashboard navigation');
    }

    // Also wait for network idle
    await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});

    // Check current URL
    const currentUrl = page.url();
    console.log(`Current URL: ${currentUrl}`);

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

    // Check for dashboard
    if (currentUrl.includes('/dashboard')) {
      console.log('');
      console.log('✅✅✅ SUCCESS! User logged in and redirected to dashboard ✅✅✅');
      console.log('');

      // Verify dashboard content
      const hasWelcome = await page.locator('text=/Welcome|Dashboard/i').isVisible().catch(() => false);
      const hasName = await page.locator(`text=Mohammad`).isVisible().catch(() => false);

      console.log(`Dashboard contains "Welcome": ${hasWelcome ? 'YES' : 'NO'}`);
      console.log(`Dashboard contains "Mohammad": ${hasName ? 'YES' : 'NO'}`);

      await page.waitForTimeout(3000); // Keep browser open for 3 seconds
    } else {
      console.log('');
      console.log('❌ FAILED - Not on dashboard page');
      console.log('');

      // 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 displayed: ${errorText}`);
      }

      await page.waitForTimeout(5000); // Keep browser open for inspection
    }

  } catch (error) {
    console.error('❌ Test error:', error);
    await page.screenshot({ path: 'manual-login-error.png', fullPage: true });
  } finally {
    await browser.close();
  }
}

testLogin();
