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

test.describe('Careers Application Form', () => {
  // Create a test PDF file for upload testing
  const testPdfPath = path.join(__dirname, '..', 'fixtures', 'test-resume.pdf');

  test.beforeAll(async () => {
    // Create fixtures directory if it doesn't exist
    const fixturesDir = path.join(__dirname, '..', 'fixtures');
    if (!fs.existsSync(fixturesDir)) {
      fs.mkdirSync(fixturesDir, { recursive: true });
    }

    // Create a minimal valid PDF file for testing if it doesn't exist
    if (!fs.existsSync(testPdfPath)) {
      // Minimal PDF content (valid PDF structure)
      const pdfContent = Buffer.from([
        '%PDF-1.4\n',
        '1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n',
        '2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n',
        '3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n',
        '4 0 obj\n<< /Length 44 >>\nstream\nBT\n/F1 12 Tf\n100 700 Td\n(Test Resume) Tj\nET\nendstream\nendobj\n',
        'xref\n0 5\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\n0000000115 00000 n\n0000000317 00000 n\ntrailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n408\n%%EOF\n'
      ].join(''));

      fs.writeFileSync(testPdfPath, pdfContent);
    }
  });

  test.describe('Application Modal - English', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');
    });

    test('should open application modal when Apply Now is clicked', async ({ page }) => {
      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      // Modal should be visible
      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).toBeVisible();

      // Modal should have form title
      await expect(modal.locator('h2:has-text("Apply for")')).toBeVisible();
    });

    test('should close modal when X button is clicked', async ({ page }) => {
      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).toBeVisible();

      // Click close button
      const closeButton = modal.locator('button[aria-label="Close"]');
      await closeButton.click();

      // Modal should be hidden
      await expect(modal).not.toBeVisible();
    });

    test('should close modal when clicking outside', async ({ page }) => {
      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).toBeVisible();

      // Click outside modal (on backdrop)
      await page.locator('div[class*="fixed inset-0 z-50"]').click({ position: { x: 10, y: 10 } });

      // Modal should be hidden
      await expect(modal).not.toBeVisible();
    });

    test('should not close modal when clicking inside form', async ({ page }) => {
      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).toBeVisible();

      // Click inside the form
      const formContainer = modal.locator('div.bg-white, div.dark\\:bg-slate-900').first();
      await formContainer.click();

      // Modal should still be visible
      await expect(modal).toBeVisible();
    });
  });

  test.describe('Form Validation', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should show required field indicators', async ({ page }) => {
      const requiredMarkers = page.locator('span.text-red-500:has-text("*")');
      const count = await requiredMarkers.count();

      // Should have at least 4 required fields (name, email, phone, resume)
      expect(count).toBeGreaterThanOrEqual(4);
    });

    test('should not submit form when required fields are empty', async ({ page }) => {
      const submitButton = page.locator('button[type="submit"]:has-text("Submit Application")');

      // Try to submit empty form
      await submitButton.click();

      // Form should still be visible (HTML5 validation prevents submission)
      await expect(page.locator('form')).toBeVisible();
    });

    test('should validate email format', async ({ page }) => {
      // Fill name and phone
      await page.fill('input[type="text"]', 'Test User');
      await page.fill('input[type="tel"]', '+966501234567');

      // Fill invalid email
      await page.fill('input[type="email"]', 'invalid-email');

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

      // Browser validation should prevent submission
      const emailInput = page.locator('input[type="email"]');
      const validationMessage = await emailInput.evaluate((el: HTMLInputElement) => el.validationMessage);
      expect(validationMessage).toBeTruthy();
    });

    test('should validate file type (PDF only)', async ({ page }) => {
      // Create a test .txt file
      const txtFilePath = path.join(__dirname, '..', 'fixtures', 'test-file.txt');
      fs.writeFileSync(txtFilePath, 'This is not a PDF');

      // Try to upload non-PDF file
      const fileInput = page.locator('input[type="file"]');
      await fileInput.setInputFiles(txtFilePath);

      // Should show alert or error
      page.on('dialog', async (dialog) => {
        expect(dialog.message()).toContain('PDF');
        await dialog.accept();
      });

      // Clean up
      fs.unlinkSync(txtFilePath);
    });

    test('should validate file size (max 10MB)', async ({ page }) => {
      // This test would require creating a large file
      // For now, we verify the validation text is present
      const helpText = page.locator('text=/max 10MB/i');
      await expect(helpText).toBeVisible();
    });

    test('should disable submit button when resume is not uploaded', async ({ page }) => {
      // Fill all required text fields
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');

      const submitButton = page.locator('button[type="submit"]:has-text("Submit Application")');

      // Submit button should be disabled without resume
      await expect(submitButton).toBeDisabled();
    });
  });

  test.describe('Form Submission Flow', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should fill and submit complete application', async ({ page }) => {
      // Fill all required fields
      await page.fill('input[placeholder*="full name"]', 'Ahmed Al-Mansouri');
      await page.fill('input[type="email"]', 'ahmed.mansouri@example.com');
      await page.fill('input[type="tel"]', '+966501234567');

      // Fill optional fields
      await page.fill('textarea[placeholder*="Cover Letter"]', 'I am very interested in this position...');

      // Upload resume
      const fileInput = page.locator('input[type="file"]');
      await fileInput.setInputFiles(testPdfPath);

      // Wait for file to be selected
      await page.waitForTimeout(500);

      const submitButton = page.locator('button[type="submit"]:has-text("Submit Application")');

      // Submit button should be enabled now
      await expect(submitButton).toBeEnabled();

      // Intercept API call
      const responsePromise = page.waitForResponse(
        response => response.url().includes('/api/apply-job') && response.request().method() === 'POST'
      );

      await submitButton.click();

      // Wait for API response
      const response = await responsePromise;

      // Should get success response (200) or see success state
      if (response.status() === 200) {
        // Should show success message
        await expect(page.locator('text=/Application Submitted|Thank you/i')).toBeVisible({ timeout: 5000 });
      }
    });

    test('should show loading state during submission', async ({ page }) => {
      // Fill required fields
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

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

      // Click submit
      await submitButton.click();

      // Should show loading state (spinner or "Submitting...")
      const loadingState = page.locator('text=/Submitting/i, span.animate-spin');

      // Check if loading state appears (might be quick)
      try {
        await expect(loadingState.first()).toBeVisible({ timeout: 1000 });
      } catch {
        // Loading state might be too quick, that's ok
      }
    });

    test('should handle submission error gracefully', async ({ page }) => {
      // Mock a failed API response
      await page.route('/api/apply-job', (route) => {
        route.fulfill({
          status: 500,
          contentType: 'application/json',
          body: JSON.stringify({ error: 'Server error' }),
        });
      });

      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

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

      // Should show error message
      await expect(page.locator('text=/Submission Failed|Something went wrong/i')).toBeVisible({ timeout: 5000 });
    });

    test('should auto-close modal after successful submission', async ({ page }) => {
      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Mock successful API response
      await page.route('/api/apply-job', (route) => {
        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({
            success: true,
            message: 'Application received successfully',
            applicationId: 'test-id-123',
          }),
        });
      });

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

      // Should show success message
      await expect(page.locator('text=/Application Submitted/i')).toBeVisible({ timeout: 2000 });

      // Modal should auto-close after 3 seconds
      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).not.toBeVisible({ timeout: 4000 });
    });

    test('should clear form data after modal closes', async ({ page }) => {
      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');

      // Close modal
      const closeButton = page.locator('button[aria-label="Close"]');
      await closeButton.click();

      // Re-open modal
      const applyButton = page.locator('button:has-text("Apply Now")').first();
      await applyButton.click();

      // Fields should be empty
      const nameInput = page.locator('input[placeholder*="full name"]');
      await expect(nameInput).toHaveValue('');

      const emailInput = page.locator('input[type="email"]');
      await expect(emailInput).toHaveValue('');
    });
  });

  test.describe('Application Modal - Arabic', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/ar/careers');

      const applyButton = page.locator('button').filter({ hasText: /تقديم|قدم/ }).first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
    });

    test('should display Arabic form with RTL direction', async ({ page }) => {
      const modalContent = page.locator('div[class*="fixed inset-0"] > div').first();
      await expect(modalContent).toHaveAttribute('dir', 'rtl');
    });

    test('should have Arabic labels and placeholders', async ({ page }) => {
      const form = page.locator('form');

      // Check for Arabic text in labels
      const labels = await form.locator('label').allTextContents();
      const hasArabicText = labels.some(label => /[\u0600-\u06FF]/.test(label));
      expect(hasArabicText).toBeTruthy();
    });

    test('should submit application with Arabic content', async ({ page }) => {
      // Fill form with Arabic content
      await page.fill('input[type="text"]', 'أحمد المنصوري');
      await page.fill('input[type="email"]', 'ahmed@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Mock successful response
      await page.route('/api/apply-job', (route) => {
        const request = route.request();
        const postData = request.postData();

        // Verify Arabic name is in the request
        expect(postData).toContain('أحمد المنصوري');
        expect(postData).toContain('lang=ar');

        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ success: true }),
        });
      });

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

      // Should show success in Arabic
      await expect(page.locator('text=/تم إرسال|نجح/i')).toBeVisible({ timeout: 3000 });
    });
  });

  test.describe('File Upload Functionality', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should accept valid PDF file', async ({ page }) => {
      const fileInput = page.locator('input[type="file"]');
      await fileInput.setInputFiles(testPdfPath);

      // Verify file is selected
      const fileName = await fileInput.evaluate((el: HTMLInputElement) => {
        return el.files?.[0]?.name || '';
      });

      expect(fileName).toBe('test-resume.pdf');

      // Submit button should be enabled after filling other fields
      await page.fill('input[type="text"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');

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

    test('should show file size limit in help text', async ({ page }) => {
      const helpText = page.locator('p.text-xs:has-text("10MB")');
      await expect(helpText).toBeVisible();
    });

    test('should only accept PDF files', async ({ page }) => {
      const fileInput = page.locator('input[type="file"]');
      const acceptAttr = await fileInput.getAttribute('accept');

      expect(acceptAttr).toBe('.pdf');
    });
  });

  test.describe('Form Fields', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should have all required form fields', async ({ page }) => {
      // Check required fields
      await expect(page.locator('input[placeholder*="full name"]')).toBeVisible();
      await expect(page.locator('input[type="email"]')).toBeVisible();
      await expect(page.locator('input[type="tel"]')).toBeVisible();
      await expect(page.locator('input[type="file"]')).toBeVisible();
    });

    test('should have optional fields', async ({ page }) => {
      // Cover letter should be optional (no asterisk required)
      const coverLetterLabel = page.locator('label:has-text("Cover Letter")');
      await expect(coverLetterLabel).toBeVisible();

      const coverLetterRequired = await coverLetterLabel.locator('span.text-red-500:has-text("*")').count();
      expect(coverLetterRequired).toBe(0);
    });

    test('should accept text input for all text fields', async ({ page }) => {
      await page.fill('input[placeholder*="full name"]', 'Ahmed Al-Mansouri');
      await expect(page.locator('input[placeholder*="full name"]')).toHaveValue('Ahmed Al-Mansouri');

      await page.fill('input[type="email"]', 'ahmed@example.com');
      await expect(page.locator('input[type="email"]')).toHaveValue('ahmed@example.com');

      await page.fill('input[type="tel"]', '+966501234567');
      await expect(page.locator('input[type="tel"]')).toHaveValue('+966501234567');

      await page.fill('textarea', 'This is my cover letter');
      await expect(page.locator('textarea')).toHaveValue('This is my cover letter');
    });

    test('should maintain form state when switching between fields', async ({ page }) => {
      // Fill fields
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');

      // Click on different field
      await page.locator('textarea').click();

      // Previous fields should maintain their values
      await expect(page.locator('input[placeholder*="full name"]')).toHaveValue('Test User');
      await expect(page.locator('input[type="email"]')).toHaveValue('test@example.com');
    });
  });

  test.describe('Form Actions', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should have Cancel button that closes modal', async ({ page }) => {
      const cancelButton = page.locator('button:has-text("Cancel")');
      await expect(cancelButton).toBeVisible();

      await cancelButton.click();

      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).not.toBeVisible();
    });

    test('should disable form actions during submission', async ({ page }) => {
      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Delay the API response
      await page.route('/api/apply-job', async (route) => {
        await new Promise(resolve => setTimeout(resolve, 2000));
        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ success: true }),
        });
      });

      const submitButton = page.locator('button[type="submit"]');
      const cancelButton = page.locator('button:has-text("Cancel")');

      await submitButton.click();

      // During submission, cancel should be disabled
      await expect(cancelButton).toBeDisabled({ timeout: 500 });
    });
  });

  test.describe('Success and Error States', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should display success state with checkmark', async ({ page }) => {
      // Fill and submit
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      await page.route('/api/apply-job', (route) => {
        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ success: true }),
        });
      });

      await page.locator('button[type="submit"]').click();

      // Should show success icon
      await expect(page.locator('div:has-text("✅")')).toBeVisible({ timeout: 3000 });

      // Should show success title
      await expect(page.locator('h3:has-text("Application Submitted")')).toBeVisible();

      // Should show success message
      await expect(page.locator('text=/Thank you for your interest/i')).toBeVisible();
    });

    test('should display error state with error icon', async ({ page }) => {
      // Fill and submit
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      await page.route('/api/apply-job', (route) => {
        route.fulfill({
          status: 500,
          contentType: 'application/json',
          body: JSON.stringify({ error: 'Server error' }),
        });
      });

      await page.locator('button[type="submit"]').click();

      // Should show error icon
      await expect(page.locator('div:has-text("❌")')).toBeVisible({ timeout: 3000 });

      // Should show error title
      await expect(page.locator('h3:has-text("Submission Failed")')).toBeVisible();

      // Should show retry button
      await expect(page.locator('button:has-text("Try Again")')).toBeVisible();
    });

    test('should allow retry after error', async ({ page }) => {
      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Mock error
      await page.route('/api/apply-job', (route) => {
        route.fulfill({ status: 500, body: JSON.stringify({ error: 'Error' }) });
      });

      await page.locator('button[type="submit"]').click();

      // Wait for error state
      await expect(page.locator('h3:has-text("Submission Failed")')).toBeVisible({ timeout: 3000 });

      // Click Try Again
      const retryButton = page.locator('button:has-text("Try Again")');
      await retryButton.click();

      // Should return to form
      await expect(page.locator('form')).toBeVisible();
      await expect(page.locator('button[type="submit"]')).toBeVisible();
    });
  });

  test.describe('Mobile Application Flow', () => {
    test.beforeEach(async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
    });

    test('should open modal on mobile', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const modal = page.locator('div[class*="fixed inset-0 z-50"]');
      await expect(modal).toBeVisible();
    });

    test('should have scrollable form content on mobile', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const modalContent = page.locator('div[class*="max-h-\\[90vh\\]"]');
      await expect(modalContent).toHaveCSS('overflow-y', 'auto');
    });

    test('should stack form buttons vertically on mobile', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const buttonsContainer = page.locator('div.flex.flex-col-reverse');
      await expect(buttonsContainer).toBeVisible();

      const cancelButton = buttonsContainer.locator('button:has-text("Cancel")');
      const submitButton = buttonsContainer.locator('button[type="submit"]');

      const cancelBox = await cancelButton.boundingBox();
      const submitBox = await submitButton.boundingBox();

      // Buttons should be stacked (different Y positions)
      if (cancelBox && submitBox) {
        expect(Math.abs(cancelBox.y - submitBox.y)).toBeGreaterThan(20);
      }
    });
  });

  test.describe('Form Field Interactions', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should show focus states on inputs', async ({ page }) => {
      const nameInput = page.locator('input[placeholder*="full name"]');

      await nameInput.focus();

      // Should have focus ring (ring-2 ring-brand-green)
      await expect(nameInput).toBeFocused();
    });

    test('should allow multiline cover letter input', async ({ page }) => {
      const coverLetter = page.locator('textarea');

      const multilineText = 'Line 1\nLine 2\nLine 3';
      await coverLetter.fill(multilineText);

      await expect(coverLetter).toHaveValue(multilineText);
    });

    test('should handle special characters in name', async ({ page }) => {
      const nameInput = page.locator('input[placeholder*="full name"]');

      const specialName = "O'Connor-Smith III";
      await nameInput.fill(specialName);

      await expect(nameInput).toHaveValue(specialName);
    });

    test('should handle international phone formats', async ({ page }) => {
      const phoneInput = page.locator('input[type="tel"]');

      const phoneFormats = [
        '+966501234567',
        '+971-50-123-4567',
        '+974 5012 3456',
      ];

      for (const format of phoneFormats) {
        await phoneInput.fill(format);
        await expect(phoneInput).toHaveValue(format);
      }
    });
  });

  test.describe('Accessibility - Application Form', () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();
      if (await applyButton.count() === 0) {
        test.skip();
        return;
      }

      await applyButton.click();
      await page.waitForSelector('form');
    });

    test('should have labels for all form fields', async ({ page }) => {
      const inputs = await page.locator('input[type="text"], input[type="email"], input[type="tel"], textarea').all();

      for (const input of inputs) {
        const id = await input.getAttribute('id');
        const name = await input.getAttribute('name');
        const placeholder = await input.getAttribute('placeholder');

        // Should have at least placeholder or associated label
        expect(placeholder || id || name).toBeTruthy();
      }
    });

    test('should support keyboard navigation', async ({ page }) => {
      // Tab through form fields
      await page.keyboard.press('Tab'); // Name field
      await expect(page.locator('input[placeholder*="full name"]')).toBeFocused();

      await page.keyboard.press('Tab'); // Email field
      await expect(page.locator('input[type="email"]')).toBeFocused();

      await page.keyboard.press('Tab'); // Phone field
      await expect(page.locator('input[type="tel"]')).toBeFocused();
    });

    test('should have accessible close button', async ({ page }) => {
      const closeButton = page.locator('button[aria-label="Close"]');
      await expect(closeButton).toHaveAttribute('aria-label', 'Close');
    });
  });

  test.describe('Job Context in Application', () => {
    test('should display selected job title in modal header', async ({ page }) => {
      await page.goto('/en/careers');

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

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

      // Get job title
      const jobTitle = await firstJobCard.locator('h3').first().textContent();

      // Click Apply Now
      await firstJobCard.locator('button:has-text("Apply Now")').click();

      // Modal should show the job title
      const modalJobTitle = page.locator('p.text-brand-green');
      await expect(modalJobTitle).toContainText(jobTitle || '');
    });

    test('should send correct job ID in application', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();
      await page.waitForSelector('form');

      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Intercept API call to verify job ID
      let jobIdSent = '';
      await page.route('/api/apply-job', (route) => {
        const postData = route.request().postData();
        if (postData) {
          const match = postData.match(/name="jobId"[\r\n]+([^\r\n]+)/);
          if (match) {
            jobIdSent = match[1];
          }
        }

        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ success: true }),
        });
      });

      await page.locator('button[type="submit"]').click();

      // Wait a bit for the request
      await page.waitForTimeout(1000);

      // Job ID should be a UUID format
      expect(jobIdSent).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
    });
  });

  test.describe('Edge Cases', () => {
    test('should handle extremely long text inputs gracefully', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      const longText = 'A'.repeat(10000);
      const coverLetter = page.locator('textarea');

      await coverLetter.fill(longText);

      // Should accept long text
      const value = await coverLetter.inputValue();
      expect(value.length).toBe(10000);
    });

    test('should handle rapid form submissions', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      await page.route('/api/apply-job', (route) => {
        route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify({ success: true }),
        });
      });

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

      // Click multiple times rapidly
      await submitButton.click();
      await submitButton.click();
      await submitButton.click();

      // Should only submit once (button should be disabled during submission)
      await page.waitForTimeout(1000);

      // Check that we get success state (not multiple submissions)
      const successIcons = page.locator('div:has-text("✅")');
      expect(await successIcons.count()).toBeLessThanOrEqual(1);
    });

    test('should handle network timeout gracefully', async ({ page }) => {
      await page.goto('/en/careers');

      const applyButton = page.locator('button:has-text("Apply Now")').first();

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

      await applyButton.click();

      // Fill form
      await page.fill('input[placeholder*="full name"]', 'Test User');
      await page.fill('input[type="email"]', 'test@example.com');
      await page.fill('input[type="tel"]', '+966501234567');
      await page.locator('input[type="file"]').setInputFiles(testPdfPath);

      await page.waitForTimeout(300);

      // Simulate timeout by never responding
      await page.route('/api/apply-job', () => {
        // Don't fulfill the route - simulates timeout
      });

      await page.locator('button[type="submit"]').click();

      // Wait for potential timeout handling
      await page.waitForTimeout(5000);

      // Form should still be functional or show error
      const isFormVisible = await page.locator('form').isVisible();
      const isErrorVisible = await page.locator('text=/Submission Failed/i').isVisible();

      expect(isFormVisible || isErrorVisible).toBeTruthy();
    });
  });
});
