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

test.describe('Comprehensive Signup Flow UI Testing', () => {
  test.describe.configure({ mode: 'serial' });

  test('English Signup Page - Complete UI Validation', async ({ page }) => {
    console.log('Testing English signup page...');

    // Navigate to English signup page
    await page.goto('http://localhost:9000/en/signup');
    await page.waitForLoadState('networkidle');

    // Take initial snapshot
    await page.screenshot({
      path: 'test-results/signup-en-initial.png',
      fullPage: true
    });

    console.log('✓ Page loaded successfully');

    // Check for package selection (Step 1 - should be visible first)
    const packageSelection = page.locator('text=Select Package').first();
    if (await packageSelection.isVisible()) {
      console.log('✓ Package selection step visible');
      await page.screenshot({
        path: 'test-results/signup-en-package-selection.png',
        fullPage: true
      });

      // Select a package to proceed to info form
      const tier2Button = page.locator('[data-tier="tier2"]').first();
      if (await tier2Button.isVisible()) {
        await tier2Button.click();
        await page.waitForTimeout(1000);
      }
    }

    // Wait for form to be visible
    await page.waitForSelector('form', { timeout: 5000 });

    // Verify page title and subtitle
    const title = await page.locator('h2:has-text("Sign Up")').first();
    expect(await title.isVisible()).toBeTruthy();
    console.log('✓ Page title found');

    // Check for Full Name input
    const fullNameInput = page.locator('input[id="fullName"]');
    expect(await fullNameInput.isVisible()).toBeTruthy();
    console.log('✓ Full Name input field present');

    // Check for Email input
    const emailInput = page.locator('input[id="email"]');
    expect(await emailInput.isVisible()).toBeTruthy();
    console.log('✓ Email input field present');

    // Check for Google OAuth button
    const googleButton = page.locator('button:has-text("Google")');
    expect(await googleButton.isVisible()).toBeTruthy();
    console.log('✓ Google OAuth button present');

    // Check for "OR" divider
    const orDivider = page.locator('text=/or/i').first();
    expect(await orDivider.isVisible()).toBeTruthy();
    console.log('✓ OR divider present');

    // Check for Passwordless notice
    const passwordlessNotice = page.locator('text=/Passwordless signup/i');
    expect(await passwordlessNotice.isVisible()).toBeTruthy();
    console.log('✓ Passwordless signup notice present');

    // Check for Submit button
    const submitButton = page.locator('button[type="submit"]');
    expect(await submitButton.isVisible()).toBeTruthy();
    console.log('✓ Submit button present');

    // Check for Sign In link
    const signInLink = page.locator('a[href="/en/login"]');
    expect(await signInLink.isVisible()).toBeTruthy();
    console.log('✓ Sign In link present');

    // Check for Progress Indicator
    const progressIndicator = page.locator('text=/Step 2/i').first();
    if (await progressIndicator.isVisible()) {
      console.log('✓ Progress indicator present');
    }

    // Take snapshot of form state
    await page.screenshot({
      path: 'test-results/signup-en-form.png',
      fullPage: true
    });

    // Test empty form submission
    console.log('\nTesting empty form validation...');
    await submitButton.click();
    await page.waitForTimeout(500);

    // Check for validation errors
    const fullNameError = page.locator('text=/This field is required/i').first();
    const emailError = page.locator('text=/This field is required/i').nth(1);

    if (await fullNameError.isVisible() || await emailError.isVisible()) {
      console.log('✓ Validation errors appear for empty form');
      await page.screenshot({
        path: 'test-results/signup-en-empty-validation.png',
        fullPage: true
      });
    }

    // Test invalid email format
    console.log('\nTesting invalid email validation...');
    await fullNameInput.fill('Test User');
    await emailInput.fill('invalid-email');
    await submitButton.click();
    await page.waitForTimeout(500);

    const invalidEmailError = page.locator('text=/Invalid email/i').first();
    if (await invalidEmailError.isVisible()) {
      console.log('✓ Invalid email error appears');
      await page.screenshot({
        path: 'test-results/signup-en-invalid-email.png',
        fullPage: true
      });
    }

    // Test valid form (but don't submit)
    console.log('\nTesting valid form state...');
    await fullNameInput.clear();
    await fullNameInput.fill('Test User');
    await emailInput.clear();
    await emailInput.fill('test@example.com');

    await page.screenshot({
      path: 'test-results/signup-en-valid-form.png',
      fullPage: true
    });
    console.log('✓ Valid form state captured');

    console.log('\n✅ English signup page testing complete');
  });

  test('Arabic Signup Page - Complete UI Validation', async ({ page }) => {
    console.log('\nTesting Arabic signup page...');

    // Navigate to Arabic signup page
    await page.goto('http://localhost:9000/ar/signup');
    await page.waitForLoadState('networkidle');

    // Take initial snapshot
    await page.screenshot({
      path: 'test-results/signup-ar-initial.png',
      fullPage: true
    });

    console.log('✓ Page loaded successfully');

    // Check for package selection (Step 1 - should be visible first)
    const packageSelection = page.locator('text=/اختيار الباقة/').first();
    if (await packageSelection.isVisible()) {
      console.log('✓ Package selection step visible (Arabic)');
      await page.screenshot({
        path: 'test-results/signup-ar-package-selection.png',
        fullPage: true
      });

      // Select a package to proceed to info form
      const tier2Button = page.locator('[data-tier="tier2"]').first();
      if (await tier2Button.isVisible()) {
        await tier2Button.click();
        await page.waitForTimeout(1000);
      }
    }

    // Wait for form to be visible
    await page.waitForSelector('form', { timeout: 5000 });

    // Check RTL direction
    const form = page.locator('form').first();
    const dir = await form.getAttribute('dir');
    expect(dir).toBe('rtl');
    console.log('✓ RTL direction applied correctly');

    // Verify page title in Arabic
    const title = await page.locator('h2').first();
    expect(await title.isVisible()).toBeTruthy();
    console.log('✓ Page title found (Arabic)');

    // Check for Full Name input (Arabic)
    const fullNameInput = page.locator('input[id="fullName"]');
    expect(await fullNameInput.isVisible()).toBeTruthy();
    console.log('✓ Full Name input field present');

    // Check for Email input
    const emailInput = page.locator('input[id="email"]');
    expect(await emailInput.isVisible()).toBeTruthy();
    console.log('✓ Email input field present');

    // Check for Google OAuth button
    const googleButton = page.locator('button:has-text("Google")');
    expect(await googleButton.isVisible()).toBeTruthy();
    console.log('✓ Google OAuth button present');

    // Check for Passwordless notice (Arabic)
    const passwordlessNotice = page.locator('text=/تسجيل بدون كلمة مرور/i');
    expect(await passwordlessNotice.isVisible()).toBeTruthy();
    console.log('✓ Passwordless signup notice present (Arabic)');

    // Check for Submit button
    const submitButton = page.locator('button[type="submit"]');
    expect(await submitButton.isVisible()).toBeTruthy();
    console.log('✓ Submit button present');

    // Check for Sign In link (Arabic)
    const signInLink = page.locator('a[href="/ar/login"]');
    expect(await signInLink.isVisible()).toBeTruthy();
    console.log('✓ Sign In link present (Arabic)');

    // Take snapshot of form state
    await page.screenshot({
      path: 'test-results/signup-ar-form.png',
      fullPage: true
    });

    // Test empty form submission
    console.log('\nTesting empty form validation (Arabic)...');
    await submitButton.click();
    await page.waitForTimeout(500);

    // Check for validation errors (Arabic)
    const errors = page.locator('text=/مطلوب|required/i');
    if (await errors.first().isVisible()) {
      console.log('✓ Validation errors appear for empty form (Arabic)');
      await page.screenshot({
        path: 'test-results/signup-ar-empty-validation.png',
        fullPage: true
      });
    }

    // Test invalid email format
    console.log('\nTesting invalid email validation (Arabic)...');
    await fullNameInput.fill('مستخدم تجريبي');
    await emailInput.fill('invalid-email');
    await submitButton.click();
    await page.waitForTimeout(500);

    await page.screenshot({
      path: 'test-results/signup-ar-invalid-email.png',
      fullPage: true
    });
    console.log('✓ Invalid email state captured (Arabic)');

    // Test valid form (but don't submit)
    console.log('\nTesting valid form state (Arabic)...');
    await fullNameInput.clear();
    await fullNameInput.fill('مستخدم تجريبي');
    await emailInput.clear();
    await emailInput.fill('test@example.com');

    await page.screenshot({
      path: 'test-results/signup-ar-valid-form.png',
      fullPage: true
    });
    console.log('✓ Valid form state captured (Arabic)');

    console.log('\n✅ Arabic signup page testing complete');
  });

  test('Comparison Report - English vs Arabic', async ({ page }) => {
    console.log('\n📊 Generating Comparison Report...\n');

    const report = {
      english: {
        url: 'http://localhost:9000/en/signup',
        elements: [
          'Full Name input',
          'Email input',
          'Google OAuth button',
          'OR divider',
          'Passwordless notice',
          'Submit button',
          'Sign In link',
          'Progress indicator',
        ],
        validation: [
          'Empty form validation',
          'Invalid email validation',
          'Valid form state',
        ],
        direction: 'ltr',
      },
      arabic: {
        url: 'http://localhost:9000/ar/signup',
        elements: [
          'Full Name input (Arabic)',
          'Email input',
          'Google OAuth button',
          'OR divider',
          'Passwordless notice (Arabic)',
          'Submit button',
          'Sign In link (Arabic)',
          'Progress indicator (Arabic)',
        ],
        validation: [
          'Empty form validation (Arabic)',
          'Invalid email validation (Arabic)',
          'Valid form state (Arabic)',
        ],
        direction: 'rtl',
      },
    };

    console.log('📸 Screenshots saved in test-results/ directory:');
    console.log('   - signup-en-initial.png');
    console.log('   - signup-en-package-selection.png (if applicable)');
    console.log('   - signup-en-form.png');
    console.log('   - signup-en-empty-validation.png');
    console.log('   - signup-en-invalid-email.png');
    console.log('   - signup-en-valid-form.png');
    console.log('   - signup-ar-initial.png');
    console.log('   - signup-ar-package-selection.png (if applicable)');
    console.log('   - signup-ar-form.png');
    console.log('   - signup-ar-empty-validation.png');
    console.log('   - signup-ar-invalid-email.png');
    console.log('   - signup-ar-valid-form.png');

    console.log('\n✅ All tests completed successfully!');
  });
});
