import React from "react";
import "@testing-library/jest-dom/extend-expect";
import { render, fireEvent, act } from "@testing-library/react";
import Popover from "../popover";

test("should open base popover", () => {
  const { queryByTestId } = render(
    <Popover reference={<span data-testid="click-id">Click me</span>} placement={undefined}>
      <div data-testid="popover-content">Content</div>
    </Popover>
  );

  expect(queryByTestId("click-id")).toBeTruthy();
  expect(queryByTestId("honeyui-popover")).toBeTruthy();
  expect(queryByTestId("honeyui-popover")).not.toHaveClass("show");

  fireEvent.click(queryByTestId("click-id"));

  expect(queryByTestId("honeyui-popover")).toHaveClass("show");

  fireEvent.click(document.body);

  expect(queryByTestId("honeyui-popover")).not.toHaveClass("show");
});

test("should have custom className", () => {
  const { queryByTestId } = render(
    <Popover
      className="test-class"
      data-testid="popover-id"
      reference={<span data-testid="click-id">Click me</span>}
      placement="bottom"
    >
      <div data-testid="popover-content">Content</div>
    </Popover>
  );

  expect(queryByTestId("popover-id")).toBeTruthy();
  expect(queryByTestId("popover-id")).toHaveClass("test-class");
});

test("should have correct placement", () => {
  const popover1 = render(
    <Popover
      placement="top-end"
      data-testid="popover-id"
      reference={<span data-testid="click-id">Click me</span>}
    >
      <div data-testid="popover-content">Content</div>
    </Popover>
  );

  expect(popover1.queryByTestId("popover-id")).toBeTruthy();
  expect(popover1.queryByTestId("popover-id")).toHaveClass("bs-popover-top");
  expect(popover1.queryByTestId("popover-id")).toHaveClass("bs-popover-end");
});

test("should have content", () => {
  const popover1 = render(
    <Popover
      placement="top"
      data-testid="popover-id"
      content={<div data-testid="popover-content3">Content</div>}
      reference={<span data-testid="click-id">Click me</span>}
    />
  );

  expect(popover1.queryByTestId("popover-content3")).toBeTruthy();
});

test("should have support external close", () => {
  const actionsRef = React.createRef<{ close: () => void }>();

  const popover = render(
    <Popover
      actions={actionsRef}
      placement="top"
      data-testid="popover-id"
      content={<div data-testid="popover-content3">Content</div>}
      reference={<button data-testid="click-id">Click me</button>}
    />
  );

  expect(popover.queryByTestId("popover-id")).not.toHaveClass("show");
  fireEvent.click(popover.queryByTestId("click-id"));
  expect(popover.queryByTestId("popover-id")).toHaveClass("show");

  act(() => {
    actionsRef.current.close();
  });

  expect(popover.queryByTestId("popover-id")).not.toHaveClass("show");
});
