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

test.describe('Careers Page - Job Listings', () => {
  test.describe('Page Load and Structure - English', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');
    });

    test('should load careers page successfully', async ({ page }) => {
      await expect(page).toHaveTitle(/Join the Mawidi Team/i);
      await expect(page.locator('h1')).toContainText('Join the Mawidi Team');
    });

    test('should display hero section with correct content', async ({ page }) => {
      const heroSection = page.locator('section').first();

      await expect(heroSection.locator('h1')).toContainText('Join the Mawidi Team');
      await expect(heroSection.locator('p').first()).toContainText('Build the future');
      await expect(heroSection.locator('a[href="#open-positions"]')).toBeVisible();
    });

    test('should display culture section with 4 values', async ({ page }) => {
      const cultureSection = page.locator('section').nth(1);

      await expect(cultureSection.locator('h2')).toContainText('Our Culture');

      const cultureCards = cultureSection.locator('div.group').filter({ hasText: /Innovation|Collaboration|Growth|Impact/ });
      await expect(cultureCards).toHaveCount(4);

      // Check each culture value has icon, title, and description
      for (let i = 0; i < 4; i++) {
        const card = cultureCards.nth(i);
        await expect(card.locator('div.text-5xl')).toBeVisible(); // Icon
        await expect(card.locator('h3')).toBeVisible(); // Title
        await expect(card.locator('p')).toBeVisible(); // Description
      }
    });

    test('should display benefits section with 6 benefits', async ({ page }) => {
      const benefitsSection = page.locator('section').nth(2);

      await expect(benefitsSection.locator('h2')).toContainText('Why Work With Us');

      const benefitCards = benefitsSection.locator('div.group');
      await expect(benefitCards).toHaveCount(6);

      // Verify benefits structure
      for (let i = 0; i < 6; i++) {
        const card = benefitCards.nth(i);
        await expect(card.locator('div.text-4xl')).toBeVisible(); // Icon
        await expect(card.locator('h3')).toBeVisible(); // Title
        await expect(card.locator('p')).toBeVisible(); // Description
      }
    });

    test('should display hiring process with 5 steps', async ({ page }) => {
      const processSection = page.locator('section').nth(4);

      await expect(processSection.locator('h2')).toContainText('Our Hiring Process');

      const processSteps = processSection.locator('div[class*="relative flex items-center"]');
      await expect(processSteps).toHaveCount(5);

      // Verify each step has number badge and content
      for (let i = 0; i < 5; i++) {
        const step = processSteps.nth(i);
        await expect(step.locator('div[class*="rounded-full"]')).toContainText(`${i + 1}`);
        await expect(step.locator('h3')).toBeVisible();
        await expect(step.locator('p')).toBeVisible();
      }
    });

    test('should display final CTA section', async ({ page }) => {
      const ctaSection = page.locator('section').last();

      await expect(ctaSection.locator('h2')).toContainText('Ready to Join Us?');
      await expect(ctaSection.locator('a[href="/en/contact"]')).toBeVisible();
      await expect(ctaSection.locator('a[href^="mailto:careers@"]')).toBeVisible();
    });

    test('should have accessible navigation to open positions', async ({ page }) => {
      const ctaButton = page.locator('a[href="#open-positions"]');
      await ctaButton.click();

      // Should scroll to open positions section
      const openPositionsSection = page.locator('#open-positions');
      await expect(openPositionsSection).toBeInViewport();
    });
  });

  test.describe('Page Load and Structure - Arabic', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/ar/careers');
    });

    test('should load Arabic careers page with RTL direction', async ({ page }) => {
      const mainElement = page.locator('main');
      await expect(mainElement).toHaveAttribute('dir', 'rtl');
    });

    test('should display Arabic content in hero section', async ({ page }) => {
      const heroSection = page.locator('section').first();

      // Check for Arabic characters in the heading
      const heading = await heroSection.locator('h1').textContent();
      expect(heading).toMatch(/[\u0600-\u06FF]/); // Arabic Unicode range
    });

    test('should display culture section with Arabic text', async ({ page }) => {
      const cultureSection = page.locator('section').nth(1);

      const cultureCards = cultureSection.locator('div.group');
      await expect(cultureCards).toHaveCount(4);

      // Verify Arabic content
      const firstCardText = await cultureCards.first().locator('p').textContent();
      expect(firstCardText).toMatch(/[\u0600-\u06FF]/);
    });

    test('should have correct CTA links for Arabic', async ({ page }) => {
      const ctaSection = page.locator('section').last();

      await expect(ctaSection.locator('a[href="/ar/contact"]')).toBeVisible();
      await expect(ctaSection.locator('a[href^="mailto:careers@"]')).toBeVisible();
    });
  });

  test.describe('Job Listings Display', () => {
    test('should display empty state when no jobs available', async ({ page }) => {
      // Navigate to careers page
      await page.goto('/en/careers');

      const openPositionsSection = page.locator('#open-positions');
      await openPositionsSection.scrollIntoViewIfNeeded();

      // Check for either job listings or empty state
      const jobCards = page.locator('div.group').filter({ hasText: /Apply Now|View Details/ });
      const emptyState = page.locator('text="No open positions at the moment"');

      // Either should have jobs OR empty state
      const hasJobs = await jobCards.count() > 0;
      const hasEmptyState = await emptyState.isVisible();

      expect(hasJobs || hasEmptyState).toBeTruthy();
    });

    test('should display job cards with all required information', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /Apply Now/ }).first();

      // Skip test if no jobs available
      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      // Verify job card structure
      await expect(jobCard.locator('h3').first()).toBeVisible(); // Job title
      await expect(jobCard.locator('button:has-text("Apply Now")')).toBeVisible(); // Apply button

      // Verify badges (department, location, contract type, level)
      const badges = jobCard.locator('span[class*="rounded-full"]');
      await expect(badges).toHaveCount(4);

      // Verify salary information
      await expect(jobCard.locator('div.text-brand-green').first()).toBeVisible();
    });

    test('should display job details sections', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /Apply Now/ }).first();

      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      // Check for common detail sections (at least one should be present)
      const responsibilitiesSection = jobCard.locator('h4:has-text("Responsibilities")');
      const requirementsSection = jobCard.locator('h4:has-text("Requirements")');
      const skillsSection = jobCard.locator('h4:has-text("Skills")');

      const hasSomeDetails =
        await responsibilitiesSection.count() > 0 ||
        await requirementsSection.count() > 0 ||
        await skillsSection.count() > 0;

      expect(hasSomeDetails).toBeTruthy();
    });

    test('should display posted date in correct format', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /Apply Now/ }).first();

      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      const postedText = jobCard.locator('p:has-text("Posted:")');
      await expect(postedText).toBeVisible();

      // Verify date format (e.g., "January 15, 2025")
      const text = await postedText.textContent();
      expect(text).toMatch(/Posted:\s*\w+\s+\d{1,2},\s+\d{4}/);
    });
  });

  test.describe('Job Listings - Arabic', () => {
    test('should display Arabic job listings with RTL layout', async ({ page }) => {
      await page.goto('/ar/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /تقديم الآن|قدم الآن/ }).first();

      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      // Verify Arabic content
      const jobTitle = await jobCard.locator('h3').first().textContent();
      expect(jobTitle).toMatch(/[\u0600-\u06FF]/); // Arabic Unicode

      // Verify Apply button in Arabic
      await expect(jobCard.locator('button').first()).toBeVisible();
    });

    test('should display posted date in Arabic format', async ({ page }) => {
      await page.goto('/ar/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /تقديم|قدم/ }).first();

      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      const postedText = jobCard.locator('p').last();
      const text = await postedText.textContent();

      // Should contain Arabic month name or Arabic text
      expect(text).toMatch(/[\u0600-\u06FF]/);
    });
  });

  test.describe('Responsive Design', () => {
    test('should display correctly on mobile viewport', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('/en/careers');

      // Hero section should be visible and readable
      await expect(page.locator('h1')).toBeVisible();

      // CTA button should be visible
      await expect(page.locator('a[href="#open-positions"]')).toBeVisible();

      // Culture cards should stack vertically
      const cultureSection = page.locator('section').nth(1);
      const cultureCards = cultureSection.locator('div.group');

      if (await cultureCards.count() > 0) {
        const firstCard = cultureCards.first();
        const secondCard = cultureCards.nth(1);

        const firstBox = await firstCard.boundingBox();
        const secondBox = await secondCard.boundingBox();

        if (firstBox && secondBox) {
          // Cards should be vertically stacked (second card Y > first card Y + height)
          expect(secondBox.y).toBeGreaterThan(firstBox.y + firstBox.height - 20);
        }
      }
    });

    test('should display correctly on tablet viewport', async ({ page }) => {
      await page.setViewportSize({ width: 768, height: 1024 });
      await page.goto('/en/careers');

      await expect(page.locator('h1')).toBeVisible();

      // Benefits section should show 2 columns on tablet
      const benefitsSection = page.locator('section').nth(2);
      const benefitCards = benefitsSection.locator('div.group');

      if (await benefitCards.count() >= 2) {
        const firstBox = await benefitCards.first().boundingBox();
        const secondBox = await benefitCards.nth(1).boundingBox();

        // On tablet, should have some horizontal layout
        if (firstBox && secondBox) {
          expect(Math.abs(firstBox.y - secondBox.y)).toBeLessThan(100);
        }
      }
    });

    test('should display correctly on desktop viewport', async ({ page }) => {
      await page.setViewportSize({ width: 1440, height: 900 });
      await page.goto('/en/careers');

      await expect(page.locator('h1')).toBeVisible();

      // Process steps should have alternating layout
      const processSection = page.locator('section').nth(4);
      await expect(processSection.locator('h2')).toContainText('Our Hiring Process');

      // Center line should be visible on desktop
      const centerLine = processSection.locator('div[class*="absolute"][class*="w-1"]');
      await expect(centerLine).toBeVisible();
    });
  });

  test.describe('SEO and Metadata', () => {
    test('should have correct canonical URLs for English', async ({ page }) => {
      await page.goto('/en/careers');

      const canonical = page.locator('link[rel="canonical"]');
      await expect(canonical).toHaveAttribute('href', /\/en\/careers$/);
    });

    test('should have correct canonical URLs for Arabic', async ({ page }) => {
      await page.goto('/ar/careers');

      const canonical = page.locator('link[rel="canonical"]');
      await expect(canonical).toHaveAttribute('href', /\/ar\/careers$/);
    });

    test('should have language alternates', async ({ page }) => {
      await page.goto('/en/careers');

      const enAlternate = page.locator('link[rel="alternate"][hreflang="en"]');
      const arAlternate = page.locator('link[rel="alternate"][hreflang="ar"]');

      await expect(enAlternate).toHaveAttribute('href', /\/en\/careers/);
      await expect(arAlternate).toHaveAttribute('href', /\/ar\/careers/);
    });

    test('should have meta description', async ({ page }) => {
      await page.goto('/en/careers');

      const metaDescription = page.locator('meta[name="description"]');
      await expect(metaDescription).toHaveAttribute('content', /.+/);
    });
  });

  test.describe('Accessibility', () => {
    test('should have proper heading hierarchy', async ({ page }) => {
      await page.goto('/en/careers');

      // Should have one h1
      const h1Count = await page.locator('h1').count();
      expect(h1Count).toBe(1);

      // Should have multiple h2s for sections
      const h2Count = await page.locator('h2').count();
      expect(h2Count).toBeGreaterThan(3);
    });

    test('should have accessible links and buttons', async ({ page }) => {
      await page.goto('/en/careers');

      // All links should have text or aria-label
      const links = await page.locator('a').all();
      for (const link of links) {
        const text = await link.textContent();
        const ariaLabel = await link.getAttribute('aria-label');
        expect(text?.trim() || ariaLabel).toBeTruthy();
      }
    });

    test('should have proper focus states', async ({ page }) => {
      await page.goto('/en/careers');

      // Test keyboard navigation
      await page.keyboard.press('Tab');
      const focusedElement = await page.evaluate(() => document.activeElement?.tagName);
      expect(focusedElement).toBeTruthy();
    });
  });

  test.describe('Performance', () => {
    test('should load within acceptable time', async ({ page }) => {
      const startTime = Date.now();
      await page.goto('/en/careers');
      const loadTime = Date.now() - startTime;

      // Page should load within 3 seconds
      expect(loadTime).toBeLessThan(3000);
    });

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

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

      await page.goto('/en/careers');

      // Allow for expected errors but filter out critical ones
      const criticalErrors = consoleErrors.filter(
        err => !err.includes('favicon') && !err.includes('404')
      );

      expect(criticalErrors).toHaveLength(0);
    });
  });

  test.describe('Interactive Elements', () => {
    test('should scroll smoothly to open positions section', async ({ page }) => {
      await page.goto('/en/careers');

      const viewPositionsButton = page.locator('a[href="#open-positions"]');
      await viewPositionsButton.click();

      // Wait for scroll animation
      await page.waitForTimeout(500);

      const openPositionsSection = page.locator('#open-positions');
      await expect(openPositionsSection).toBeInViewport();
    });

    test('should have working email link in CTA', async ({ page }) => {
      await page.goto('/en/careers');

      const emailLink = page.locator('a[href^="mailto:careers@"]');
      await expect(emailLink).toHaveAttribute('href', 'mailto:careers@mawidi.app');
    });

    test('should have working contact link', async ({ page }) => {
      await page.goto('/en/careers');

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

      // Click should navigate to contact page
      await contactLink.click();
      await expect(page).toHaveURL(/\/en\/contact/);
    });
  });

  test.describe('Job Card Interactions', () => {
    test('should display apply button for each job', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCards = page.locator('div.group').filter({ hasText: /Apply Now/ });
      const count = await jobCards.count();

      if (count === 0) {
        test.skip();
        return;
      }

      // Each job should have an Apply Now button
      for (let i = 0; i < count; i++) {
        const applyButton = jobCards.nth(i).locator('button:has-text("Apply Now")');
        await expect(applyButton).toBeVisible();
        await expect(applyButton).toBeEnabled();
      }
    });

    test('should have hover effects on job cards', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCard = page.locator('div.group').filter({ hasText: /Apply Now/ }).first();

      if (await jobCard.count() === 0) {
        test.skip();
        return;
      }

      // Get initial position
      const initialBox = await jobCard.boundingBox();

      // Hover over card
      await jobCard.hover();

      // Card should have transform effect (hover:-translate-y-1)
      // Note: This is a visual test, we just verify the card is still visible
      await expect(jobCard).toBeVisible();
      expect(initialBox).toBeTruthy();
    });

    test('should sort jobs by opening date (newest first)', async ({ page }) => {
      await page.goto('/en/careers');

      const jobCards = page.locator('div.group').filter({ hasText: /Apply Now/ });
      const count = await jobCards.count();

      if (count < 2) {
        test.skip();
        return;
      }

      // Extract posted dates from first two jobs
      const dates: Date[] = [];
      for (let i = 0; i < Math.min(2, count); i++) {
        const postedText = await jobCards.nth(i).locator('p:has-text("Posted:")').textContent();
        if (postedText) {
          const dateMatch = postedText.match(/Posted:\s*(.+)/);
          if (dateMatch) {
            dates.push(new Date(dateMatch[1]));
          }
        }
      }

      if (dates.length === 2) {
        // First job should be newer or equal to second job
        expect(dates[0].getTime()).toBeGreaterThanOrEqual(dates[1].getTime());
      }
    });
  });

  test.describe('Bilingual Content Consistency', () => {
    test('should have matching job count across languages', async ({ page }) => {
      // Get English job count
      await page.goto('/en/careers');
      const enJobCards = page.locator('div.group').filter({ hasText: /Apply Now/ });
      const enCount = await enJobCards.count();

      // Get Arabic job count
      await page.goto('/ar/careers');
      const arJobCards = page.locator('div.group').filter({ hasText: /تقديم|قدم/ });
      const arCount = await arJobCards.count();

      // Should have same number of jobs
      expect(enCount).toBe(arCount);
    });

    test('should have consistent empty state across languages', async ({ page }) => {
      // Check English
      await page.goto('/en/careers');
      const enEmpty = await page.locator('text=/No open positions/i').count();

      // Check Arabic
      await page.goto('/ar/careers');
      const arEmpty = await page.locator('text=/لا توجد وظائف|لا يوجد/').count();

      // Both should either show empty state or have jobs
      if (enEmpty > 0) {
        expect(arEmpty).toBeGreaterThan(0);
      } else {
        expect(arEmpty).toBe(0);
      }
    });
  });
});
