import { fireEvent, render } from "@testing-library/react";
import React from "react";

import { TagButton } from "../TagButton";

describe("TagButton", () => {
  describe("rendering", () => {
    it("has default class tag__action", () => {
      const { getByRole } = render(
        <TagButton iconName="close" ariaLabel="Close" />,
      );
      expect(getByRole("button")).toHaveClass("tag__action");
    });

    it("renders the provided icon", () => {
      const { container } = render(
        <TagButton iconName="close" ariaLabel="Close" />,
      );
      expect(container.querySelector(".icon")).toBeInTheDocument();
    });

    it("accepts custom className", () => {
      const { getByRole } = render(
        <TagButton
          iconName="close"
          ariaLabel="Close"
          className="custom-class"
        />,
      );
      expect(getByRole("button")).toHaveClass("custom-class");
    });

    it("forwards ref to button element", () => {
      const ref = React.createRef();
      render(<TagButton iconName="close" ariaLabel="Close" ref={ref} />);
      expect(ref.current).toBeInstanceOf(HTMLButtonElement);
    });
  });

  describe("size prop", () => {
    it("adds tag__action--large class when size is large", () => {
      const { getByRole } = render(
        <TagButton iconName="close" ariaLabel="Close" size="large" />,
      );
      expect(getByRole("button")).toHaveClass("tag__action--large");
    });

    it("uses medium icon size for large buttons", () => {
      const { container } = render(
        <TagButton iconName="close" ariaLabel="Close" size="large" />,
      );
      expect(container.querySelector(".icon--medium")).toBeInTheDocument();
    });

    it("uses small icon size for default size buttons", () => {
      const { container } = render(
        <TagButton iconName="close" ariaLabel="Close" />,
      );
      expect(container.querySelector(".icon--small")).toBeInTheDocument();
    });
  });

  describe("interaction", () => {
    it("calls onClick when clicked", () => {
      const handleClick = vi.fn();
      const { getByRole } = render(
        <TagButton iconName="close" ariaLabel="Close" onClick={handleClick} />,
      );

      fireEvent.click(getByRole("button"));
      expect(handleClick).toHaveBeenCalledTimes(1);
    });

    it("does not call onClick when disabled", () => {
      const handleClick = vi.fn();
      const { getByRole } = render(
        <TagButton
          iconName="close"
          ariaLabel="Close"
          onClick={handleClick}
          isDisabled
        />,
      );

      fireEvent.click(getByRole("button"));
      expect(handleClick).not.toHaveBeenCalled();
    });

    it("has aria-disabled attribute when disabled", () => {
      const { getByRole } = render(
        <TagButton iconName="close" ariaLabel="Close" isDisabled />,
      );

      expect(getByRole("button")).toHaveAttribute("aria-disabled", "true");
    });
  });
});
