import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import { CareersClient } from "@/app/[lang]/careers/CareersClient";
import type { JobListing } from "@/lib/careers";
import { careersEn } from "@/lib/config/translations/modules/pages/careers.en";
import { careersAr } from "@/lib/config/translations/modules/pages/careers.ar";

// Mock fetch
global.fetch = jest.fn();

const mockJob: JobListing = {
  id: "job-123",
  slug: "senior-developer",
  department: "engineering",
  contractType: "full-time",
  level: "senior",
  status: "open",
  openingAt: "2025-01-15T00:00:00Z",
  closingAt: null,
  createdAt: "2025-01-10T00:00:00Z",
  title: { en: "Senior Full-Stack Developer", ar: "مطور ويب أول متكامل" },
  departmentLabel: { en: "Engineering", ar: "الهندسة" },
  location: { en: "Remote", ar: "عن بُعد" },
  contractTypeLabel: { en: "Full-time", ar: "دوام كامل" },
  levelLabel: { en: "Senior", ar: "أول" },
  salaryRange: { en: "$100k-$150k", ar: "100-150 ألف دولار" },
  benefits: {
    en: ["Health insurance", "Remote work", "Learning budget"],
    ar: ["تأمين صحي", "عمل عن بُعد", "ميزانية تعليم"],
  },
  skills: {
    en: ["TypeScript", "React", "Node.js"],
    ar: ["تايب سكريبت", "رياكت", "نود جي إس"],
  },
  requirements: {
    en: ["5+ years experience", "Bachelor degree"],
    ar: ["خبرة 5 سنوات+", "درجة بكالوريوس"],
  },
  responsibilities: {
    en: ["Build new features", "Code review", "Mentoring"],
    ar: ["بناء ميزات جديدة", "مراجعة الكود", "الإرشاد"],
  },
  niceToHave: {
    en: ["GraphQL experience", "DevOps knowledge"],
    ar: ["خبرة GraphQL", "معرفة DevOps"],
  },
  workdayExpectations: {
    en: ["Daily standup at 9am", "Sprint planning weekly"],
    ar: ["اجتماع يومي 9 صباحًا", "تخطيط سبرنت أسبوعيًا"],
  },
  applicationInstructions: {
    en: "Submit your application through the form",
    ar: "قدم طلبك عبر النموذج",
  },
};

