import { createRoot } from "solid-js";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createDismiss } from "../../src/utilities/dismiss/create-dismiss";

describe("createDismiss", () => {
  afterEach(() => {
    document.body.innerHTML = "";
  });

  it("calls onDismiss when Escape key is pressed", () => {
    const container = document.createElement("div");
    document.body.appendChild(container);

    createRoot((dispose) => {
      const onDismiss = vi.fn();
      const dismiss = createDismiss({ getContainer: () => container, onDismiss });
      dismiss.attach();

      document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
      expect(onDismiss).toHaveBeenCalledTimes(1);

      dismiss.detach();
      dispose();
    });
  });

  it("calls onDismiss when pointer is pressed outside container", () => {
    const container = document.createElement("div");
    document.body.appendChild(container);
    const outside = document.createElement("button");
    document.body.appendChild(outside);

    createRoot((dispose) => {
      const onDismiss = vi.fn();
      const dismiss = createDismiss({ getContainer: () => container, onDismiss });
      dismiss.attach();

      outside.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
      expect(onDismiss).toHaveBeenCalledTimes(1);

      dismiss.detach();
      dispose();
    });
  });

  it("does not call onDismiss when pointer is inside container", () => {
    const container = document.createElement("div");
    const inner = document.createElement("button");
    container.appendChild(inner);
    document.body.appendChild(container);

    createRoot((dispose) => {
      const onDismiss = vi.fn();
      const dismiss = createDismiss({ getContainer: () => container, onDismiss });
      dismiss.attach();

      inner.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
      expect(onDismiss).not.toHaveBeenCalled();

      dismiss.detach();
      dispose();
    });
  });

  it("does not call onDismiss after detach", () => {
    const container = document.createElement("div");
    document.body.appendChild(container);

    createRoot((dispose) => {
      const onDismiss = vi.fn();
      const dismiss = createDismiss({ getContainer: () => container, onDismiss });
      dismiss.attach();
      dismiss.detach();

      document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
      expect(onDismiss).not.toHaveBeenCalled();
      dispose();
    });
  });
});
