import { test, expect } from '@playwright/test';
import { generateTestId, acceptCookieConsent } from '../helpers/utils';

test.describe('Registration Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Start at registration page
    await page.goto('/register');
    // Accept cookie consent if present
    await acceptCookieConsent(page);
  });

  test('should display registration form', async ({ page }) => {
    // Verify registration form elements (support both English and Spanish)
    await expect(page.getByLabel(/email|correo/i)).toBeVisible();
    await expect(page.getByRole('textbox', { name: /password|contraseña/i }).first()).toBeVisible();

    // Look for submit button
    const submitButton = page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i });
    await expect(submitButton).toBeVisible();
  });

  test('should successfully register a new user', async ({ page }) => {
    // Generate unique test credentials
    const testEmail = `test-${generateTestId()}@bakery.com`;
    const testPassword = 'Test123!@#Password';

    // Fill in registration form
    await page.getByLabel(/email|correo/i).fill(testEmail);

    // Find password fields
    const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });
    await passwordFields.first().fill(testPassword);

    // If there's a confirm password field
    const count = await passwordFields.count();
    if (count > 1) {
      await passwordFields.nth(1).fill(testPassword);
    }

    // Fill additional fields if they exist
    const nameField = page.getByLabel(/name|nombre/i);
    if (await nameField.isVisible().catch(() => false)) {
      await nameField.fill('Test User');
    }

    const companyField = page.getByLabel(/company|bakery|panadería/i);
    if (await companyField.isVisible().catch(() => false)) {
      await companyField.fill('Test Bakery');
    }

    // Accept terms if checkbox exists
    const termsCheckbox = page.getByLabel(/terms|accept|acepto/i);
    if (await termsCheckbox.isVisible().catch(() => false)) {
      await termsCheckbox.check();
    }

    // Submit form
    await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

    // Should redirect to onboarding or dashboard
    await expect(page).toHaveURL(/\/(app|dashboard|onboarding)/, { timeout: 15000 });
  });

  test('should show validation error for invalid email format', async ({ page }) => {
    // Fill in invalid email
    await page.getByLabel(/email|correo/i).fill('invalid-email');

    const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });
    await passwordFields.first().fill('ValidPassword123!');

    // Submit
    await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

    // Should show email validation error
    await expect(page.locator('body')).toContainText(/valid email|email válido|formato/i, {
      timeout: 5000,
    });
  });

  test('should show error for weak password', async ({ page }) => {
    const testEmail = `test-${generateTestId()}@bakery.com`;

    await page.getByLabel(/email|correo/i).fill(testEmail);

    const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });
    await passwordFields.first().fill('123'); // Weak password

    const count = await passwordFields.count();
    if (count > 1) {
      await passwordFields.nth(1).fill('123');
    }

    await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

    // Should show password strength error
    await expect(page.locator('body')).toContainText(
      /password.*strong|contraseña.*fuerte|weak|débil|minimum|mínimo/i,
      { timeout: 5000 }
    );
  });

  test('should show error when passwords do not match', async ({ page }) => {
    const testEmail = `test-${generateTestId()}@bakery.com`;

    await page.getByLabel(/email|correo/i).fill(testEmail);

    const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });

    // Only test if there are multiple password fields (password + confirm)
    const count = await passwordFields.count();
    if (count > 1) {
      await passwordFields.first().fill('Password123!');
      await passwordFields.nth(1).fill('DifferentPassword123!');

      await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

      // Should show mismatch error
      await expect(page.locator('body')).toContainText(/match|coincide|igual/i, {
        timeout: 5000,
      });
    }
  });

  test('should show error for already registered email', async ({ page }) => {
    // Try to register with an email that's already in use
    await page.getByLabel(/email|correo/i).fill('existing@bakery.com');

    const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });
    await passwordFields.first().fill('ValidPassword123!');

    const count = await passwordFields.count();
    if (count > 1) {
      await passwordFields.nth(1).fill('ValidPassword123!');
    }

    await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

    // Should show error about email already existing
    await expect(page.locator('body')).toContainText(
      /already.*exist|ya.*existe|already.*registered|ya.*registrado/i,
      { timeout: 5000 }
    );
  });

  test('should have link to login page', async ({ page }) => {
    // Look for login link or button
    const loginLink = page.getByRole('link', { name: /log in|sign in|iniciar sesión/i });
    const loginButton = page.getByRole('button', { name: /log in|sign in|iniciar sesión/i });

    const isLinkVisible = await loginLink.isVisible({ timeout: 2000 }).catch(() => false);
    const isButtonVisible = await loginButton.isVisible({ timeout: 2000 }).catch(() => false);

    if (isLinkVisible) {
      await expect(loginLink).toHaveAttribute('href', /\/login/);
    } else if (isButtonVisible) {
      await expect(loginButton).toBeVisible();
    }
  });

  test('should require acceptance of terms and conditions', async ({ page }) => {
    const termsCheckbox = page.getByLabel(/terms|accept|acepto/i);

    // Only test if terms checkbox exists
    if (await termsCheckbox.isVisible().catch(() => false)) {
      const testEmail = `test-${generateTestId()}@bakery.com`;

      await page.getByLabel(/email|correo/i).fill(testEmail);

      const passwordFields = page.getByRole('textbox', { name: /password|contraseña/i });
      await passwordFields.first().fill('ValidPassword123!');

      const count = await passwordFields.count();
      if (count > 1) {
        await passwordFields.nth(1).fill('ValidPassword123!');
      }

      // Try to submit without checking terms
      await page.getByRole('button', { name: /register|sign up|crear cuenta|registrar/i }).click();

      // Should show error or prevent submission
      await expect(page.locator('body')).toContainText(/terms|accept|acepto|required/i, {
        timeout: 5000,
      });
    }
  });
});
