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

test.describe('Signup Flow', () => {
  test('should display the signup page with all elements', async ({ page }) => {
    // Navigate to signup page
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Check page title
    await expect(page.locator('h2')).toContainText('Create an account');

    // Check Google signup button exists
    await expect(page.locator('button:has-text("Sign up with Google")')).toBeVisible();

    // Check form fields exist
    await expect(page.locator('input[type="text"]#fullName')).toBeVisible();
    await expect(page.locator('input[type="email"]#email')).toBeVisible();
    await expect(page.locator('input[type="password"]#password')).toBeVisible();
    await expect(page.locator('input[type="password"]#confirmPassword')).toBeVisible();

    // Check submit button
    await expect(page.locator('button[type="submit"]')).toBeVisible();

    // Check sign in link (more specific selector)
    await expect(page.locator('main a[href="/en/login"]')).toBeVisible();
  });

  test('should show validation errors for empty form', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Click submit without filling form
    await page.locator('button[type="submit"]').click();

    // Check for error messages
    await expect(page.locator('text=This field is required')).toHaveCount(4);
  });

  test('should validate email format on submit', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Fill form with invalid email
    await page.fill('#fullName', 'Test User');
    await page.fill('#email', 'invalid-email');
    await page.fill('#password', 'password123');
    await page.fill('#confirmPassword', 'password123');

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

    // Should still be on signup page (not navigating away means validation failed)
    await expect(page).toHaveURL(/\/signup/);
  });

  test('should show error for password mismatch', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Fill form with mismatched passwords
    await page.fill('#fullName', 'Test User');
    await page.fill('#email', 'test@example.com');
    await page.fill('#password', 'password123');
    await page.fill('#confirmPassword', 'different123');

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

    // Check for password mismatch error
    await expect(page.locator('text=Passwords do not match')).toBeVisible();
  });

  test('should show error for short password', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Fill form with short password
    await page.fill('#fullName', 'Test User');
    await page.fill('#email', 'test@example.com');
    await page.fill('#password', 'short');
    await page.fill('#confirmPassword', 'short');

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

    // Check for password length error
    await expect(page.locator('text=Password must be at least 8 characters')).toBeVisible();
  });

  test('should have password fields with visibility toggle', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    const passwordInput = page.locator('#password');

    // Wait for form to load
    await passwordInput.waitFor({ state: 'visible' });

    // Check initial type is password
    await expect(passwordInput).toHaveAttribute('type', 'password');

    // Verify password field is secure by default
    await passwordInput.fill('testpassword');
    await expect(passwordInput).toHaveAttribute('type', 'password');
  });

  test('should complete email signup flow', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup?plan=tier1');

    // Fill valid form
    const timestamp = Date.now();
    const email = `test${timestamp}@example.com`;

    await page.fill('#fullName', 'Test User');
    await page.fill('#email', email);
    await page.fill('#password', 'password123');
    await page.fill('#confirmPassword', 'password123');

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

    // Should redirect to verification page
    await expect(page).toHaveURL(/\/signup\/verify/);
    await expect(page.locator('h2')).toContainText('Verify your email');
  });

  test('should display Arabic version correctly', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/signup?plan=tier1');

    // Check Arabic text
    await expect(page.locator('h2')).toContainText('إنشاء حساب');
    await expect(page.locator('button:has-text("التسجيل بحساب Google")')).toBeVisible();

    // Check RTL direction
    await expect(page.locator('form')).toHaveAttribute('dir', 'rtl');
  });
});

test.describe('Email Verification Page', () => {
  test.beforeEach(async ({ page }) => {
    // Setup: Create a user first
    await page.goto('http://localhost:9000/en/signup');
    const timestamp = Date.now();
    await page.fill('#fullName', 'Test User');
    await page.fill('#email', `test${timestamp}@example.com`);
    await page.fill('#password', 'password123');
    await page.fill('#confirmPassword', 'password123');
    await page.locator('button[type="submit"]').click();
    await page.waitForURL(/\/signup\/verify/);
  });

  test('should display OTP input fields', async ({ page }) => {
    // Check for 6 OTP inputs
    const otpInputs = page.locator('input[type="text"][maxlength="1"]');
    await expect(otpInputs).toHaveCount(6);
  });

  test('should show resend timer', async ({ page }) => {
    await expect(page.locator('text=/Resend in \\d+s/')).toBeVisible();
  });

  test('should enable resend button after timer expires', async ({ page }) => {
    // This would take 60 seconds, so we'll just check the initial state
    await expect(page.locator('text=/Resend in/')).toBeVisible();
  });
});

