import { fireEvent, render, screen } from "@solidjs/testing-library";
import { describe, expect, it } from "vitest";
import { Popover } from "../../../src/components/popover/index";

describe("Popover", () => {
  it("content has role=dialog when open", () => {
    render(() => (
      <Popover defaultOpen>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>Content</Popover.Content>
      </Popover>
    ));
    expect(screen.getByRole("dialog")).toBeTruthy();
  });
  it("trigger has correct ARIA", () => {
    render(() => (
      <Popover>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>Content</Popover.Content>
      </Popover>
    ));
    const trigger = screen.getByText("Open");
    expect(trigger.getAttribute("aria-haspopup")).toBe("dialog");
    expect(trigger.getAttribute("aria-expanded")).toBe("false");
  });
  it("click trigger opens", () => {
    render(() => (
      <Popover>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>Content</Popover.Content>
      </Popover>
    ));
    fireEvent.click(screen.getByText("Open"));
    expect(screen.getByRole("dialog")).toBeTruthy();
  });
  it("Escape closes", () => {
    render(() => (
      <Popover defaultOpen>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>Content</Popover.Content>
      </Popover>
    ));
    fireEvent.keyDown(document, { key: "Escape" });
    expect(screen.queryByRole("dialog")).toBeNull();
  });
  it("Close button closes", () => {
    render(() => (
      <Popover defaultOpen>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>
          <Popover.Close>X</Popover.Close>
          Content
        </Popover.Content>
      </Popover>
    ));
    fireEvent.click(screen.getByText("X"));
    expect(screen.queryByRole("dialog")).toBeNull();
  });
  it("controlled mode", () => {
    render(() => (
      <Popover open={true} onOpenChange={() => {}}>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content>Content</Popover.Content>
      </Popover>
    ));
    expect(screen.getByRole("dialog")).toBeTruthy();
  });
  it("content is positioned", () => {
    render(() => (
      <Popover defaultOpen>
        <Popover.Trigger>Open</Popover.Trigger>
        <Popover.Content data-testid="content">Content</Popover.Content>
      </Popover>
    ));
    expect(screen.getByTestId("content").style.position).toBeTruthy();
  });
});
