/* @vitest-environment jsdom */

import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
  type Mock,
  vi,
} from "vitest";

import { FullscreenImageViewer } from "../fullscreen-image-viewer";

describe("FullscreenImageViewer", () => {
  let container: HTMLDivElement;
  let root: Root;
  let onClose: Mock<() => void>;

  beforeEach(() => {
    (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
      .IS_REACT_ACT_ENVIRONMENT = true;
    container = document.createElement("div");
    document.body.append(container);
    root = createRoot(container);
    onClose = vi.fn<() => void>();

    act(() => {
      root.render(
        <FullscreenImageViewer
          characterId="elio-silvestri"
          remoteMessageId="message-1"
          imageUrl="/chat-image.png"
          onClose={onClose}
        />,
      );
    });
  });

  afterEach(() => {
    act(() => root.unmount());
    container.remove();
  });

  it("closes exactly once when the fullscreen image is tapped", () => {
    const image = container.querySelector("img");
    expect(image).not.toBeNull();

    act(() => image?.click());

    expect(onClose).toHaveBeenCalledTimes(1);
  });

  it("closes exactly once from the visible back button", () => {
    const backButton = container.querySelector<HTMLButtonElement>(
      'button[aria-label="Back"]',
    );
    expect(backButton).not.toBeNull();

    act(() => backButton?.click());

    expect(onClose).toHaveBeenCalledTimes(1);
  });

  it("closes from the backdrop and Escape key", () => {
    const viewer = container.querySelector<HTMLDivElement>(
      '[aria-label="Fullscreen image"]',
    );
    expect(viewer).not.toBeNull();

    act(() => viewer?.click());
    act(() =>
      document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })),
    );

    expect(onClose).toHaveBeenCalledTimes(2);
  });
});