test.describe('Company Information Page', () => {
  test('should display all form fields', async ({ page }) => {
    // Setup: Add signup data so we don't get redirected
    await page.goto('http://localhost:9000/en/signup');
    await page.evaluate(() => {
      localStorage.setItem('mawidi_signup_data', JSON.stringify({
        email: 'test@example.com',
        fullName: 'Test User',
        verified: true,
        createdAt: new Date().toISOString()
      }));
    });

    // Navigate to company info
    await page.goto('http://localhost:9000/en/signup/company-info');

    // Check main fields
    await expect(page.locator('#companyName')).toBeVisible();
    await expect(page.locator('#industry')).toBeVisible();
    await expect(page.locator('#companySize')).toBeVisible();
    await expect(page.locator('#gccCountry')).toBeVisible();
    await expect(page.locator('#phoneNumber')).toBeVisible();
    await expect(page.locator('#agentCount')).toBeVisible();
  });

  test('should have skip option', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/company-info');

    await expect(page.locator('button:has-text("Skip")')).toBeVisible();
  });

  test('should have industry dropdown', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/company-info');

    // Wait for select to be ready
    const industrySelect = page.locator('#industry');
    await expect(industrySelect).toBeVisible();

    // Can select an industry
    await industrySelect.selectOption('medical');
    await expect(industrySelect).toHaveValue('medical');
  });

  test('should have GCC country dropdown', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/company-info');

    // Wait for select to be ready
    const countrySelect = page.locator('#gccCountry');
    await expect(countrySelect).toBeVisible();

    // Can select a country
    await countrySelect.selectOption('sa');
    await expect(countrySelect).toHaveValue('sa');
  });
});

test.describe('Success Page', () => {
  test.beforeEach(async ({ page }) => {
    // Setup: Add mock signup data to localStorage
    await page.goto('http://localhost:9000/en/signup');
    await page.evaluate(() => {
      localStorage.setItem('mawidi_signup_data', JSON.stringify({
        email: 'test@example.com',
        fullName: 'Test User',
        verified: true,
        createdAt: new Date().toISOString(),
        companyInfo: {
          companyName: 'Test Company'
        }
      }));
    });
  });

  test('should display success message', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/success');

    // Wait for component to load
    await page.waitForTimeout(500);

    await expect(page.locator('h1')).toContainText('Thank you for signing up!');
  });

  test('should have dashboard link', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/success');

    // Wait for component to load
    await page.waitForTimeout(500);

    await expect(page.locator('a[href="/en/dashboard"]')).toBeVisible();
  });

  test('should display next steps', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/success');

    // Wait for component to load
    await page.waitForTimeout(500);

    await expect(page.locator('text=Next Steps:')).toBeVisible();
  });

  test('should show contact information', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup/success');

    // Use more specific selector
    await expect(page.locator('a[href="mailto:hello@mawidi.com"]').first()).toBeVisible();
  });
});

test.describe('Responsive Design', () => {
  test('should be mobile responsive', async ({ page }) => {
    // Set mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });
    await page.goto('http://localhost:9000/en/signup');

    // Check elements are visible on mobile
    await expect(page.locator('h2')).toBeVisible();
    await expect(page.locator('button:has-text("Sign up with Google")')).toBeVisible();
    await expect(page.locator('#fullName')).toBeVisible();
  });

  test('should be tablet responsive', async ({ page }) => {
    // Set tablet viewport
    await page.setViewportSize({ width: 768, height: 1024 });
    await page.goto('http://localhost:9000/en/signup/company-info');

    // Check grid layout works
    await expect(page.locator('#companyName')).toBeVisible();
    await expect(page.locator('#industry')).toBeVisible();
  });
});
