/**
 * Onboarding Debug Test
 * Investigates why the onboarding page doesn't work properly
 */

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

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

test.describe('Onboarding Page Debug', () => {
  test('check onboarding page without auth', async ({ page }) => {
    // Visit onboarding directly without login
    console.log('Navigating to onboarding page without auth...');
    const response = await page.goto(`${BASE_URL}/en/dashboard/onboarding`);

    console.log('Response status:', response?.status());
    console.log('Final URL:', page.url());

    // Should redirect to login
    await expect(page).toHaveURL(/\/login/);
    console.log('Correctly redirected to login page');

    // Take screenshot
    await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-no-auth.png' });
  });

  test('check onboarding page with auth', async ({ page }) => {
    // First login via OTP
    console.log('Step 1: Going to login page...');
    await page.goto(`${BASE_URL}/en/login`);
    await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-1-login-page.png' });

    // Fill email
    console.log('Step 2: Filling email...');
    const emailInput = page.locator('input[type="email"], input[name="email"]');
    await emailInput.fill(TEST_EMAIL);
    await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-2-email-filled.png' });

    // Click send OTP
    console.log('Step 3: Sending OTP...');
    const sendOtpButton = page.locator('button:has-text("Send"), button:has-text("OTP"), button[type="submit"]').first();
    await sendOtpButton.click();

    // Wait for OTP input to appear
    console.log('Step 4: Waiting for OTP input...');
    await page.waitForTimeout(2000);
    await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-3-otp-sent.png' });

    // Check if OTP input is visible
    const otpInput = page.locator('input[name="otp"], input[placeholder*="OTP"], input[placeholder*="code"]');
    const isOtpVisible = await otpInput.isVisible().catch(() => false);
    console.log('OTP input visible:', isOtpVisible);

    // If we can get OTP from MailHog
    if (isOtpVisible) {
      try {
        // Fetch OTP from MailHog
        const mailhogResponse = await page.request.get('http://localhost:8025/api/v2/messages?limit=1');
        const mailhogData = await mailhogResponse.json();

        if (mailhogData.items?.length > 0) {
          const emailBody = mailhogData.items[0].Content?.Body || '';
          const otpMatch = emailBody.match(/\b(\d{6})\b/);

          if (otpMatch) {
            const otp = otpMatch[1];
            console.log('Found OTP:', otp);

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

            // Submit OTP
            const verifyButton = page.locator('button:has-text("Verify"), button:has-text("Login"), button[type="submit"]').first();
            await verifyButton.click();

            // Wait for navigation
            await page.waitForTimeout(3000);
            console.log('After OTP submit, URL:', page.url());
            await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-5-after-otp.png' });

            // Now try to navigate to onboarding
            console.log('Step 5: Navigating to onboarding...');
            await page.goto(`${BASE_URL}/en/dashboard/onboarding`);
            await page.waitForTimeout(2000);

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

            // Check page content
            const pageContent = await page.content();
            console.log('Page has OnboardingWizard:', pageContent.includes('OnboardingWizard') || pageContent.includes('onboarding'));
            console.log('Page has error:', pageContent.includes('error') || pageContent.includes('Error'));

            // Check for any visible errors
            const errorElements = page.locator('[class*="error"], [role="alert"], .text-red');
            const errorCount = await errorElements.count();
            console.log('Error elements found:', errorCount);

            if (errorCount > 0) {
              for (let i = 0; i < errorCount; i++) {
                const errorText = await errorElements.nth(i).textContent();
                console.log(`Error ${i + 1}:`, errorText);
              }
            }
          }
        }
      } catch (e) {
        console.log('Could not fetch OTP from MailHog:', e);
      }
    }
  });

  test('check onboarding components exist', async ({ page }) => {
    // Navigate to dashboard first (to establish session context)
    await page.goto(`${BASE_URL}/en/dashboard`);
    await page.waitForTimeout(1000);

    console.log('Dashboard URL:', page.url());
    await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-dashboard.png' });

    // Check if redirected to login
    if (page.url().includes('/login')) {
      console.log('Not authenticated - redirected to login');
    } else {
      // Check for onboarding banner or wizard
      const onboardingBanner = page.locator('[data-testid="onboarding-banner"], .onboarding-banner, [class*="onboarding"]');
      const bannerVisible = await onboardingBanner.isVisible().catch(() => false);
      console.log('Onboarding banner visible:', bannerVisible);

      // Navigate to onboarding
      await page.goto(`${BASE_URL}/en/dashboard/onboarding`);
      await page.waitForTimeout(2000);

      console.log('Final onboarding URL:', page.url());
      await page.screenshot({ path: 'tests/e2e/screenshots/onboarding-final.png' });
    }
  });
});
