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

/**
 * Signup Page UI Validation Tests
 *
 * Validates that the signup page meets production quality standards:
 * - Theme color consistency (brand-green for CTAs)
 * - Button styling and states
 * - Responsive layouts
 * - RTL/LTR support
 * - Accessibility standards
 */

test.describe('Signup Page UI Validation', () => {

  test.describe('Theme Consistency - English', () => {

    test('submit button should use brand-green color', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Locate the submit button
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account|Loading/ });

      // Verify brand-green background color is applied
      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('bg-brand-green');
      expect(buttonClasses).not.toContain('bg-neutral-400');
      expect(buttonClasses).not.toContain('bg-gray');
    });

    test('submit button should have proper hover state', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account|Loading/ });
      const buttonClasses = await submitButton.getAttribute('class');

      // Verify hover class includes brand-green with opacity
      expect(buttonClasses).toMatch(/hover:bg-brand-green\/90|hover:bg-brand-greenHover/);
    });

    test('submit button should have focus ring', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account|Loading/ });
      const buttonClasses = await submitButton.getAttribute('class');

      // Verify focus ring is present
      expect(buttonClasses).toContain('focus:ring-2');
      expect(buttonClasses).toContain('focus:ring-brand-green/20');
    });

    test('Google OAuth button should maintain white background', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      const googleButton = page.locator('button').filter({ hasText: /Sign up with Google/ });
      const buttonClasses = await googleButton.getAttribute('class');

      // Verify white background with border
      expect(buttonClasses).toContain('bg-white');
      expect(buttonClasses).toContain('border');
      expect(buttonClasses).not.toContain('bg-brand-green');
    });

  });

  test.describe('Theme Consistency - Arabic (RTL)', () => {

    test('submit button should use brand-green color in RTL layout', async ({ page }) => {
      await page.goto('http://localhost:9000/ar/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /إنشاء الحساب|جاري التحميل/ });

      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('bg-brand-green');
      expect(buttonClasses).not.toContain('bg-neutral-400');
    });

    test('RTL layout should mirror password visibility icons correctly', async ({ page }) => {
      await page.goto('http://localhost:9000/ar/signup');

      // Password visibility buttons should be on the left in RTL
      const visibilityButtons = page.locator('button').filter({ has: page.locator('svg') }).filter({ hasNot: page.locator('text') });
      const firstButton = visibilityButtons.first();
      const buttonClasses = await firstButton.getAttribute('class');

      // In RTL, icon should be on left
      expect(buttonClasses).toContain('left-3');
    });

  });

  test.describe('Responsive Layout Validation', () => {

    test('desktop layout should center form correctly', async ({ page }) => {
      await page.setViewportSize({ width: 1920, height: 1080 });
      await page.goto('http://localhost:9000/en/signup');

      // Form container should have max-width
      const formContainer = page.locator('main > div').first();
      const containerClasses = await formContainer.getAttribute('class');

      expect(containerClasses).toContain('max-w-md');
      expect(containerClasses).toMatch(/mx-auto|items-center/);
    });

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

      // Verify no horizontal scroll
      const bodyWidth = await page.evaluate(() => document.body.scrollWidth);
      const viewportWidth = await page.evaluate(() => window.innerWidth);
      expect(bodyWidth).toBeLessThanOrEqual(viewportWidth);

      // Submit button should be full width
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });
      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('w-full');
    });

    test('mobile buttons should meet touch target size requirements', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('http://localhost:9000/en/signup');

      // Submit button should be at least 44px tall
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });
      const boundingBox = await submitButton.boundingBox();

      expect(boundingBox).not.toBeNull();
      expect(boundingBox!.height).toBeGreaterThanOrEqual(44);
    });

  });

  test.describe('Button States Validation', () => {

    test('submit button should be enabled when form is ready', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });

      // Initially should be enabled
      await expect(submitButton).toBeEnabled();
    });

    test('submit button should show loading state when clicked', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Fill form with valid data
      await page.fill('input[id="fullName"]', 'Test User');
      await page.fill('input[id="email"]', 'test@example.com');
      await page.fill('input[id="password"]', 'SecurePass123!@#');
      await page.fill('input[id="confirmPassword"]', 'SecurePass123!@#');

      const submitButton = page.locator('button[type="submit"]');

      // Click and verify loading state appears
      await submitButton.click();

      // Should show loading text (will fail fast due to missing CSRF, but we can see state change)
      await expect(submitButton).toHaveText(/Loading|جاري التحميل/);
    });

    test('disabled button should have reduced opacity', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Fill form to trigger validation
      await page.fill('input[id="fullName"]', 'Test User');
      await page.fill('input[id="email"]', 'test@example.com');
      await page.fill('input[id="password"]', 'SecurePass123!@#');
      await page.fill('input[id="confirmPassword"]', 'SecurePass123!@#');

      const submitButton = page.locator('button[type="submit"]');

      // Click to trigger loading state (which disables button)
      await submitButton.click();

      // Verify disabled attribute and opacity class
      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('disabled:opacity-50');
    });

  });

  test.describe('Visual Regression - Button Appearance', () => {

    test('submit button should visually match brand-green theme', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Take screenshot of submit button
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });

      // Verify button is visible and has correct styling
      await expect(submitButton).toBeVisible();

      // Get computed background color (should be brand-green #10B981)
      const bgColor = await submitButton.evaluate((el) => {
        return window.getComputedStyle(el).backgroundColor;
      });

      // RGB values for #10B981 are approximately rgb(16, 185, 129)
      // Allow some tolerance for browser rendering
      expect(bgColor).toMatch(/rgb\(1[0-9], 18[0-9], 12[0-9]\)/);
    });

    test('submit button should have visible white text', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });

      const textColor = await submitButton.evaluate((el) => {
        return window.getComputedStyle(el).color;
      });

      // White text should be rgb(255, 255, 255)
      expect(textColor).toMatch(/rgb\(255, 255, 255\)/);
    });

  });

  test.describe('Input Focus States', () => {

    test('inputs should have brand-green focus ring', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Test email input focus
      const emailInput = page.locator('input[id="email"]');
      await emailInput.focus();

      const inputClasses = await emailInput.getAttribute('class');
      expect(inputClasses).toContain('focus:border-brand-green');
      expect(inputClasses).toContain('focus:ring-brand-green/20');
    });

    test('password visibility toggle should be accessible', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Locate password visibility toggle
      const passwordToggle = page.locator('button[type="button"]').filter({ has: page.locator('svg') }).first();

      // Should be visible and clickable
      await expect(passwordToggle).toBeVisible();
      await passwordToggle.click();

      // Password input should change type
      const passwordInput = page.locator('input[id="password"]');
      const inputType = await passwordInput.getAttribute('type');
      expect(inputType).toBe('text');
    });

  });

  test.describe('Error Message Styling', () => {

    test('error messages should be visible and styled correctly', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Submit empty form to trigger validation errors
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });
      await submitButton.click();

      // Wait for validation error
      await page.waitForTimeout(500);

      // Error messages should be red and visible
      const errorMessage = page.locator('p.text-red-600').first();

      if (await errorMessage.isVisible()) {
        const errorClasses = await errorMessage.getAttribute('class');
        expect(errorClasses).toContain('text-red-600');
        expect(errorClasses).toContain('text-xs');
      }
    });

  });

  test.describe('Cross-Browser Consistency', () => {

    test('button styling should be consistent across browsers', async ({ page, browserName }) => {
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });

      // Verify button is visible in all browsers
      await expect(submitButton).toBeVisible();

      // Verify classes are applied (Tailwind should work across browsers)
      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('bg-brand-green');

      console.log(`✅ ${browserName}: Submit button has brand-green color`);
    });

  });

  test.describe('Accessibility Compliance', () => {

    test('form should have proper labels and ARIA attributes', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // All inputs should have associated labels
      const nameInput = page.locator('input[id="fullName"]');
      const nameLabel = page.locator('label[for="fullName"]');

      await expect(nameLabel).toBeVisible();
      await expect(nameInput).toBeVisible();

      // Verify label association
      const labelFor = await nameLabel.getAttribute('for');
      const inputId = await nameInput.getAttribute('id');
      expect(labelFor).toBe(inputId);
    });

    test('error messages should be associated with form fields', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

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

      // Check if error messages appear near their fields
      const emailError = page.locator('p.text-red-600').filter({ hasText: /required|invalid/i }).first();

      if (await emailError.isVisible()) {
        // Error should be close to the input field (within same parent)
        const errorText = await emailError.textContent();
        expect(errorText).toBeTruthy();
      }
    });

  });

  test.describe('Visual Comparison - Before/After Fix', () => {

    test('screenshot comparison - submit button should be green', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Scroll to submit button
      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });
      await submitButton.scrollIntoViewIfNeeded();

      // Take screenshot of the button area
      await submitButton.screenshot({
        path: 'claudedocs/signup-ui-validation/submit-button-after-fix.png'
      });

      // Verify button is visible with brand color
      const bgColor = await submitButton.evaluate((el) => {
        return window.getComputedStyle(el).backgroundColor;
      });

      // Should be brand-green (#10B981 = rgb(16, 185, 129))
      expect(bgColor).toMatch(/rgb\(1[0-9], 18[0-9], 12[0-9]\)/);
    });

  });

  test.describe('Responsive Button Styling', () => {

    test('submit button should maintain brand-green on mobile', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });

      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('bg-brand-green');
      expect(buttonClasses).toContain('w-full');
    });

    test('submit button should meet mobile touch target size', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('http://localhost:9000/en/signup');

      const submitButton = page.locator('button[type="submit"]').filter({ hasText: /Create Account/ });
      const boundingBox = await submitButton.boundingBox();

      expect(boundingBox).not.toBeNull();
      expect(boundingBox!.height).toBeGreaterThanOrEqual(44); // WCAG minimum
      expect(boundingBox!.width).toBeGreaterThanOrEqual(44);
    });

  });

  test.describe('Button State Consistency', () => {

    test('disabled button should maintain brand-green with opacity', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Fill form and trigger loading state
      await page.fill('input[id="fullName"]', 'Test User');
      await page.fill('input[id="email"]', `test-${Date.now()}@example.com`);
      await page.fill('input[id="password"]', 'SecurePass123!@#');
      await page.fill('input[id="confirmPassword"]', 'SecurePass123!@#');

      const submitButton = page.locator('button[type="submit"]');

      // Click to trigger loading/disabled state
      await submitButton.click();

      // Verify classes still include brand-green (color should remain, just with opacity)
      const buttonClasses = await submitButton.getAttribute('class');
      expect(buttonClasses).toContain('bg-brand-green');
      expect(buttonClasses).toContain('disabled:opacity-50');
    });

  });

  test.describe('Overall Page Quality', () => {

    test('page should have no console errors on load', async ({ page }) => {
      const consoleErrors: string[] = [];

      page.on('console', msg => {
        if (msg.type() === 'error') {
          consoleErrors.push(msg.text());
        }
      });

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

      // Should have no JavaScript errors
      expect(consoleErrors.length).toBe(0);
    });

    test('page should load all required resources', async ({ page }) => {
      const failedRequests: string[] = [];

      page.on('response', response => {
        if (!response.ok() && !response.url().includes('favicon')) {
          failedRequests.push(`${response.status()} ${response.url()}`);
        }
      });

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

      // All resources should load successfully (except favicon)
      expect(failedRequests.length).toBe(0);
    });

  });

  test.describe('Brand Consistency Across Pages', () => {

    test('navigation Sign Up button should use brand-green', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Nav signup button should also use brand-green
      const navSignupButton = page.locator('nav a[href*="signup"]').last();

      if (await navSignupButton.isVisible()) {
        const buttonClasses = await navSignupButton.getAttribute('class');
        expect(buttonClasses).toMatch(/bg-brand-green|text-brand-green/);
      }
    });

    test('footer CTA buttons should maintain brand consistency', async ({ page }) => {
      await page.goto('http://localhost:9000/en/signup');

      // Footer "Start Free" button should use brand-green
      const footerCTA = page.locator('footer a').filter({ hasText: /Start Free|ابدأ مجاناً/ });

      if (await footerCTA.isVisible()) {
        const buttonClasses = await footerCTA.getAttribute('class');
        expect(buttonClasses).toContain('bg-brand-green');
      }
    });

  });

});

test.describe('Performance Metrics', () => {

  test('page should have acceptable Core Web Vitals', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup');
    await page.waitForLoadState('networkidle');

    // Note: These are basic checks. Full performance testing requires Lighthouse
    const performanceMetrics = await page.evaluate(() => {
      const perfData = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
      return {
        loadTime: perfData.loadEventEnd - perfData.loadEventStart,
        domContentLoaded: perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart,
      };
    });

    // Log performance for monitoring
    console.log('Performance Metrics:', performanceMetrics);

    // Basic assertion - page should load in reasonable time
    expect(performanceMetrics.loadTime).toBeLessThan(5000);
  });

});
