/**
 * Onboarding Authenticated Test
 * Tests the onboarding page after login
 */

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

const BASE_URL = 'http://localhost:9000';
const TEST_EMAIL = 'guqo@mailinator.com';

test.describe('Onboarding Page - Authenticated', () => {
  test('login and access onboarding', async ({ page }) => {
    // Increase timeout for this test
    test.setTimeout(120000);

    // Step 1: Go to login
    console.log('Step 1: Going to login page...');
    await page.goto(`${BASE_URL}/en/login`);
    await page.waitForLoadState('networkidle');

    // Dismiss cookie consent if present
    const acceptCookies = page.locator('button:has-text("Accept All")');
    if (await acceptCookies.isVisible({ timeout: 2000 }).catch(() => false)) {
      await acceptCookies.click();
      console.log('Dismissed cookie consent');
    }

    await page.screenshot({ path: 'tests/e2e/screenshots/auth-1-login.png' });

    // Step 2: Enter email using the specific email input
    console.log('Step 2: Entering email...');
    const emailInput = page.locator('#email');
    await emailInput.waitFor({ state: 'visible', timeout: 10000 });
    await emailInput.fill(TEST_EMAIL);
    console.log('Email filled:', TEST_EMAIL);
    await page.screenshot({ path: 'tests/e2e/screenshots/auth-2-email-filled.png' });

    // Step 3: Click Send OTP
    console.log('Step 3: Clicking Send OTP...');
    const sendButton = page.locator('button[type="submit"]');
    await sendButton.click();
    console.log('Send OTP clicked');

    // Step 4: Wait for OTP step to appear (wait for the OTP input to be visible)
    console.log('Step 4: Waiting for OTP step...');
    const otpInput = page.locator('input[name="otp"]');

    try {
      await otpInput.waitFor({ state: 'visible', timeout: 15000 });
      console.log('OTP input is visible');
    } catch (e) {
      // Take screenshot if OTP step doesn't appear
      await page.screenshot({ path: 'tests/e2e/screenshots/auth-3-no-otp-step.png' });
      const pageContent = await page.content();
      console.log('Page content (first 1000 chars):', pageContent.substring(0, 1000));
      throw new Error('OTP step did not appear - Send OTP may have failed');
    }

    await page.screenshot({ path: 'tests/e2e/screenshots/auth-3-otp-step.png' });

    // Step 5: Get OTP from MailHog
    console.log('Step 5: Fetching OTP from MailHog...');

    // Retry fetching OTP a few times
    let otp = '';
    for (let i = 0; i < 5; i++) {
      try {
        const mailResponse = await page.request.get('http://localhost:8025/api/v2/messages?limit=5');
        const mailData = await mailResponse.json();

        if (mailData.items && mailData.items.length > 0) {
          // Find the most recent email for our test user
          for (const item of mailData.items) {
            const emailBody = item.Content?.Body || '';
            const headers = item.Content?.Headers || {};
            const to = headers.To?.[0] || '';

            // Check if this email is for our test user
            if (to.includes(TEST_EMAIL)) {
              // Try to find 6-digit OTP
              const otpMatch = emailBody.match(/\b(\d{6})\b/);
              if (otpMatch) {
                otp = otpMatch[1];
                console.log('Found OTP:', otp);
                break;
              }
            }
          }
        }

        if (otp) break;
        console.log(`No OTP found yet, attempt ${i + 1}/5...`);
        await page.waitForTimeout(1000);
      } catch (e) {
        console.log('Error fetching OTP:', e);
        await page.waitForTimeout(1000);
      }
    }

    if (!otp) {
      await page.screenshot({ path: 'tests/e2e/screenshots/auth-4-no-otp.png' });
      throw new Error('Could not find OTP in MailHog');
    }

    // Step 6: Enter OTP using pressSequentially for better React compatibility
    console.log('Step 6: Entering OTP...');
    await otpInput.click(); // Focus the input first
    await otpInput.clear(); // Clear any existing value

    // Use pressSequentially to type each digit - this triggers React events properly
    await otpInput.pressSequentially(otp, { delay: 50 });

    // Wait a moment for React state to update
    await page.waitForTimeout(500);

    // Verify the input value
    const inputValue = await otpInput.inputValue();
    console.log('OTP input value:', inputValue);

    await page.screenshot({ path: 'tests/e2e/screenshots/auth-4-otp-filled.png' });

    // Step 7: Wait for verify button to be enabled and click it
    console.log('Step 7: Verifying OTP...');
    const verifyButton = page.locator('button[type="submit"]:has-text("Verify")');

    // Wait for button to be enabled
    await expect(verifyButton).toBeEnabled({ timeout: 5000 });
    console.log('Verify button is enabled');

    await verifyButton.click();
    console.log('Verify button clicked');

    // Step 8: Wait for redirect to dashboard
    console.log('Step 8: Waiting for redirect...');
    await page.waitForURL('**/dashboard**', { timeout: 15000 });
    console.log('Redirected to:', page.url());
    await page.screenshot({ path: 'tests/e2e/screenshots/auth-5-after-verify.png' });

    // Step 9: Navigate to onboarding
    console.log('Step 9: Navigating to onboarding...');
    await page.goto(`${BASE_URL}/en/dashboard/onboarding`);
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);

    console.log('Onboarding URL:', page.url());
    await page.screenshot({ path: 'tests/e2e/screenshots/auth-6-onboarding.png', fullPage: true });

    // Step 10: Verify onboarding page loaded
    console.log('Step 10: Verifying onboarding page...');

    // Check if we're still on onboarding (not redirected to login)
    expect(page.url()).toContain('/dashboard');

    // Look for onboarding elements
    const pageTitle = await page.title();
    console.log('Page title:', pageTitle);

    // Get body text to understand what's on the page
    const bodyText = await page.locator('body').innerText();
    console.log('Page content preview:', bodyText.substring(0, 500));

    // Check for specific onboarding elements
    const hasWelcome = await page.locator('text=/Welcome|مرحباً|Get Started|Setup/i').isVisible().catch(() => false);
    console.log('Has welcome/setup text:', hasWelcome);

    const hasProgressBar = await page.locator('[class*="progress"], .progress').isVisible().catch(() => false);
    console.log('Has progress bar:', hasProgressBar);

    // The test passes if we're on the dashboard and see onboarding content
    if (page.url().includes('/dashboard')) {
      console.log('SUCCESS: Authenticated and on dashboard');
    }
  });
});
