import React from "react";
import { Button } from "./index";

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

import "@testing-library/jest-dom";

describe("Button", () => {
  it("renders children content", () => {
    render(<Button>Click me</Button>);
    expect(screen.getByRole("button")).toHaveTextContent("Click me");
  });

  it("has correct displayName", () => {
    expect(Button.displayName).toBe("Button");
  });

  it("applies className", () => {
    render(<Button className="btn-primary">Styled</Button>);
    expect(screen.getByRole("button")).toHaveClass("btn-primary");
  });

  it("applies inline style", () => {
    render(<Button style={{ color: "red" }}>Styled</Button>);
    expect(screen.getByRole("button").style.color).toBe("red");
  });

  it("defaults className to empty string", () => {
    render(<Button>Default</Button>);
    expect(screen.getByRole("button")).toHaveAttribute("class", "");
  });

  it("disables button when disabled prop is true", () => {
    render(<Button disabled={true}>Disabled</Button>);
    expect(screen.getByRole("button")).toBeDisabled();
  });

  it("is enabled by default", () => {
    render(<Button>Enabled</Button>);
    expect(screen.getByRole("button")).not.toBeDisabled();
  });

  it("calls onClick handler when clicked", () => {
    const onClick = jest.fn();
    render(<Button onClick={onClick}>Click</Button>);
    fireEvent.click(screen.getByRole("button"));
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it("does not call onClick when disabled", () => {
    const onClick = jest.fn();
    render(
      <Button onClick={onClick} disabled={true}>
        Click
      </Button>
    );
    fireEvent.click(screen.getByRole("button"));
    expect(onClick).not.toHaveBeenCalled();
  });

  it("forwards ref to button element", () => {
    const ref = React.createRef<HTMLButtonElement>();
    render(<Button ref={ref}>Ref</Button>);
    expect(ref.current).toBeInstanceOf(HTMLButtonElement);
  });

  it("passes additional HTML attributes", () => {
    render(
      <Button data-testid="custom-btn" id="my-btn">
        Attr
      </Button>
    );
    const btn = screen.getByTestId("custom-btn");
    expect(btn).toHaveAttribute("id", "my-btn");
  });

  it("renders without children", () => {
    const { container } = render(<Button />);
    expect(container.querySelector("button")).toBeInTheDocument();
  });

  it("supports type attribute", () => {
    render(<Button type="submit">Submit</Button>);
    expect(screen.getByRole("button")).toHaveAttribute("type", "submit");
  });

  it("passes aria attributes", () => {
    render(<Button aria-label="Close">X</Button>);
    expect(screen.getByRole("button")).toHaveAttribute("aria-label", "Close");
  });
});
