/**
 * TEAM: frontend_infra
 * @flow strict
 */

import * as React from "react";
import {render, screen} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import SelectInputExperimental from "../SelectInput_experimental";

function mountSelect(
  props: ?$Shape<React.ElementConfig<typeof SelectInputExperimental>>
) {
  return render(
    <SelectInputExperimental
      disabled={true}
      onChange={() => {}}
      value=""
      {...props}
    >
      {props?.children ?? ""}
    </SelectInputExperimental>
  );
}

/** Tests behavior specifically tied to SelectInput's connecting behavior
 * between TextInput and DropdownList, those components' test will cover
 * nested behavior */
describe("SelectInput", () => {
  it("renders with a selectable element", () => {
    const result = mountSelect();

    expect(result.getByRole("button") != null).toBe(true);
  });
  it("selecting the button opens a dropdown", async () => {
    const result = mountSelect();
    const selectInputButton = result.getByRole("button");

    userEvent.click(selectInputButton);

    expect(screen.getByRole("listbox") != null).toBe(true);
  });
  it("selecting the select input displays passed options", async () => {
    const options = ["a", "b", "foo", "bar"];
    const result = mountSelect({
      children: options.map(option => (
        <SelectInputExperimental.Option key={option} value={option} />
      )),
    });
    const selectInputButton = result.getByRole("button");

    userEvent.click(selectInputButton);

    options.forEach(option => {
      expect(screen.getByText(option) != null).toBe(true);
    });
  });
  it("passing a value displays correctly", async () => {
    const value = "what is a sandwich?";
    const result = mountSelect({
      value,
    });

    expect(result.getByDisplayValue(value) != null).toBe(true);
  });
});
