import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { StringListEditor } from "../StringListEditor";

describe("StringListEditor", () => {
  it("renders duplicate items and updates the correct entry", () => {
    const handleChange = vi.fn();

    render(
      <StringListEditor
        items={["foo", "foo"]}
        onChange={handleChange}
        placeholder="Value"
      />,
    );

    const inputs = screen.getAllByRole("textbox");
    expect(inputs).toHaveLength(2);
    const firstInput = inputs[0]!;
    const secondInput = inputs[1]!;
    expect(firstInput).toHaveValue("foo");
    expect(secondInput).toHaveValue("foo");

    fireEvent.change(firstInput, { target: { value: "bar" } });
    expect(handleChange).toHaveBeenLastCalledWith(["bar", "foo"]);
  });

  it("removes the correct item when delete is clicked", () => {
    const handleChange = vi.fn();

    render(
      <StringListEditor
        items={["one", "two", "three"]}
        onChange={handleChange}
      />,
    );

    const deleteButtons = screen.getAllByRole("button", { name: /Remove entry/i });
    expect(deleteButtons).toHaveLength(3);
    const secondDeleteButton = deleteButtons[1]!;

    fireEvent.click(secondDeleteButton);
    expect(handleChange).toHaveBeenLastCalledWith(["one", "three"]);
  });
});
