import { fireEvent, render, screen } from "@testing-library/react";
import { examples } from "../../lib/examples";
import useNavState from "../../store/navStore";
import CelexSelector from "./CelexSelector";

jest.mock("../../store/navStore");

describe("CelexSelector", () => {
  const mockSetCelexId = jest.fn();
  const mockSetArticleId = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    jest.mocked(useNavState).mockReturnValue({
      celexId: "",
      setCelexId: mockSetCelexId,
      setArticleId: mockSetArticleId,
    });
  });

  it("renders the dropdown with options", () => {
    render(<CelexSelector />);

    expect(screen.getByLabelText("Select example:")).toBeInTheDocument();
    expect(screen.getByRole("combobox")).toBeInTheDocument();

    const options = screen.getAllByRole("option");
    expect(options).toHaveLength(examples.length);
    for (const i in examples) {
      expect(options[i]).toHaveValue(examples[i].id);
      expect(options[i]).toHaveTextContent(examples[i].name);
    }
  });

  it("calls setCelexId and setArticleId on selection change", () => {
    const celexId = "32016R0679";
    render(<CelexSelector />);

    fireEvent.change(screen.getByRole("combobox"), {
      target: { value: celexId },
    });

    expect(mockSetCelexId).toHaveBeenCalledWith(celexId);
    expect(mockSetArticleId).toHaveBeenCalledWith(1);
  });

  it("sets the correct value in the dropdown based on celexId", () => {
    const mockCelexId = "32024R1689";
    jest.mocked(useNavState).mockReturnValue({
      celexId: mockCelexId,
      setCelexId: mockSetCelexId,
      setArticleId: mockSetArticleId,
    });

    render(<CelexSelector />);

    expect(screen.getByRole("combobox")).toHaveValue(mockCelexId);
  });
});
