/**
 * Comprehensive Internationalization (i18n) and RTL Testing Suite
 * Tests all critical pages in both Arabic (RTL) and English (LTR)
 *
 * Test Coverage:
 * 1. Language switching functionality
 * 2. RTL/LTR layout correctness
 * 3. Translation completeness
 * 4. Direction-specific CSS
 * 5. Forms in both directions
 * 6. Navigation consistency
 * 7. Locale-aware formatting (dates, numbers)
 */

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

// Configure for port 9000
const BASE_URL = 'http://localhost:9000';

/**
 * Helper to check if HTML has correct direction attribute
 */
async function checkDirection(page: Page, expectedDir: 'rtl' | 'ltr', expectedLang: 'ar' | 'en') {
  const dir = await page.locator('html').getAttribute('dir');
  const lang = await page.locator('html').getAttribute('lang');

  expect(dir).toBe(expectedDir);
  expect(lang).toBe(expectedLang);
}

/**
 * Helper to check if navigation is present and functional
 */
async function checkNavigation(page: Page) {
  const nav = page.locator('nav');
  await expect(nav).toBeVisible();

  // Check for language switcher
  const langSwitcher = page.locator('[data-testid="lang-switcher"], .lang-switcher, button:has-text("AR"), button:has-text("EN")').first();
  await expect(langSwitcher).toBeVisible();
}

/**
 * Helper to check for missing translation keys (showing {{key}} or t.key)
 */
async function checkForMissingTranslations(page: Page) {
  const bodyText = await page.locator('body').textContent();

  // Check for common patterns of missing translations
  const missingPatterns = [
    /\{\{[\w.]+\}\}/,  // {{key.path}}
    /t\.[\w.]+/,       // t.key.path
    /\[object Object\]/i,
  ];

  for (const pattern of missingPatterns) {
    if (bodyText && pattern.test(bodyText)) {
      // Get a snippet of where it appears
      const match = bodyText.match(pattern);
      console.warn(`⚠️ Possible missing translation: ${match?.[0]}`);
    }
  }
}

test.describe('i18n: Homepage', () => {
  test('Arabic homepage - RTL layout and translations', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'rtl', 'ar');
    await checkNavigation(page);
    await checkForMissingTranslations(page);

    // Check text alignment
    const mainHeading = page.locator('h1').first();
    if (await mainHeading.isVisible()) {
      const textAlign = await mainHeading.evaluate(el =>
        window.getComputedStyle(el).textAlign
      );
      // RTL should have right or start alignment
      expect(['right', 'start'].includes(textAlign)).toBeTruthy();
    }

    // Check Arabic content present
    const bodyText = await page.locator('body').textContent();
    expect(bodyText).toMatch(/[\u0600-\u06FF]/); // Arabic Unicode range
  });

  test('English homepage - LTR layout and translations', async ({ page }) => {
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'ltr', 'en');
    await checkNavigation(page);
    await checkForMissingTranslations(page);
  });

  test('Language switching preserves route', async ({ page }) => {
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

    // Find and click language switcher
    const langSwitcher = page.locator('[data-testid="lang-switcher"], .lang-switcher, button:has-text("AR"), a:has-text("AR")').first();

    if (await langSwitcher.isVisible()) {
      await langSwitcher.click();
      await page.waitForLoadState('networkidle');

      // Should be on Arabic version
      expect(page.url()).toContain('/ar');
      await checkDirection(page, 'rtl', 'ar');
    }
  });
});

test.describe('i18n: Industry Pages', () => {
  const industries = [
    { path: 'healthcare', ar: 'healthcare', en: 'healthcare' },
    { path: 'beauty-wellness', ar: 'beauty-wellness', en: 'beauty-wellness' },
    { path: 'hotels-accommodation', ar: 'hotels-accommodation', en: 'hotels-accommodation' },
    { path: 'retail', ar: 'retail', en: 'retail' },
  ];

  for (const industry of industries) {
    test(`${industry.path} - Arabic version`, async ({ page }) => {
      await page.goto(`${BASE_URL}/ar/industries/${industry.ar}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'rtl', 'ar');
      await checkForMissingTranslations(page);

      // Page should load without 404
      expect(page.url()).toContain(`/ar/industries/${industry.ar}`);
    });

    test(`${industry.path} - English version`, async ({ page }) => {
      await page.goto(`${BASE_URL}/en/industries/${industry.en}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'ltr', 'en');
      await checkForMissingTranslations(page);
    });
  }
});

