import { describe, it, expect, vi } from "vitest";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import "../i18n";
import { OptionsCombobox, type Option } from "./options-combobox";

const options: Option[] = [
  { id: "t1", labels: [{ lang: "en", label: "Wood" }] },
  { id: "t2", labels: [{ lang: "en", label: "Bronze" }] },
];

function setup(value = "") {
  const onChange = vi.fn();

  render(
    <OptionsCombobox
      id="material"
      value={value}
      onChange={onChange}
      options={options}
      lang="en"
      placeholder="Select…"
    />,
  );

  return { onChange };
}

describe("OptionsCombobox", () => {
  it("filters by label and selects the option id", async () => {
    const user = userEvent.setup();
    const { onChange } = setup();

    const input = screen.getByPlaceholderText("Select…");

    await user.click(input);
    await user.type(input, "bro");

    const body = within(document.body);

    expect(body.queryByText("Wood")).toBeNull();
    await user.click(await body.findByText("Bronze"));

    expect(onChange).toHaveBeenCalledWith("t2");
  });

  it("shows the selected option's label", () => {
    setup("t1");
    expect(screen.getByDisplayValue("Wood")).toBeInTheDocument();
  });

  it("gives the open control a translated accessible name", () => {
    setup();
    expect(screen.getByRole("button", { name: /open/i })).toBeInTheDocument();
  });

  it("clears the selection when the Clear button is clicked", async () => {
    const user = userEvent.setup();
    const { onChange } = setup("t1");

    const clearBtn = document.querySelector("[data-slot=combobox-clear]") as HTMLElement;
    expect(clearBtn).not.toBeNull();

    await user.click(clearBtn);

    expect(onChange).toHaveBeenCalledWith("");
  });
});
