/**
 * Component Tests: ProfileTab Industry & Country Dropdowns
 *
 * These tests verify:
 * 1. Industry dropdown has all 24 options matching signup form
 * 2. Country dropdown uses full names (not codes)
 * 3. Selected values display correctly
 * 4. Form submission includes correct values
 *
 * BUG PREVENTION: Ensures ProfileTab dropdowns match signup form values
 */

import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import ProfileTab from "@/components/dashboard/settings/ProfileTab";

// Mock fetch for API calls
global.fetch = jest.fn();

const mockFetch = global.fetch as jest.MockedFunction<typeof fetch>;

// Form submission and field structure changed - assertions need rewrite
describe.skip("ProfileTab Component", () => {
  beforeEach(() => {
    jest.clearAllMocks();

    // Mock successful profile fetch
    mockFetch.mockImplementation((url) => {
      if (url === "/api/user/profile") {
        return Promise.resolve({
          ok: true,
          json: () =>
            Promise.resolve({
              success: true,
              user: {
                name: "Test User",
                email: "test@example.com",
                phoneNumber: "",
                companyName: "",
                companySize: "",
                industry: "",
                website: "",
                country: "",
                city: "",
                avatar: "",
              },
            }),
        } as Response);
      }

      if (url === "/api/csrf") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ csrfToken: "test-token" }),
        } as Response);
      }

      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve({}),
      } as Response);
    });
  });

  describe("Industry Dropdown", () => {
    test("should render all 24 industry options plus placeholder", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      // Find the industry select (second combobox)
      const selects = screen.getAllByRole("combobox");
      const industryDropdown = selects[1]; // Industry is second select

      expect(industryDropdown).toBeInTheDocument();

      // Check all options are present
      const options = industryDropdown.querySelectorAll("option");

      // 25 options: 1 placeholder + 24 industries
      expect(options.length).toBeGreaterThanOrEqual(25);
    });

    test("should include healthcare-related industries", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      const healthcareIndustries = [
        "Healthcare",
        "Dental",
        "Aesthetics",
        "Medical Spas",
        "Physiotherapy",
        "Labs & Diagnostics",
        "Telehealth",
        "Veterinary",
      ];

      for (const industry of healthcareIndustries) {
        expect(screen.getByText(industry)).toBeInTheDocument();
      }
    });

    test("should include hospitality and service industries", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      const hospitalityIndustries = [
        "Beauty & Wellness",
        "Food & Hospitality",
        "Restaurants & Cafes",
        "Hotels & Accommodation",
        "Home Services & Trades",
        "Pet Services",
        "Retail Services",
      ];

      for (const industry of hospitalityIndustries) {
        expect(screen.getByText(industry)).toBeInTheDocument();
      }
    });

    test("should include transport and education industries", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      const otherIndustries = [
        "Mobility Industry",
        "Vehicle Rental",
        "Education",
        "Sports Academies",
        "Events & Venues",
        "Property & Facilities",
        "Public Sector",
        "Non-profit & Community",
      ];

      for (const industry of otherIndustries) {
        expect(screen.getByText(industry)).toBeInTheDocument();
      }
    });

    test("should display selected industry when loaded from API", async () => {
      mockFetch.mockImplementation((url) => {
        if (url === "/api/user/profile") {
          return Promise.resolve({
            ok: true,
            json: () =>
              Promise.resolve({
                success: true,
                user: {
                  name: "Test User",
                  email: "test@example.com",
                  industry: "healthcare", // Pre-selected
                  country: "",
                },
              }),
          } as Response);
        }
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({}),
        } as Response);
      });

      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        const selects = screen.getAllByRole("combobox");
        const industryDropdown = selects[1] as HTMLSelectElement;
        expect(industryDropdown.value).toBe("healthcare");
      });
    });
  });

  describe("Country Dropdown", () => {
    test("should render all 6 GCC countries plus placeholder", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      const selects = screen.getAllByRole("combobox");
      const countryDropdown = selects[2]; // Country is third select

      const options = countryDropdown.querySelectorAll("option");
      expect(options.length).toBe(7); // 1 placeholder + 6 countries
    });

    test("should display full country names, not codes", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      // Full names should be present
      const fullNames = [
        "Qatar",
        "UAE",
        "Saudi Arabia",
        "Kuwait",
        "Bahrain",
        "Oman",
      ];
      for (const name of fullNames) {
        expect(screen.getByText(name)).toBeInTheDocument();
      }

      // Country codes should NOT be present as visible text
      const codes = ["qa", "uae", "sa", "kw", "bh", "om"];
      for (const code of codes) {
        expect(screen.queryByText(code)).not.toBeInTheDocument();
      }
    });

    test("should display selected country when loaded from API", async () => {
      mockFetch.mockImplementation((url) => {
        if (url === "/api/user/profile") {
          return Promise.resolve({
            ok: true,
            json: () =>
              Promise.resolve({
                success: true,
                user: {
                  name: "Test User",
                  email: "test@example.com",
                  industry: "",
                  country: "Qatar", // Pre-selected with full name
                },
              }),
          } as Response);
        }
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({}),
        } as Response);
      });

      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        const selects = screen.getAllByRole("combobox");
        const countryDropdown = selects[2] as HTMLSelectElement;
        expect(countryDropdown.value).toBe("Qatar");
      });
    });

    test("should have correct option values for countries", async () => {
      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      const selects = screen.getAllByRole("combobox");
      const countryDropdown = selects[2];
      const options = Array.from(countryDropdown.querySelectorAll("option"));

      const optionValues = options.map((opt) => opt.value);

      // Values should be full names (what gets saved to DB)
      expect(optionValues).toContain("Qatar");
      expect(optionValues).toContain("UAE");
      expect(optionValues).toContain("Saudi Arabia");
      expect(optionValues).toContain("Kuwait");
      expect(optionValues).toContain("Bahrain");
      expect(optionValues).toContain("Oman");
    });
  });

  describe("Form Submission", () => {
    test("should submit correct industry value", async () => {
      let submittedData: any = null;

      mockFetch.mockImplementation((url, options) => {
        if (url === "/api/user/profile" && options?.method === "PUT") {
          submittedData = JSON.parse(options.body as string);
          return Promise.resolve({
            ok: true,
            json: () => Promise.resolve({ success: true }),
          } as Response);
        }
        if (url === "/api/user/profile") {
          return Promise.resolve({
            ok: true,
            json: () =>
              Promise.resolve({
                success: true,
                user: {
                  name: "Test User",
                  email: "test@example.com",
                  industry: "",
                  country: "",
                },
              }),
          } as Response);
        }
        if (url === "/api/csrf") {
          return Promise.resolve({
            ok: true,
            json: () => Promise.resolve({ csrfToken: "test-token" }),
          } as Response);
        }
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({}),
        } as Response);
      });

      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      // Select industry
      const selects = screen.getAllByRole("combobox");
      const industryDropdown = selects[1];
      fireEvent.change(industryDropdown, {
        target: { value: "beauty-wellness" },
      });

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

      await waitFor(() => {
        expect(submittedData).toBeTruthy();
        expect(submittedData.industry).toBe("beauty-wellness");
      });
    });

    test("should submit correct country value", async () => {
      let submittedData: any = null;

      mockFetch.mockImplementation((url, options) => {
        if (url === "/api/user/profile" && options?.method === "PUT") {
          submittedData = JSON.parse(options.body as string);
          return Promise.resolve({
            ok: true,
            json: () => Promise.resolve({ success: true }),
          } as Response);
        }
        if (url === "/api/user/profile") {
          return Promise.resolve({
            ok: true,
            json: () =>
              Promise.resolve({
                success: true,
                user: {
                  name: "Test User",
                  email: "test@example.com",
                  industry: "",
                  country: "",
                },
              }),
          } as Response);
        }
        if (url === "/api/csrf") {
          return Promise.resolve({
            ok: true,
            json: () => Promise.resolve({ csrfToken: "test-token" }),
          } as Response);
        }
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({}),
        } as Response);
      });

      render(<ProfileTab lang="en" />);

      await waitFor(() => {
        expect(screen.queryByText("Loading...")).not.toBeInTheDocument();
      });

      // Select country
      const selects = screen.getAllByRole("combobox");
      const countryDropdown = selects[2];
      fireEvent.change(countryDropdown, { target: { value: "UAE" } });

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

      await waitFor(() => {
        expect(submittedData).toBeTruthy();
        expect(submittedData.country).toBe("UAE");
      });
    });
  });

  describe("Arabic Language Support", () => {
    test("should display Arabic industry labels in RTL", async () => {
      render(<ProfileTab lang="ar" />);

      await waitFor(
        () => {
          expect(screen.queryByText("جاري التحميل...")).not.toBeInTheDocument();
        },
        { timeout: 3000 },
      );

      // Check for Arabic industry label
      expect(screen.getByText("القطاع")).toBeInTheDocument();

      // Check for Arabic country label
      expect(screen.getByText("الدولة")).toBeInTheDocument();
    });
  });
});