test.describe('i18n: Service × Location Pages', () => {
  const combinations = [
    { location: 'qatar', service: 'medical-appointment-scheduling' },
    { location: 'qatar', service: 'beauty-salon-booking' },
    { location: 'uae', service: 'medical-appointment-scheduling' },
    { location: 'saudi-arabia', service: 'beauty-salon-booking' },
    { location: 'kuwait', service: 'medical-appointment-scheduling' },
  ];

  for (const combo of combinations) {
    test(`${combo.location}/${combo.service} - Arabic`, async ({ page }) => {
      await page.goto(`${BASE_URL}/ar/${combo.location}/${combo.service}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'rtl', 'ar');
      await checkForMissingTranslations(page);
    });

    test(`${combo.location}/${combo.service} - English`, async ({ page }) => {
      await page.goto(`${BASE_URL}/en/${combo.location}/${combo.service}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'ltr', 'en');
      await checkForMissingTranslations(page);
    });
  }
});

test.describe('i18n: Authentication Pages', () => {
  test('Signup - Arabic RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar/signup`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'rtl', 'ar');
    await checkForMissingTranslations(page);

    // Check form direction
    const form = page.locator('form').first();
    if (await form.isVisible()) {
      const direction = await form.evaluate(el =>
        window.getComputedStyle(el).direction
      );
      expect(direction).toBe('rtl');
    }
  });

  test('Signup - English LTR', async ({ page }) => {
    await page.goto(`${BASE_URL}/en/signup`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'ltr', 'en');
    await checkForMissingTranslations(page);
  });

  test('Login - Arabic RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar/login`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'rtl', 'ar');
    await checkForMissingTranslations(page);
  });

  test('Login - English LTR', async ({ page }) => {
    await page.goto(`${BASE_URL}/en/login`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'ltr', 'en');
    await checkForMissingTranslations(page);
  });

  test('Forgot Password - Arabic RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar/forgot-password`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'rtl', 'ar');
    await checkForMissingTranslations(page);
  });

  test('Forgot Password - English LTR', async ({ page }) => {
    await page.goto(`${BASE_URL}/en/forgot-password`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'ltr', 'en');
    await checkForMissingTranslations(page);
  });
});

test.describe('i18n: Demo Booking Page', () => {
  test('Demo booking - Arabic RTL with date formatting', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar/demo`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'rtl', 'ar');
    await checkForMissingTranslations(page);

    // Check if calendar/date picker exists
    const datePicker = page.locator('[data-testid="date-picker"], .react-calendar, input[type="date"]').first();
    if (await datePicker.isVisible()) {
      // Verify RTL support in date picker
      const direction = await datePicker.evaluate(el =>
        window.getComputedStyle(el).direction
      );
      expect(direction).toBe('rtl');
    }
  });

  test('Demo booking - English LTR', async ({ page }) => {
    await page.goto(`${BASE_URL}/en/demo`);
    await page.waitForLoadState('networkidle');

    await checkDirection(page, 'ltr', 'en');
    await checkForMissingTranslations(page);
  });
});

test.describe('i18n: Content Pages', () => {
  const contentPages = [
    'pricing',
    'about',
    'contact',
    'resources',
    'blog',
  ];

  for (const pagePath of contentPages) {
    test(`${pagePath} - Arabic`, async ({ page }) => {
      await page.goto(`${BASE_URL}/ar/${pagePath}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'rtl', 'ar');
      await checkForMissingTranslations(page);
    });

    test(`${pagePath} - English`, async ({ page }) => {
      await page.goto(`${BASE_URL}/en/${pagePath}`);
      await page.waitForLoadState('networkidle');

      await checkDirection(page, 'ltr', 'en');
      await checkForMissingTranslations(page);
    });
  }
});

