/**
 * Comprehensive E2E tests for all careers page features
 * Ensures complete functionality for future deployments
 */

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

test.describe('Careers Page - Complete Feature Suite', () => {
  
  test.describe('Page Load & SEO', () => {
    test('should load page with correct metadata (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');

      // SEO metadata
      await expect(page).toHaveTitle(/Join the Mawidi Team.*Mawidi/i);
      
      // Check meta description
      const metaDescription = page.locator('meta[name="description"]');
      await expect(metaDescription).toHaveAttribute('content', /.+/);
    });

    test('should load page with correct metadata (AR)', async ({ page }) => {
      await page.goto('/ar/careers');
      await page.waitForLoadState('networkidle');

      // Should have title
      await expect(page).toHaveTitle(/Mawidi/);
      
      // Should be in RTL mode
      const main = page.locator('main').first();
      await expect(main).toHaveAttribute('dir', 'rtl');
    });

    test('should have canonical and alternate language links', async ({ page }) => {
      await page.goto('/en/careers');
      
      // Canonical link
      const canonical = page.locator('link[rel="canonical"]');
      await expect(canonical).toHaveAttribute('href', /\/en\/careers$/);
      
      // Alternate language links
      const alternateLangs = page.locator('link[rel="alternate"]');
      const count = await alternateLangs.count();
      expect(count).toBeGreaterThanOrEqual(2); // At least ar and en
    });
  });

  test.describe('Hero Section', () => {
    test('should display hero section with all elements (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      
      const h1 = page.getByRole('heading', { level: 1, name: /join the mawidi team/i });
      await expect(h1).toBeVisible();
      
      const subtitle = page.getByText(/build the future of appointment management/i);
      await expect(subtitle).toBeVisible();
      
      const description = page.getByText(/revolutionizing how businesses manage appointments/i);
      await expect(description).toBeVisible();
      
      const ctaButton = page.getByRole('link', { name: /view open positions/i });
      await expect(ctaButton).toBeVisible();
      await expect(ctaButton).toHaveAttribute('href', '#open-positions');
    });

    test('should display hero section in Arabic (AR)', async ({ page }) => {
      await page.goto('/ar/careers');
      
      const h1 = page.locator('h1').first();
      await expect(h1).toBeVisible();
      await expect(h1).toContainText(/ماويدي/);
    });
  });

  test.describe('Culture Section', () => {
    test('should display all 4 culture values (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /our culture/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /innovation first/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /collaboration/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /continuous growth/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /real impact/i })).toBeVisible();
    });

    test('should display culture values with icons', async ({ page }) => {
      await page.goto('/en/careers');
      
      // Check for emoji icons
      await expect(page.getByText('💡')).toBeVisible();
      await expect(page.getByText('🤝')).toBeVisible();
      await expect(page.getByText('📈')).toBeVisible();
      await expect(page.getByText('🎯')).toBeVisible();
    });
  });

  test.describe('Benefits Section', () => {
    test('should display all 6 benefits (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /why work with us/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /competitive compensation/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /flexible work/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /health & wellness/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /learning budget/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /team events/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /latest technology/i })).toBeVisible();
    });

    test('should display benefits with icons', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByText('💰').first()).toBeVisible();
      await expect(page.getByText('🏠')).toBeVisible();
      await expect(page.getByText('🏥')).toBeVisible();
      await expect(page.getByText('📚')).toBeVisible();
      await expect(page.getByText('🎉')).toBeVisible();
      await expect(page.getByText('💻')).toBeVisible();
    });
  });

  test.describe('Job Listings', () => {
    test('should display job listings section (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      
      const openPositionsHeading = page.getByRole('heading', { name: /open positions/i });
      await expect(openPositionsHeading).toBeVisible();
      
      const subtitle = page.getByText(/current opportunities/i);
      await expect(subtitle).toBeVisible();
    });

    test('should fetch and display jobs from database', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      
      // Wait a moment for jobs to load
      await page.waitForTimeout(1000);
      
      // Check if jobs are displayed (look for job-specific content)
      const jobCards = page.locator('h3').filter({ hasText: /engineer|manager|designer|developer/i });
      const count = await jobCards.count();
      
      // Should have at least 1 job (we inserted 5)
      expect(count).toBeGreaterThan(0);
    });

    test('should display job details correctly', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Look for job-specific elements
      const applyButtons = page.getByRole('button', { name: /apply now/i });
      const buttonCount = await applyButtons.count();
      
      if (buttonCount > 0) {
        // Job listings are present
        await expect(applyButtons.first()).toBeVisible();
        
        // Check for salary information (QAR currency)
        const salaryText = page.getByText(/QAR/i).first();
        await expect(salaryText).toBeVisible();
      }
    });

    test('should display job responsibilities and requirements', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Look for section headings within job cards
      const responsibilitiesHeading = page.getByRole('heading', { name: /responsibilities/i }).first();
      const requirementsHeading = page.getByRole('heading', { name: /requirements/i }).first();
      
      const hasJobs = (await responsibilitiesHeading.count()) > 0;
      
      if (hasJobs) {
        await expect(responsibilitiesHeading).toBeVisible();
        await expect(requirementsHeading).toBeVisible();
      }
    });

    test('should display bilingual jobs (AR)', async ({ page }) => {
      await page.goto('/ar/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Check for Arabic currency format
      const arabicSalary = page.getByText(/ريال قطري/i).first();
      const hasArabicJobs = (await arabicSalary.count()) > 0;
      
      if (hasArabicJobs) {
        await expect(arabicSalary).toBeVisible();
      }
    });
  });

  test.describe('Hiring Process Section', () => {
    test('should display all 5 process steps (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /our hiring process/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /1\. application/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /2\. initial review/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /3\. technical interview/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /4\. team interview/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /5\. offer/i })).toBeVisible();
    });

    test('should display process step badges', async ({ page }) => {
      await page.goto('/en/careers');
      
      // Look for step numbers 1-5
      for (let i = 1; i <= 5; i++) {
        const stepBadge = page.locator('div').filter({ hasText: new RegExp(`^${i}$`) }).first();
        await expect(stepBadge).toBeVisible();
      }
    });
  });

  test.describe('CTA Section', () => {
    test('should display final CTA section (EN)', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /ready to join us/i })).toBeVisible();
      
      const contactLink = page.getByRole('link', { name: /contact us/i }).last();
      await expect(contactLink).toBeVisible();
      await expect(contactLink).toHaveAttribute('href', /\/en\/contact$/);
      
      const emailLink = page.getByRole('link', { name: /careers@mawidi\.app/i });
      await expect(emailLink).toBeVisible();
      await expect(emailLink).toHaveAttribute('href', 'mailto:careers@mawidi.app');
    });
  });

  test.describe('Navigation & Interactions', () => {
    test('should have working language switcher', async ({ page }) => {
      await page.goto('/en/careers');
      
      const arLink = page.getByRole('link', { name: 'AR', exact: true });
      await expect(arLink).toBeVisible();
      
      await arLink.click();
      await page.waitForLoadState('networkidle');
      
      await expect(page).toHaveURL(/\/ar\/careers$/);
    });

    test('should scroll to open positions when clicking hero CTA', async ({ page }) => {
      await page.goto('/en/careers');
      
      const viewPositionsButton = page.getByRole('link', { name: /view open positions/i });
      await viewPositionsButton.click();
      
      // Check URL has hash
      await expect(page).toHaveURL(/#open-positions$/);
    });

    test('should have working navigation menu', async ({ page }) => {
      await page.goto('/en/careers');
      
      await expect(page.getByRole('link', { name: 'Home' })).toBeVisible();
      await expect(page.getByRole('link', { name: 'About' })).toBeVisible();
      await expect(page.getByRole('link', { name: 'Pricing' })).toBeVisible();
      await expect(page.getByRole('link', { name: 'Contact' })).toBeVisible();
    });

    test('should navigate to home page from logo', async ({ page }) => {
      await page.goto('/en/careers');
      
      const logoLink = page.getByRole('link', { name: 'Mawidi' }).first();
      await expect(logoLink).toBeVisible();
      await expect(logoLink).toHaveAttribute('href', '/en');
    });
  });

  test.describe('Error Handling', () => {
    test('should not have PGRST205 errors in console', async ({ page }) => {
      const consoleErrors: string[] = [];
      
      page.on('console', (msg) => {
        if (msg.type() === 'error') {
          consoleErrors.push(msg.text());
        }
      });
      
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      
      // Filter for specific database errors
      const dbErrors = consoleErrors.filter(err => 
        err.includes('PGRST205') || 
        err.includes("Could not find the table 'public.jobs'") ||
        err.includes('Failed to fetch jobs')
      );
      
      expect(dbErrors).toHaveLength(0);
    });

    test('should handle missing jobs gracefully', async ({ page }) => {
      // Even if no jobs exist, page should still load
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      
      // Page should load successfully
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
      
      // Should have either jobs or empty state message
      const hasJobs = await page.getByRole('button', { name: /apply now/i }).count() > 0;
      const hasEmptyState = await page.getByText(/no open positions/i).count() > 0;
      
      expect(hasJobs || hasEmptyState).toBe(true);
    });
  });

  test.describe('Responsive Design', () => {
    test('should be responsive on mobile (EN)', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
      await expect(page.getByRole('heading', { name: /our culture/i })).toBeVisible();
    });

    test('should be responsive on tablet (EN)', async ({ page }) => {
      await page.setViewportSize({ width: 768, height: 1024 });
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
    });

    test('should be responsive on desktop (EN)', async ({ page }) => {
      await page.setViewportSize({ width: 1920, height: 1080 });
      await page.goto('/en/careers');
      
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
    });
  });

  test.describe('Performance', () => {
    test('should load within reasonable time (EN)', async ({ page }) => {
      const startTime = Date.now();
      
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      
      const loadTime = Date.now() - startTime;
      
      // Should load within 10 seconds (generous for dev server)
      expect(loadTime).toBeLessThan(10000);
    });

    test('should not have memory leaks on multiple navigations', async ({ page }) => {
      // Navigate multiple times
      for (let i = 0; i < 3; i++) {
        await page.goto('/en/careers');
        await page.waitForLoadState('networkidle');
        
        await page.goto('/ar/careers');
        await page.waitForLoadState('networkidle');
      }
      
      // Page should still be functional
      await expect(page.getByRole('heading', { level: 1 }).first()).toBeVisible();
    });
  });

  test.describe('Accessibility', () => {
    test('should have proper heading hierarchy', async ({ page }) => {
      await page.goto('/en/careers');
      
      // H1 should exist and be unique
      const h1Count = await page.getByRole('heading', { level: 1 }).count();
      expect(h1Count).toBe(1);
      
      // H2 sections should exist
      const h2Count = await page.getByRole('heading', { level: 2 }).count();
      expect(h2Count).toBeGreaterThan(0);
    });

    test('should have alt text on logo', async ({ page }) => {
      await page.goto('/en/careers');
      
      const logo = page.getByRole('link', { name: 'Mawidi' }).first();
      await expect(logo).toBeVisible();
    });

    test('should have lang attribute', async ({ page }) => {
      await page.goto('/en/careers');
      
      const html = page.locator('html');
      await expect(html).toHaveAttribute('lang', 'en');
    });

    test('should have lang=ar for Arabic version', async ({ page }) => {
      await page.goto('/ar/careers');
      
      const html = page.locator('html');
      await expect(html).toHaveAttribute('lang', 'ar');
    });
  });

  test.describe('Data Integrity', () => {
    test('should display job data from database', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Check for specific job titles we inserted
      const jobTitles = [
        /senior backend engineer/i,
        /product manager/i,
        /frontend developer/i,
        /customer success manager/i,
        /ux.*ui designer/i,
      ];
      
      let jobsFound = 0;
      for (const titlePattern of jobTitles) {
        const count = await page.getByRole('heading', { name: titlePattern }).count();
        if (count > 0) jobsFound++;
      }
      
      // Should find at least 3 out of 5 jobs
      expect(jobsFound).toBeGreaterThanOrEqual(3);
    });

    test('should display correct salary ranges', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Check for QAR currency (Qatari Riyal)
      const qarTexts = page.getByText(/QAR.*\d{2,}/i);
      const count = await qarTexts.count();
      
      // Should have salary information
      expect(count).toBeGreaterThan(0);
    });

    test('should display department labels', async ({ page }) => {
      await page.goto('/en/careers');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      
      // Check for department badges
      const departments = [
        /engineering/i,
        /design/i,
        /product/i,
        /customer success/i,
      ];
      
      let departmentsFound = 0;
      for (const dept of departments) {
        const count = await page.getByText(dept).count();
        if (count > 0) departmentsFound++;
      }
      
      expect(departmentsFound).toBeGreaterThan(0);
    });
  });

  test.describe('Mobile Navigation', () => {
    test('should have mobile menu working', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('/en/careers');
      
      // Navigation should be present (may be hamburger menu)
      const nav = page.locator('nav').first();
      await expect(nav).toBeVisible();
    });
  });

  test.describe('Link Validation', () => {
    test('should have valid internal links', async ({ page }) => {
      await page.goto('/en/careers');
      
      const internalLinks = [
        { name: 'Home', href: '/en' },
        { name: 'About', href: '/en/about' },
        { name: 'Pricing', href: '/en/pricing' },
        { name: 'Contact', href: '/en/contact' },
      ];
      
      for (const link of internalLinks) {
        const element = page.getByRole('link', { name: link.name });
        await expect(element).toHaveAttribute('href', new RegExp(link.href));
      }
    });

    test('should have valid email links', async ({ page }) => {
      await page.goto('/en/careers');
      
      const emailLink = page.getByRole('link', { name: /careers@mawidi\.app/i });
      await expect(emailLink).toHaveAttribute('href', 'mailto:careers@mawidi.app');
    });
  });

  test.describe('Cross-browser Compatibility', () => {
    test('should work in Chromium', async ({ page, browserName }) => {
      test.skip(browserName !== 'chromium');
      
      await page.goto('/en/careers');
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
    });

    test('should work in Firefox', async ({ page, browserName }) => {
      test.skip(browserName !== 'firefox');
      
      await page.goto('/en/careers');
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
    });

    test('should work in WebKit', async ({ page, browserName }) => {
      test.skip(browserName !== 'webkit');
      
      await page.goto('/en/careers');
      await expect(page.getByRole('heading', { name: /join the mawidi team/i })).toBeVisible();
    });
  });
});
