import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { afterEach, describe, expect, it } from "vitest";
import { Chip, ChipsInput, RemoveChipButton } from "./chip-input";
afterEach(cleanup);
describe("ChipsInput Component", () => {
    it("should render correctly", () => {
        render(<ChipsInput name="tags"/>);
        const input = screen.getByRole("textbox");
        expect(input).toBeTruthy();
    });
    it("should add chips on Enter", () => {
        render(<ChipsInput name="tags"/>);
        const input = screen.getByRole("textbox");
        fireEvent.change(input, { target: { value: "react" } });
        fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
        expect(screen.getByText("react")).toBeTruthy();
        expect(input.value).toBe("");
    });
    it("should add chips on paste (with separator)", () => {
        render(<ChipsInput name="tags" separator=","/>);
        const input = screen.getByRole("textbox");
        fireEvent.change(input, { target: { value: "react, vue" } });
        expect(screen.getByText("react")).toBeTruthy();
        expect(screen.getByText("vue")).toBeTruthy();
        expect(input.value).toBe("");
    });
    it("should remove chip on Backspace when input is empty", () => {
        render(<ChipsInput name="tags" defaultValue="react"/>);
        const input = screen.getByRole("textbox");
        expect(screen.getByText("react")).toBeTruthy();
        // Focus input
        input.focus();
        // First backspace highlights the last chip
        fireEvent.keyDown(input, { key: "Backspace", code: "Backspace" });
        // Second backspace deletes it
        fireEvent.keyDown(input, { key: "Backspace", code: "Backspace" });
        expect(screen.queryByText("react")).toBeNull();
    });
    it("should update hidden input value", () => {
        render(<ChipsInput name="tags" defaultValue="react,vue"/>);
        // Hidden input is not accessible by role, so we use selector or name
        // But testing-library recommends testing user visible things.
        // However, we can check the value prop if we controlled it, or check the DOM.
        // The hidden input has name="tags".
        const hiddenInput = document.querySelector('input[name="tags"]');
        expect(hiddenInput.value).toBe("react,vue");
    });
    it("should use custom render function", () => {
        render(<ChipsInput name="tags" defaultValue="react" render={({ value, onDelete }) => (<Chip>
                        {value}
                        <RemoveChipButton onClick={onDelete} aria-label="remove"/>
                    </Chip>)}/>);
        expect(screen.getByText("react")).toBeTruthy();
        const removeBtn = screen.getByLabelText("remove");
        fireEvent.click(removeBtn);
        expect(screen.queryByText("react")).toBeNull();
    });
});