test.describe('i18n: RTL Layout Specifics', () => {
  test('Navigation mirrors correctly in RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    const nav = page.locator('nav').first();
    if (await nav.isVisible()) {
      const direction = await nav.evaluate(el =>
        window.getComputedStyle(el).direction
      );
      expect(direction).toBe('rtl');
    }
  });

  test('Buttons and CTAs positioned correctly in RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    // Get all buttons
    const buttons = await page.locator('button, a.btn, .button').all();

    for (const button of buttons.slice(0, 5)) { // Check first 5 buttons
      if (await button.isVisible()) {
        const direction = await button.evaluate(el =>
          window.getComputedStyle(el).direction
        );
        // Should inherit RTL or be explicitly RTL
        expect(['rtl', 'inherit'].includes(direction)).toBeTruthy();
      }
    }
  });

  test('Forms layout correctly in RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar/signup`);
    await page.waitForLoadState('networkidle');

    const inputs = await page.locator('input[type="text"], input[type="email"], input[type="password"]').all();

    for (const input of inputs.slice(0, 3)) {
      if (await input.isVisible()) {
        const textAlign = await input.evaluate(el =>
          window.getComputedStyle(el).textAlign
        );
        // RTL inputs should align right
        expect(['right', 'start'].includes(textAlign)).toBeTruthy();
      }
    }
  });

  test('No layout overflow in RTL', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    // Check main content container doesn't overflow
    const main = page.locator('main').first();
    if (await main.isVisible()) {
      const box = await main.boundingBox();
      const scrollWidth = await main.evaluate(el => el.scrollWidth);
      const clientWidth = await main.evaluate(el => el.clientWidth);

      // Allow 10px tolerance for scrollbars
      expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 10);
    }
  });
});

test.describe('i18n: Language Preference Persistence', () => {
  test('Language preference remembered across navigation', async ({ page }) => {
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

    // Click language switcher to Arabic
    const langSwitcher = page.locator('[data-testid="lang-switcher"], .lang-switcher, button:has-text("AR"), a:has-text("AR")').first();

    if (await langSwitcher.isVisible()) {
      await langSwitcher.click();
      await page.waitForLoadState('networkidle');

      // Navigate to different page
      await page.goto(`${BASE_URL}/ar/pricing`);
      await page.waitForLoadState('networkidle');

      // Should stay in Arabic
      await checkDirection(page, 'rtl', 'ar');
    }
  });
});

test.describe('i18n: Visual Consistency Check', () => {
  test('Footer has same structure in both languages', async ({ page }) => {
    // English footer
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

    const enFooterLinks = await page.locator('footer a').count();

    // Arabic footer
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    const arFooterLinks = await page.locator('footer a').count();

    // Should have similar number of links (allow ±2 for slight differences)
    expect(Math.abs(enFooterLinks - arFooterLinks)).toBeLessThanOrEqual(2);
  });

  test('Navigation items consistent across languages', async ({ page }) => {
    // English nav
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

    const enNavLinks = await page.locator('nav a, nav button').count();

    // Arabic nav
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

    const arNavLinks = await page.locator('nav a, nav button').count();

    // Should have same structure
    expect(enNavLinks).toBe(arNavLinks);
  });
});

test.describe('i18n: Critical Issues Detection', () => {
  test('No English text leaking into Arabic pages', async ({ page }) => {
    await page.goto(`${BASE_URL}/ar`);
    await page.waitForLoadState('networkidle');

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

    // Check for common English words that shouldn't appear on Arabic pages
    const englishLeaks = [
      'Sign Up',
      'Log In',
      'Contact Us',
      'About Us',
      'Privacy Policy',
    ];

    for (const leak of englishLeaks) {
      if (bodyText?.includes(leak)) {
        console.warn(`⚠️ English text "${leak}" found on Arabic page`);
      }
    }
  });

  test('No Arabic text leaking into English pages', async ({ page }) => {
    await page.goto(`${BASE_URL}/en`);
    await page.waitForLoadState('networkidle');

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

    // Check for Arabic characters
    const hasArabic = /[\u0600-\u06FF]/.test(bodyText || '');

    if (hasArabic) {
      console.warn('⚠️ Arabic characters found on English page (may be intentional for proper nouns)');
    }
  });
});
