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

test.describe('i18n & RTL Testing - Auth Pages', () => {
  const baseUrl = 'http://localhost:9000';

  // =================================================================
  // TEST 1: ENGLISH LOGIN PAGE
  // =================================================================
  test.describe('English Login Page (/en/login)', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto(`${baseUrl}/en/login`);
      await page.waitForLoadState('networkidle');
    });

    test('should have correct HTML attributes for LTR', async ({ page }) => {
      // Check html dir attribute
      const htmlDir = await page.locator('html').getAttribute('dir');
      expect(htmlDir).toBe('ltr');

      // Check html lang attribute
      const htmlLang = await page.locator('html').getAttribute('lang');
      expect(htmlLang).toBe('en');

      // Check main element dir
      const mainDir = await page.locator('main').getAttribute('dir');
      expect(mainDir).toBe('ltr');
    });

    test('should display all text in English', async ({ page }) => {
      // Check heading
      const heading = await page.locator('h2').first().textContent();
      expect(heading).toContain('Log in');

      // Check subtitle
      const subtitle = await page.locator('p').first().textContent();
      expect(subtitle).toContain('Welcome back');

      // Check Google button
      const googleBtn = await page.locator('button').filter({ hasText: 'Continue with Google' }).textContent();
      expect(googleBtn).toContain('Continue with Google');

      // Check email label
      const emailLabel = await page.locator('label[for="email"]').textContent();
      expect(emailLabel).toContain('Email or Phone Number');

      // Check no Arabic text is present
      const bodyText = await page.locator('body').textContent();
      // Arabic Unicode range: \u0600-\u06FF
      const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');
      expect(hasArabic).toBe(false);
    });

    test('should have correct text alignment (left)', async ({ page }) => {
      // Check main content text alignment
      const mainTextAlign = await page.locator('main').evaluate((el) =>
        window.getComputedStyle(el).textAlign
      );
      // Should be 'left' or 'start' for LTR
      expect(['left', 'start']).toContain(mainTextAlign);
    });

    test('should have email input with LTR direction', async ({ page }) => {
      const emailInput = page.locator('input[type="text"]').first();

      // Email should always be LTR even on RTL pages
      const direction = await emailInput.evaluate((el) =>
        window.getComputedStyle(el).direction
      );

      // Can be either ltr or inherit (which will be ltr for English page)
      expect(['ltr', 'inherit']).toContain(direction);
    });

    test('should have buttons properly positioned', async ({ page }) => {
      const submitBtn = page.locator('button[type="submit"]').first();
      const btnBox = await submitBtn.boundingBox();

      expect(btnBox).not.toBeNull();
      expect(btnBox!.width).toBeGreaterThan(100); // Button should be visible
    });

    test('should have signup link in English', async ({ page }) => {
      const signupText = await page.locator('text=Don\'t have an account?').textContent();
      expect(signupText).toBeTruthy();

      const signupLink = page.locator('a[href="/en/signup"]');
      await expect(signupLink).toBeVisible();

      const linkText = await signupLink.textContent();
      expect(linkText).toContain('Sign up');
    });

    test('should have properly aligned form fields', async ({ page }) => {
      const formExists = await page.locator('form').count();
      expect(formExists).toBeGreaterThan(0);

      // Check that labels are to the left of or above inputs
      const labelBox = await page.locator('label[for="email"]').boundingBox();
      const inputBox = await page.locator('input[type="text"]').first().boundingBox();

      expect(labelBox).not.toBeNull();
      expect(inputBox).not.toBeNull();
    });
  });

  // =================================================================
  // TEST 2: ARABIC LOGIN PAGE
  // =================================================================
  test.describe('Arabic Login Page (/ar/login)', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto(`${baseUrl}/ar/login`);
      await page.waitForLoadState('networkidle');
    });

    test('should have correct HTML attributes for RTL', async ({ page }) => {
      // Check html dir attribute
      const htmlDir = await page.locator('html').getAttribute('dir');
      expect(htmlDir).toBe('rtl');

      // Check html lang attribute
      const htmlLang = await page.locator('html').getAttribute('lang');
      expect(htmlLang).toBe('ar');

      // Check main element dir
      const mainDir = await page.locator('main').getAttribute('dir');
      expect(mainDir).toBe('rtl');
    });

    test('should display all text in Arabic', async ({ page }) => {
      // Check heading
      const heading = await page.locator('h2').first().textContent();
      expect(heading).toContain('تسجيل الدخول');

      // Check subtitle
      const subtitle = await page.locator('p').first().textContent();
      expect(subtitle).toContain('مرحباً بعودتك');

      // Check Google button text
      const googleBtn = await page.locator('button').filter({ hasText: 'Google' }).first().textContent();
      expect(googleBtn).toMatch(/المتابعة مع Google|Google/);

      // Check email label
      const emailLabel = await page.locator('label[for="email"]').textContent();
      expect(emailLabel).toContain('البريد الإلكتروني');

      // Verify Arabic text is present
      const bodyText = await page.locator('body').textContent();
      const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');
      expect(hasArabic).toBe(true);
    });

    test('should have correct text alignment (right)', async ({ page }) => {
      // Check main content text alignment
      const mainTextAlign = await page.locator('main').evaluate((el) =>
        window.getComputedStyle(el).textAlign
      );
      // Should be 'right' or 'start' for RTL (start means right in RTL context)
      expect(['right', 'start']).toContain(mainTextAlign);
    });

    test('should have email input with LTR direction (emails are always LTR)', async ({ page }) => {
      const emailInput = page.locator('input[type="text"]').first();

      // Email input should be LTR even on Arabic page
      const direction = await emailInput.evaluate((el) =>
        window.getComputedStyle(el).direction
      );

      // Even though page is RTL, email field should ideally be LTR or inherit
      // This is acceptable as long as it works correctly
      expect(direction).toBeTruthy();
    });

    test('should have password toggle icon on correct side (left for RTL)', async ({ page }) => {
      // First switch to password mode
      const usePasswordBtn = page.locator('text=استخدم كلمة المرور');

      if (await usePasswordBtn.count() > 0) {
        await usePasswordBtn.click();
        await page.waitForTimeout(500);

        // Check if eye icon exists and is positioned correctly
        const eyeIcon = page.locator('button[aria-label*="password"]').first();

        if (await eyeIcon.count() > 0) {
          const iconBox = await eyeIcon.boundingBox();
          const inputBox = await page.locator('input[type="password"]').first().boundingBox();

          if (iconBox && inputBox) {
            // Icon should be on the LEFT side for RTL
            expect(iconBox.x).toBeLessThan(inputBox.x + inputBox.width / 2);
          }
        }
      }
    });

    test('should have signup link in Arabic', async ({ page }) => {
      const signupText = await page.locator('text=ليس لديك حساب؟').textContent();
      expect(signupText).toBeTruthy();

      const signupLink = page.locator('a[href="/ar/signup"]');
      await expect(signupLink).toBeVisible();

      const linkText = await signupLink.textContent();
      expect(linkText).toContain('إنشاء حساب');
    });

    test('should not have untranslated English text (except brand names)', async ({ page }) => {
      const bodyText = await page.locator('body').textContent();

      // Common English words that shouldn't appear (except in brand names)
      const englishWords = ['Login', 'Email or Phone', 'Password', 'Welcome back', 'Sign up'];

      for (const word of englishWords) {
        // These shouldn't appear in Arabic version
        const hasEnglish = bodyText?.includes(word);
        if (hasEnglish) {
          console.log(`Warning: Found English text "${word}" on Arabic page`);
        }
      }

      // At minimum, check main heading is in Arabic
      const mainHeading = await page.locator('h2').first().textContent();
      const isArabic = /[\u0600-\u06FF]/.test(mainHeading || '');
      expect(isArabic).toBe(true);
    });
  });

  // =================================================================
  // TEST 3: ENGLISH SIGNUP PAGE
  // =================================================================
  test.describe('English Signup Page (/en/signup)', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto(`${baseUrl}/en/signup`);
      await page.waitForLoadState('networkidle');
    });

    test('should have correct HTML attributes for LTR', async ({ page }) => {
      const htmlDir = await page.locator('html').getAttribute('dir');
      expect(htmlDir).toBe('ltr');

      const htmlLang = await page.locator('html').getAttribute('lang');
      expect(htmlLang).toBe('en');
    });

    test('should display all text in English', async ({ page }) => {
      // Wait for content to load (could be on package selection or info form)
      await page.waitForTimeout(1000);

      // Check for English text
      const bodyText = await page.locator('body').textContent();

      // Should have common English signup words
      const hasEnglishContent =
        bodyText?.includes('Create') ||
        bodyText?.includes('Sign up') ||
        bodyText?.includes('Package') ||
        bodyText?.includes('Professional');

      expect(hasEnglishContent).toBe(true);

      // Should not have Arabic
      const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');
      expect(hasArabic).toBe(false);
    });

    test('should have correct text alignment (left)', async ({ page }) => {
      const bodyTextAlign = await page.locator('body').evaluate((el) =>
        window.getComputedStyle(el).textAlign
      );
      expect(['left', 'start']).toContain(bodyTextAlign);
    });

    test('should have login link in English', async ({ page }) => {
      const loginLink = page.locator('a[href="/en/login"]');

      if (await loginLink.count() > 0) {
        await expect(loginLink).toBeVisible();
        const linkText = await loginLink.textContent();
        expect(linkText?.toLowerCase()).toMatch(/log in|sign in/);
      }
    });
  });

  // =================================================================
  // TEST 4: ARABIC SIGNUP PAGE
  // =================================================================
  test.describe('Arabic Signup Page (/ar/signup)', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto(`${baseUrl}/ar/signup`);
      await page.waitForLoadState('networkidle');
    });

    test('should have correct HTML attributes for RTL', async ({ page }) => {
      const htmlDir = await page.locator('html').getAttribute('dir');
      expect(htmlDir).toBe('rtl');

      const htmlLang = await page.locator('html').getAttribute('lang');
      expect(htmlLang).toBe('ar');
    });

    test('should display all text in Arabic', async ({ page }) => {
      await page.waitForTimeout(1000);

      const bodyText = await page.locator('body').textContent();

      // Should have Arabic content
      const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');
      expect(hasArabic).toBe(true);

      // Common Arabic words that should appear
      const hasArabicSignupContent =
        bodyText?.includes('إنشاء') ||
        bodyText?.includes('حساب') ||
        bodyText?.includes('الباقة') ||
        bodyText?.includes('المحترف');

      expect(hasArabicSignupContent).toBe(true);
    });

    test('should have correct text alignment (right)', async ({ page }) => {
      const bodyTextAlign = await page.locator('body').evaluate((el) =>
        window.getComputedStyle(el).textAlign
      );
      expect(['right', 'start']).toContain(bodyTextAlign);
    });

    test('should have login link in Arabic', async ({ page }) => {
      const loginLink = page.locator('a[href="/ar/login"]');

      if (await loginLink.count() > 0) {
        await expect(loginLink).toBeVisible();
        const linkText = await loginLink.textContent();
        expect(linkText).toMatch(/تسجيل الدخول|الدخول/);
      }
    });
  });

  // =================================================================
  // TEST 5: LANGUAGE SWITCHING
  // =================================================================
  test.describe('Language Switching Functionality', () => {
    test('should switch from English to Arabic on login page', async ({ page }) => {
      // Start on English
      await page.goto(`${baseUrl}/en/login`);
      await page.waitForLoadState('networkidle');

      // Verify we're on English
      let heading = await page.locator('h2').first().textContent();
      expect(heading).toContain('Log in');

      // Look for language switcher (could be a link or button)
      const langSwitcher = page.locator('a[href="/ar/login"], a[href*="/ar"]').first();

      if (await langSwitcher.count() > 0) {
        await langSwitcher.click();
        await page.waitForLoadState('networkidle');

        // Should be on Arabic version now
        expect(page.url()).toContain('/ar/login');

        // Check dir changed to RTL
        const htmlDir = await page.locator('html').getAttribute('dir');
        expect(htmlDir).toBe('rtl');

        // Check content is in Arabic
        heading = await page.locator('h2').first().textContent();
        expect(heading).toContain('تسجيل الدخول');
      } else {
        console.log('Language switcher not found on login page');
      }
    });

    test('should switch from Arabic to English on signup page', async ({ page }) => {
      // Start on Arabic
      await page.goto(`${baseUrl}/ar/signup`);
      await page.waitForLoadState('networkidle');

      // Verify we're on Arabic
      const bodyText = await page.locator('body').textContent();
      const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');
      expect(hasArabic).toBe(true);

      // Look for language switcher
      const langSwitcher = page.locator('a[href="/en/signup"], a[href*="/en"]').first();

      if (await langSwitcher.count() > 0) {
        await langSwitcher.click();
        await page.waitForLoadState('networkidle');

        // Should be on English version now
        expect(page.url()).toContain('/en/signup');

        // Check dir changed to LTR
        const htmlDir = await page.locator('html').getAttribute('dir');
        expect(htmlDir).toBe('ltr');

        // Check content is in English
        const newBodyText = await page.locator('body').textContent();
        const hasEnglish =
          newBodyText?.includes('Create') ||
          newBodyText?.includes('Sign up') ||
          newBodyText?.includes('Package');
        expect(hasEnglish).toBe(true);
      } else {
        console.log('Language switcher not found on signup page');
      }
    });

    test('should preserve route when switching languages', async ({ page }) => {
      await page.goto(`${baseUrl}/en/login`);
      await page.waitForLoadState('networkidle');

      const langSwitcher = page.locator('a[href="/ar/login"]').first();

      if (await langSwitcher.count() > 0) {
        await langSwitcher.click();
        await page.waitForLoadState('networkidle');

        // Should be on /ar/login (not /ar or /ar/something-else)
        expect(page.url()).toBe(`${baseUrl}/ar/login`);
      }
    });
  });

  // =================================================================
  // TEST 6: FORM BEHAVIOR & ERROR MESSAGES
  // =================================================================
  test.describe('Form Validation i18n', () => {
    test('should show English error messages on English login', async ({ page }) => {
      await page.goto(`${baseUrl}/en/login`);
      await page.waitForLoadState('networkidle');

      // Try to submit empty form (if OTP is default)
      const submitBtn = page.locator('button[type="submit"]').first();
      await submitBtn.click();
      await page.waitForTimeout(500);

      // Look for error message
      const errorText = await page.locator('[class*="red"], [class*="error"], [role="alert"]').first().textContent();

      if (errorText) {
        // Should be in English
        const hasEnglishError =
          errorText.includes('required') ||
          errorText.includes('field') ||
          errorText.includes('This');

        expect(hasEnglishError).toBe(true);
      }
    });

    test('should show Arabic error messages on Arabic login', async ({ page }) => {
      await page.goto(`${baseUrl}/ar/login`);
      await page.waitForLoadState('networkidle');

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

      // Look for error message
      const errorText = await page.locator('[class*="red"], [class*="error"], [role="alert"]').first().textContent();

      if (errorText) {
        // Should be in Arabic
        const hasArabic = /[\u0600-\u06FF]/.test(errorText || '');
        expect(hasArabic).toBe(true);
      }
    });
  });

  // =================================================================
  // TEST 7: VISUAL LAYOUT CONSISTENCY
  // =================================================================
  test.describe('Visual Layout Consistency', () => {
    test('English and Arabic login pages should have similar structure', async ({ page }) => {
      // Test English
      await page.goto(`${baseUrl}/en/login`);
      await page.waitForLoadState('networkidle');

      const enButtonCount = await page.locator('button').count();
      const enInputCount = await page.locator('input').count();
      const enLinkCount = await page.locator('a').count();

      // Test Arabic
      await page.goto(`${baseUrl}/ar/login`);
      await page.waitForLoadState('networkidle');

      const arButtonCount = await page.locator('button').count();
      const arInputCount = await page.locator('input').count();
      const arLinkCount = await page.locator('a').count();

      // Should have same number of interactive elements
      expect(arButtonCount).toBe(enButtonCount);
      expect(arInputCount).toBe(enInputCount);
      // Link count might vary slightly due to language switcher
      expect(Math.abs(arLinkCount - enLinkCount)).toBeLessThanOrEqual(2);
    });

    test('Text should not overflow containers in either language', async ({ page }) => {
      const urls = [
        `${baseUrl}/en/login`,
        `${baseUrl}/ar/login`,
        `${baseUrl}/en/signup`,
        `${baseUrl}/ar/signup`,
      ];

      for (const url of urls) {
        await page.goto(url);
        await page.waitForLoadState('networkidle');

        // Check all buttons for overflow
        const buttons = await page.locator('button').all();

        for (const button of buttons) {
          const scrollWidth = await button.evaluate((el) => el.scrollWidth);
          const clientWidth = await button.evaluate((el) => el.clientWidth);

          // Allow 2px tolerance for rounding
          expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 2);
        }
      }
    });
  });
});
