/**
 * E2E Test: Passwordless Signup Flow
 *
 * Tests the complete passwordless signup experience:
 * 1. User enters name + email (no password)
 * 2. System sends OTP to email
 * 3. User verifies OTP
 * 4. Account created with password: null
 */

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

const APP_URL = 'http://localhost:9000';
const MAILHOG_API = 'http://localhost:8025/api/v2';

// Helper: Get latest email from MailHog
async function getLatestEmailForAddress(email: string): Promise<any> {
  const response = await fetch(`${MAILHOG_API}/messages`);
  const data = await response.json();

  const userEmails = data.items.filter((item: any) => {
    const toHeader = item.Content?.Headers?.To?.[0] || '';
    return toHeader.includes(email);
  });

  return userEmails.length > 0 ? userEmails[0] : null;
}

// Helper: Extract OTP from email
function extractOTP(emailData: any): string | null {
  const body = emailData?.Content?.Body || '';

  // Look for 6-digit code
  const match = body.match(/(\d{6})/);
  return match ? match[1] : null;
}

// Helper: Clear MailHog
async function clearMailHog() {
  await fetch(`${MAILHOG_API}/messages`, { method: 'DELETE' });
}

test.describe('Passwordless Signup Flow', () => {

  test.beforeEach(async () => {
    await clearMailHog();
  });

  test('should complete passwordless signup successfully', async ({ page }) => {
    const testEmail = `passwordless-${Date.now()}@example.com`;
    const testName = 'Test Passwordless User';

    // Step 1: Navigate to signup page
    await page.goto(`${APP_URL}/en/signup`);
    await expect(page).toHaveURL(/\/en\/signup/);

    // Step 2: Verify no password fields exist
    const passwordInput = page.locator('input[type="password"]');
    await expect(passwordInput).toHaveCount(0);
    console.log('✅ No password fields found on signup page');

    // Step 3: Verify passwordless notice is shown
    await expect(page.locator('text=/Passwordless Signup/i')).toBeVisible();
    console.log('✅ Passwordless notice visible');

    // Step 4: Check if we need to select a package first
    const packageSelection = page.locator('text=/Select.*Plan|Choose.*Package/i');
    if (await packageSelection.isVisible()) {
      // Select a package if needed
      await page.click('button:has-text("Get Started"), button:has-text("Choose"), button:has-text("Select")').catch(() => {
        console.log('Package already selected or not needed');
      });
      await page.waitForTimeout(1000);
    }

    // Step 5: Fill signup form (only name and email!)
    const nameInput = page.locator('input[id="fullName"], input[name="fullName"], input[placeholder*="name" i]').first();
    const emailInput = page.locator('input[type="email"], input[id="email"], input[name="email"]').first();

    await nameInput.fill(testName);
    await emailInput.fill(testEmail);
    console.log(`✅ Filled form - Name: ${testName}, Email: ${testEmail}`);

    // Step 6: Submit form (should send OTP, not create account)
    const submitButton = page.locator('button[type="submit"]:has-text("Send"), button:has-text("Verification Code"), button[type="submit"]').first();
    await submitButton.click();
    console.log('✅ Clicked submit - should send OTP');

    // Step 7: Wait for redirect to verify page
    await expect(page).toHaveURL(/\/verify/, { timeout: 10000 });
    console.log('✅ Redirected to OTP verification page');

    // Step 8: Wait for email to arrive
    await page.waitForTimeout(3000);

    // Step 9: Get OTP from MailHog
    const emailData = await getLatestEmailForAddress(testEmail);
    expect(emailData).toBeTruthy();
    console.log('✅ Email received in MailHog');

    // Step 10: Verify email is personalized with name
    const emailBody = emailData.Content.Body;
    expect(emailBody).toContain(testName.split(' ')[0]); // Should contain first name
    console.log(`✅ Email is personalized with name`);

    // Step 11: Extract OTP code
    const otpCode = extractOTP(emailData);
    expect(otpCode).toBeTruthy();
    expect(otpCode).toMatch(/^\d{6}$/);
    console.log(`✅ OTP extracted: ${otpCode}`);

    // Step 12: Enter OTP code
    const otpInputs = page.locator('input[type="text"][maxlength="1"], input[inputmode="numeric"]');
    const inputCount = await otpInputs.count();

    if (inputCount >= 6) {
      // Individual digit inputs
      const digits = otpCode!.split('');
      for (let i = 0; i < 6; i++) {
        await otpInputs.nth(i).fill(digits[i]);
      }
    } else {
      // Single input field
      const singleInput = page.locator('input[inputmode="numeric"], input[type="text"]').first();
      await singleInput.fill(otpCode!);
    }
    console.log('✅ OTP entered');

    // Step 13: Submit OTP verification
    const verifyButton = page.locator('button:has-text("Verify"), button[type="submit"]').first();
    await verifyButton.click();
    console.log('✅ Clicked verify');

    // Step 14: Wait for successful verification and redirect
    await expect(page).toHaveURL(/\/(company-info|dashboard|onboarding)/, { timeout: 10000 });
    console.log('✅ Account created and redirected to next step');

    // Step 15: Verify in database (via API check)
    const checkResponse = await page.request.get(`${APP_URL}/api/auth/check-email?email=${encodeURIComponent(testEmail)}`);
    const checkData = await checkResponse.json();

    expect(checkData.exists).toBe(true);
    expect(checkData.verified).toBe(true);
    console.log('✅ Account verified in database');
  });

  test('should show no password fields on signup page', async ({ page }) => {
    await page.goto(`${APP_URL}/en/signup`);

    // Verify password fields don't exist
    const passwordFields = page.locator('input[type="password"]');
    await expect(passwordFields).toHaveCount(0);

    // Verify passwordless notice exists
    await expect(page.locator('text=/Passwordless/i')).toBeVisible();

    // Verify button text is about sending code, not creating account
    const submitButton = page.locator('button[type="submit"]').first();
    const buttonText = await submitButton.textContent();
    expect(buttonText).toMatch(/send|verification|code/i);
    expect(buttonText).not.toMatch(/create.*account/i);
  });

  test('should prevent duplicate signups with existing email', async ({ page }) => {
    const existingEmail = 'gara2222ge@support.com'; // Known existing account

    await page.goto(`${APP_URL}/en/signup`);

    // Fill form with existing email
    await page.locator('input[id="fullName"], input[name="fullName"]').first().fill('Duplicate Test');
    await page.locator('input[type="email"]').first().fill(existingEmail);

    // Submit
    await page.locator('button[type="submit"]').first().click();

    // Should show "already registered" message
    await expect(page.locator('text=/already registered|already exists|مسجل بالفعل/i')).toBeVisible({ timeout: 5000 });
    console.log('✅ Duplicate email message shown');

    // Should show login link
    await expect(page.locator('a[href*="/login"], text=/Go to login|تسجيل الدخول/i')).toBeVisible();
    console.log('✅ Login link shown');

    // Should auto-redirect to login (wait max 5 seconds)
    await page.waitForURL(/\/login/, { timeout: 5000 });
    console.log('✅ Auto-redirected to login page');
  });

  test('should send personalized OTP emails', async ({ page }) => {
    const testEmail = `personalized-${Date.now()}@example.com`;
    const testName = 'John Doe';

    await clearMailHog();
    await page.goto(`${APP_URL}/en/signup`);

    // Fill form
    await page.locator('input[id="fullName"], input[name="fullName"]').first().fill(testName);
    await page.locator('input[type="email"]').first().fill(testEmail);
    await page.locator('button[type="submit"]').first().click();

    // Wait for email
    await page.waitForTimeout(3000);

    // Get email
    const emailData = await getLatestEmailForAddress(testEmail);
    expect(emailData).toBeTruthy();

    // Check personalization
    const emailBody = emailData.Content.Body;
    expect(emailBody).toMatch(/Hello John|مرحباً John/);
    console.log('✅ Email contains personalized greeting');

    // Check subject
    const subject = emailData.Content.Headers.Subject[0];
    expect(subject).toContain('Mawidi');
    console.log(`✅ Professional subject line: ${subject}`);

    // Check contains OTP
    const otp = extractOTP(emailData);
    expect(otp).toBeTruthy();
    console.log(`✅ OTP found in email: ${otp}`);
  });

  test('should work in Arabic language', async ({ page }) => {
    const testEmail = `arabic-${Date.now()}@example.com`;

    await clearMailHog();
    await page.goto(`${APP_URL}/ar/signup`);

    // Verify RTL layout
    const html = page.locator('html');
    await expect(html).toHaveAttribute('dir', 'rtl');

    // Fill form
    await page.locator('input[id="fullName"], input[name="fullName"]').first().fill('مستخدم تجريبي');
    await page.locator('input[type="email"]').first().fill(testEmail);

    // Verify Arabic text on button
    const button = page.locator('button[type="submit"]').first();
    const buttonText = await button.textContent();
    expect(buttonText).toMatch(/رمز|تحقق/);

    await button.click();

    // Wait for email
    await page.waitForTimeout(3000);

    // Verify Arabic email was sent
    const emailData = await getLatestEmailForAddress(testEmail);
    const subject = emailData?.Content?.Headers?.Subject?.[0] || '';
    expect(subject).toMatch(/رمز|Mawidi/);
    console.log('✅ Arabic email sent successfully');
  });

  test('should validate email format before sending OTP', async ({ page }) => {
    await page.goto(`${APP_URL}/en/signup`);

    // Fill with invalid email
    await page.locator('input[id="fullName"], input[name="fullName"]').first().fill('Test User');
    await page.locator('input[type="email"]').first().fill('invalid-email');
    await page.locator('button[type="submit"]').first().click();

    // Should show validation error
    await expect(page.locator('text=/invalid.*email|email.*invalid/i')).toBeVisible({ timeout: 3000 });
    console.log('✅ Email validation working');
  });

  test('should validate required fields', async ({ page }) => {
    await page.goto(`${APP_URL}/en/signup`);

    // Try to submit empty form
    await page.locator('button[type="submit"]').first().click();

    // Should show required field errors
    const errorMessages = page.locator('text=/required|field is required/i');
    await expect(errorMessages.first()).toBeVisible({ timeout: 3000 });
    console.log('✅ Required field validation working');
  });
});

test.describe('MailHog Integration', () => {

  test('MailHog should be accessible', async () => {
    const response = await fetch(`${MAILHOG_API}/messages`);
    expect(response.ok).toBeTruthy();
    console.log('✅ MailHog API accessible');
  });

  test('should send emails to MailHog within 2 seconds', async ({ page }) => {
    const testEmail = `speed-test-${Date.now()}@example.com`;

    await clearMailHog();
    await page.goto(`${APP_URL}/en/signup`);

    await page.locator('input[id="fullName"], input[name="fullName"]').first().fill('Speed Test');
    await page.locator('input[type="email"]').first().fill(testEmail);

    const startTime = Date.now();
    await page.locator('button[type="submit"]').first().click();

    // Wait for email
    await page.waitForTimeout(2500);

    const emailData = await getLatestEmailForAddress(testEmail);
    const endTime = Date.now();

    expect(emailData).toBeTruthy();

    const duration = endTime - startTime;
    console.log(`✅ Email arrived in ${duration}ms (target: <2000ms)`);
  });
});