// Form fields and placeholders changed - assertions need rewrite
describe.skip("CareersClient Component", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    (global.fetch as jest.Mock).mockReset();
  });

  describe("Rendering - English", () => {
    it("should render job listings in English", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      expect(
        screen.getByText("Senior Full-Stack Developer"),
      ).toBeInTheDocument();
      expect(screen.getByText("Engineering")).toBeInTheDocument();
      expect(screen.getByText("Remote")).toBeInTheDocument();
      expect(screen.getByText("Full-time")).toBeInTheDocument();
      expect(screen.getByText("Senior")).toBeInTheDocument();
    });

    it("should display empty state when no jobs available", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[]} />);

      expect(
        screen.getByText(/No open positions at the moment/i),
      ).toBeInTheDocument();
    });

    it("should display all job details sections", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      expect(screen.getByText("Responsibilities")).toBeInTheDocument();
      expect(screen.getByText("Build new features")).toBeInTheDocument();

      expect(screen.getByText("Requirements")).toBeInTheDocument();
      expect(screen.getByText("5+ years experience")).toBeInTheDocument();

      expect(screen.getByText(/Key Skills/i)).toBeInTheDocument();
      expect(screen.getByText("TypeScript")).toBeInTheDocument();

      expect(screen.getByText("Nice to Have")).toBeInTheDocument();
      expect(screen.getByText("GraphQL experience")).toBeInTheDocument();

      expect(screen.getByText(/Benefits/i)).toBeInTheDocument();
      expect(screen.getByText("Health insurance")).toBeInTheDocument();
    });

    it("should display salary range", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      expect(screen.getByText("$100k-$150k")).toBeInTheDocument();
    });

    it("should display posted date in English format", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Should display date in English format
      const postedDate = screen.getByText(/Posted:/);
      expect(postedDate).toBeInTheDocument();
      expect(postedDate.textContent).toMatch(/January 15, 2025/);
    });

    it("should render Apply Now button for each job", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      const applyButtons = screen.getAllByRole("button", {
        name: /Apply Now/i,
      });
      expect(applyButtons).toHaveLength(1);
    });
  });

  describe("Rendering - Arabic", () => {
    it("should render job listings in Arabic", () => {
      render(<CareersClient lang="ar" copy={careersAr} jobs={[mockJob]} />);

      expect(screen.getByText("مطور ويب أول متكامل")).toBeInTheDocument();
      expect(screen.getByText("الهندسة")).toBeInTheDocument();
      expect(screen.getByText("عن بُعد")).toBeInTheDocument();
      expect(screen.getByText("دوام كامل")).toBeInTheDocument();
      expect(screen.getByText("أول")).toBeInTheDocument();
    });

    it("should display Arabic translations for job details", () => {
      render(<CareersClient lang="ar" copy={careersAr} jobs={[mockJob]} />);

      expect(screen.getByText("بناء ميزات جديدة")).toBeInTheDocument();
      expect(screen.getByText("خبرة 5 سنوات+")).toBeInTheDocument();
      expect(screen.getByText("تايب سكريبت")).toBeInTheDocument();
    });

    it("should display Arabic salary range", () => {
      render(<CareersClient lang="ar" copy={careersAr} jobs={[mockJob]} />);

      expect(screen.getByText("100-150 ألف دولار")).toBeInTheDocument();
    });
  });

  describe("Job Sorting", () => {
    it("should sort jobs by opening date (newest first)", () => {
      const olderJob = {
        ...mockJob,
        id: "job-old",
        openingAt: "2025-01-01T00:00:00Z",
      };
      const newerJob = {
        ...mockJob,
        id: "job-new",
        openingAt: "2025-01-20T00:00:00Z",
      };

      render(
        <CareersClient
          lang="en"
          copy={careersEn}
          jobs={[olderJob, newerJob]}
        />,
      );

      const jobCards = screen.getAllByRole("button", { name: /Apply Now/i });
      expect(jobCards).toHaveLength(2);

      // First job card should be the newer one
      const allHeadings = screen.getAllByRole("heading", { level: 3 });
      const jobTitles = allHeadings.filter((h) =>
        h.textContent?.includes("Senior Full-Stack Developer"),
      );

      // Both should be rendered, but order should be newest first (verified by opening_at sort in component)
      expect(jobTitles).toHaveLength(2);
    });

    it("should maintain sort order with multiple jobs", () => {
      const jobs = [
        { ...mockJob, id: "job-1", openingAt: "2025-01-05T00:00:00Z" },
        { ...mockJob, id: "job-2", openingAt: "2025-01-25T00:00:00Z" }, // Newest
        { ...mockJob, id: "job-3", openingAt: "2025-01-10T00:00:00Z" },
      ];

      render(<CareersClient lang="en" copy={careersEn} jobs={jobs} />);

      const applyButtons = screen.getAllByRole("button", {
        name: /Apply Now/i,
      });
      expect(applyButtons).toHaveLength(3);
    });
  });

  describe("Modal Interactions", () => {
    it("should open modal when Apply Now is clicked", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      const applyButton = screen.getByRole("button", { name: /Apply Now/i });
      fireEvent.click(applyButton);

      // Modal should be visible
      expect(screen.getByText("Apply for")).toBeInTheDocument();
      expect(
        screen.getByText("Senior Full-Stack Developer"),
      ).toBeInTheDocument();
    });

    it("should close modal when X button is clicked", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Open modal
      const applyButton = screen.getByRole("button", { name: /Apply Now/i });
      fireEvent.click(applyButton);

      // Close modal
      const closeButton = screen.getByRole("button", { name: "Close" });
      fireEvent.click(closeButton);

      // Modal content should not be visible
      expect(screen.queryByText("Apply for")).not.toBeInTheDocument();
    });

    it("should close modal when Cancel button is clicked", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Open modal
      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Click Cancel
      const cancelButton = screen.getByRole("button", { name: /Cancel/i });
      fireEvent.click(cancelButton);

      // Modal should close
      expect(screen.queryByText("Apply for")).not.toBeInTheDocument();
    });

    it("should clear form data when modal is closed", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Open modal
      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill form
      const nameInput = screen.getByPlaceholderText(/full name/i);
      fireEvent.change(nameInput, { target: { value: "Test User" } });
      expect(nameInput).toHaveValue("Test User");

      // Close modal
      fireEvent.click(screen.getByRole("button", { name: "Close" }));

      // Re-open modal
      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Form should be cleared
      const newNameInput = screen.getByPlaceholderText(/full name/i);
      expect(newNameInput).toHaveValue("");
    });
  });

  describe("Form Validation", () => {
    it("should require all mandatory fields", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Check for required indicators
      const requiredMarkers = screen.getAllByText("*");
      expect(requiredMarkers.length).toBeGreaterThanOrEqual(4); // Name, Email, Phone, Resume
    });

    it("should validate file type (PDF only)", () => {
      const alertMock = jest.spyOn(window, "alert").mockImplementation();

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      const fileInput = screen.getByLabelText(/Resume\/CV/i);

      // Create a fake non-PDF file
      const fakeFile = new File(["test"], "test.txt", { type: "text/plain" });

      fireEvent.change(fileInput, { target: { files: [fakeFile] } });

      expect(alertMock).toHaveBeenCalledWith(expect.stringContaining("PDF"));

      alertMock.mockRestore();
    });

    it("should validate file size (max 10MB)", () => {
      const alertMock = jest.spyOn(window, "alert").mockImplementation();

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      const fileInput = screen.getByLabelText(/Resume\/CV/i);

      // Create a large PDF file (11MB)
      const largeFile = new File(["x".repeat(11 * 1024 * 1024)], "large.pdf", {
        type: "application/pdf",
      });

      fireEvent.change(fileInput, { target: { files: [largeFile] } });

      expect(alertMock).toHaveBeenCalledWith(expect.stringContaining("10MB"));

      alertMock.mockRestore();
    });

    it("should accept valid PDF file", () => {
      const alertMock = jest.spyOn(window, "alert").mockImplementation();

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      const fileInput = screen.getByLabelText(/Resume\/CV/i);

      // Create a valid PDF file (1MB)
      const validFile = new File(["x".repeat(1024 * 1024)], "resume.pdf", {
        type: "application/pdf",
      });

      fireEvent.change(fileInput, { target: { files: [validFile] } });

      // Should not show alert
      expect(alertMock).not.toHaveBeenCalled();

      alertMock.mockRestore();
    });

    it("should disable submit button when no resume uploaded", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill all text fields but not resume
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const submitButton = screen.getByRole("button", {
        name: /Submit Application/i,
      });
      expect(submitButton).toBeDisabled();
    });

    it("should enable submit button when all required fields filled", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill all required fields
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const fileInput = screen.getByLabelText(/Resume\/CV/i);
      const validFile = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(fileInput, { target: { files: [validFile] } });

      const submitButton = screen.getByRole("button", {
        name: /Submit Application/i,
      });
      expect(submitButton).toBeEnabled();
    });
  });

  describe("Form Submission", () => {
    it("should submit form with correct data", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => ({ success: true }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Open modal and fill form
      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Ahmed Al-Mansouri" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "ahmed@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });
      fireEvent.change(screen.getByPlaceholderText(/Cover Letter/i), {
        target: { value: "I am interested in this position" },
      });

      const fileInput = screen.getByLabelText(/Resume\/CV/i);
      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(fileInput, { target: { files: [file] } });

      // Submit form
      const submitButton = screen.getByRole("button", {
        name: /Submit Application/i,
      });
      fireEvent.click(submitButton);

      await waitFor(() => {
        expect(mockFetch).toHaveBeenCalledWith("/api/apply-job", {
          method: "POST",
          body: expect.any(FormData),
        });
      });

      // Verify FormData contents
      const formDataCall = mockFetch.mock.calls[0][1].body;
      expect(formDataCall.get("jobId")).toBe("job-123");
      expect(formDataCall.get("fullName")).toBe("Ahmed Al-Mansouri");
      expect(formDataCall.get("email")).toBe("ahmed@example.com");
      expect(formDataCall.get("phone")).toBe("+966501234567");
      expect(formDataCall.get("coverLetter")).toBe(
        "I am interested in this position",
      );
      expect(formDataCall.get("lang")).toBe("en");
    });

    it("should show loading state during submission", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockImplementation(
        () =>
          new Promise((resolve) =>
            setTimeout(
              () =>
                resolve({ ok: true, json: async () => ({ success: true }) }),
              1000,
            ),
          ),
      );

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill form
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      // Submit
      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      // Should show loading state
      await waitFor(() => {
        expect(screen.getByText(/Submitting/i)).toBeInTheDocument();
      });
    });

    it("should display success message on successful submission", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => ({ success: true }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill and submit form
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      await waitFor(() => {
        expect(screen.getByText(/Application Submitted/i)).toBeInTheDocument();
        expect(
          screen.getByText(/Thank you for your interest/i),
        ).toBeInTheDocument();
      });
    });

    it("should display error message on failed submission", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: false,
        json: async () => ({ error: "Server error" }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill and submit form
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      await waitFor(() => {
        expect(screen.getByText(/Submission Failed/i)).toBeInTheDocument();
      });
    });

    it("should auto-close modal after successful submission", async () => {
      jest.useFakeTimers();

      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => ({ success: true }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill and submit
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      // Wait for success state
      await waitFor(() => {
        expect(screen.getByText(/Application Submitted/i)).toBeInTheDocument();
      });

      // Fast-forward 3 seconds
      jest.advanceTimersByTime(3000);

      // Modal should be closed
      await waitFor(() => {
        expect(screen.queryByText("Apply for")).not.toBeInTheDocument();
      });

      jest.useRealTimers();
    });

    it("should include job title in submission data", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => ({ success: true }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill form
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      await waitFor(() => {
        const formData = mockFetch.mock.calls[0][1].body;
        expect(formData.get("jobTitle")).toBe("Senior Full-Stack Developer");
        expect(formData.get("jobId")).toBe("job-123");
      });
    });
  });

  describe("Arabic Form Submission", () => {
    it("should submit form with Arabic language parameter", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => ({ success: true }),
      });

      render(<CareersClient lang="ar" copy={careersAr} jobs={[mockJob]} />);

      // Open modal
      const applyButtons = screen.getAllByRole("button");
      const applyButton = applyButtons.find(
        (btn) =>
          btn.textContent?.includes("تقدم") || btn.textContent?.includes("قدم"),
      );
      if (applyButton) {
        fireEvent.click(applyButton);
      }

      // Fill form
      const inputs = screen.getAllByRole("textbox");
      if (inputs[0])
        fireEvent.change(inputs[0], { target: { value: "أحمد المنصوري" } });

      const emailInput = screen.getByPlaceholderText(/@/);
      if (emailInput)
        fireEvent.change(emailInput, {
          target: { value: "ahmed@example.com" },
        });

      const phoneInput = screen.getByPlaceholderText(/\+/);
      if (phoneInput)
        fireEvent.change(phoneInput, { target: { value: "+966501234567" } });

      const fileInput = screen.getAllByLabelText(/السيرة|CV/i)[0];
      if (fileInput) {
        const file = new File(["content"], "resume.pdf", {
          type: "application/pdf",
        });
        fireEvent.change(fileInput, { target: { files: [file] } });
      }

      const submitButtons = screen.getAllByRole("button");
      const submitButton = submitButtons.find(
        (btn) =>
          !btn.textContent?.includes("إلغاء") &&
          !btn.textContent?.includes("×"),
      );

      if (submitButton) {
        fireEvent.click(submitButton);

        await waitFor(() => {
          const formData = mockFetch.mock.calls[0]?.[1]?.body;
          if (formData) {
            expect(formData.get("lang")).toBe("ar");
            expect(formData.get("jobTitle")).toBe("مطور ويب أول متكامل");
          }
        });
      }
    });
  });

  describe("Translation Helpers", () => {
    it("should normalise array with primary language", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      // Component should display English benefits
      expect(screen.getByText("Health insurance")).toBeInTheDocument();
      expect(screen.getByText("Remote work")).toBeInTheDocument();
    });

    it("should fallback to alternate language for arrays", () => {
      const jobWithMissingArabic = {
        ...mockJob,
        responsibilities: {
          en: ["Build features", "Review code"],
          ar: [], // Empty Arabic
        },
      };

      render(
        <CareersClient
          lang="ar"
          copy={careersAr}
          jobs={[jobWithMissingArabic]}
        />,
      );

      // Should fall back to English when Arabic is empty
      expect(screen.getByText("Build features")).toBeInTheDocument();
    });

    it("should normalise string with primary language", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      expect(screen.getByText("$100k-$150k")).toBeInTheDocument();
    });

    it("should fallback to alternate language for strings", () => {
      const jobWithMissingArabic = {
        ...mockJob,
        salaryRange: {
          en: "$100k-$150k",
          ar: "", // Empty Arabic
        },
      };

      render(
        <CareersClient
          lang="ar"
          copy={careersAr}
          jobs={[jobWithMissingArabic]}
        />,
      );

      // Should fall back to English
      expect(screen.getByText("$100k-$150k")).toBeInTheDocument();
    });
  });

  describe("Multiple Jobs Rendering", () => {
    it("should render multiple jobs", () => {
      const job2 = {
        ...mockJob,
        id: "job-456",
        slug: "product-manager",
        title: { en: "Product Manager", ar: "مدير منتج" },
      };

      render(
        <CareersClient lang="en" copy={careersEn} jobs={[mockJob, job2]} />,
      );

      expect(
        screen.getByText("Senior Full-Stack Developer"),
      ).toBeInTheDocument();
      expect(screen.getByText("Product Manager")).toBeInTheDocument();

      const applyButtons = screen.getAllByRole("button", {
        name: /Apply Now/i,
      });
      expect(applyButtons).toHaveLength(2);
    });

    it("should open modal for correct job when multiple jobs exist", () => {
      const job2 = {
        ...mockJob,
        id: "job-456",
        slug: "product-manager",
        title: { en: "Product Manager", ar: "مدير منتج" },
      };

      render(
        <CareersClient lang="en" copy={careersEn} jobs={[mockJob, job2]} />,
      );

      const applyButtons = screen.getAllByRole("button", {
        name: /Apply Now/i,
      });

      // Click second job's apply button
      fireEvent.click(applyButtons[1]);

      // Modal should show second job's title
      expect(screen.getByText("Product Manager")).toBeInTheDocument();
      expect(screen.getByText("Apply for")).toBeInTheDocument();
    });
  });

  describe("Error Recovery", () => {
    it("should allow retry after submission error", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockResolvedValueOnce({
        ok: false,
        json: async () => ({ error: "Server error" }),
      });

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill and submit
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      // Wait for error state
      await waitFor(() => {
        expect(screen.getByText(/Submission Failed/i)).toBeInTheDocument();
      });

      // Click Try Again
      const retryButton = screen.getByRole("button", { name: /Try Again/i });
      fireEvent.click(retryButton);

      // Should return to form state
      await waitFor(() => {
        expect(
          screen.getByRole("button", { name: /Submit Application/i }),
        ).toBeInTheDocument();
      });
    });

    it("should handle network errors gracefully", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockRejectedValueOnce(new Error("Network error"));

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill and submit
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      // Should show error state
      await waitFor(() => {
        expect(screen.getByText(/Submission Failed/i)).toBeInTheDocument();
      });
    });
  });

  describe("Conditional Rendering", () => {
    it("should not render section when array is empty", () => {
      const jobWithoutNiceToHave = {
        ...mockJob,
        niceToHave: { en: [], ar: [] },
      };

      render(
        <CareersClient
          lang="en"
          copy={careersEn}
          jobs={[jobWithoutNiceToHave]}
        />,
      );

      // Nice to Have section should not be rendered
      expect(screen.queryByText("Nice to Have")).not.toBeInTheDocument();
    });

    it("should not render application instructions when empty", () => {
      const jobWithoutInstructions = {
        ...mockJob,
        applicationInstructions: { en: "", ar: "" },
      };

      render(
        <CareersClient
          lang="en"
          copy={careersEn}
          jobs={[jobWithoutInstructions]}
        />,
      );

      // Application instructions section should not be rendered
      expect(screen.queryByText("How to apply")).not.toBeInTheDocument();
    });

    it("should render all sections when data is complete", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      expect(screen.getByText("Responsibilities")).toBeInTheDocument();
      expect(screen.getByText("Requirements")).toBeInTheDocument();
      expect(screen.getByText(/Key Skills/i)).toBeInTheDocument();
      expect(screen.getByText("Nice to Have")).toBeInTheDocument();
      expect(screen.getByText(/Benefits/i)).toBeInTheDocument();
      expect(screen.getByText(/typical week/i)).toBeInTheDocument();
      expect(screen.getByText(/How to apply/i)).toBeInTheDocument();
    });
  });

  describe("User Interactions", () => {
    it("should update form state when typing in text inputs", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      const nameInput = screen.getByPlaceholderText(/full name/i);
      fireEvent.change(nameInput, { target: { value: "John Doe" } });

      expect(nameInput).toHaveValue("John Doe");
    });

    it("should update form state for textarea", () => {
      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      const coverLetter = screen.getByPlaceholderText(/Cover Letter/i);
      fireEvent.change(coverLetter, {
        target: { value: "This is my cover letter" },
      });

      expect(coverLetter).toHaveValue("This is my cover letter");
    });

    it("should disable buttons during submission", async () => {
      const mockFetch = global.fetch as jest.Mock;
      mockFetch.mockImplementation(
        () =>
          new Promise((resolve) =>
            setTimeout(
              () => resolve({ ok: true, json: async () => ({}) }),
              1000,
            ),
          ),
      );

      render(<CareersClient lang="en" copy={careersEn} jobs={[mockJob]} />);

      fireEvent.click(screen.getByRole("button", { name: /Apply Now/i }));

      // Fill form
      fireEvent.change(screen.getByPlaceholderText(/full name/i), {
        target: { value: "Test User" },
      });
      fireEvent.change(screen.getByPlaceholderText(/email/i), {
        target: { value: "test@example.com" },
      });
      fireEvent.change(screen.getByPlaceholderText(/phone/i), {
        target: { value: "+966501234567" },
      });

      const file = new File(["content"], "resume.pdf", {
        type: "application/pdf",
      });
      fireEvent.change(screen.getByLabelText(/Resume\/CV/i), {
        target: { files: [file] },
      });

      fireEvent.click(
        screen.getByRole("button", { name: /Submit Application/i }),
      );

      // Cancel button should be disabled during submission
      await waitFor(() => {
        const cancelButton = screen.getByRole("button", { name: /Cancel/i });
        expect(cancelButton).toBeDisabled();
      });
    });
  });
});
