import { act, assertEquals, cleanup, fireEvent, render } from "./setup.ts";
import { EditorMode } from "../../islands/Editor.tsx";
import TopBar from "../../islands/TopBar.tsx";

const baseProps = {
  allowMode: EditorMode.Read,
  isLogined: false,
  shared: false,
  title: "Test Post",
  id: "abc123",
};

Deno.test({
  name: "TopBar - renders download icon for non-logged-in user",
  fn() {
    const { container } = render(<TopBar {...baseProps} isLogined={false} />);
    const downloadIcons = container.querySelectorAll(".bi-download");
    assertEquals(downloadIcons.length, 1);
    assertEquals(downloadIcons[0].getAttribute("title"), "Download");
    cleanup();
  },
  sanitizeResources: false,
  sanitizeOps: false,
});

Deno.test({
  name: "TopBar - renders download icon for logged-in user",
  fn() {
    const { container } = render(<TopBar {...baseProps} isLogined />);
    const downloadIcons = container.querySelectorAll(".bi-download");
    assertEquals(downloadIcons.length, 1);
    assertEquals(downloadIcons[0].getAttribute("title"), "Download");
    cleanup();
  },
  sanitizeResources: false,
  sanitizeOps: false,
});

Deno.test({
  name: "TopBar - click download dispatches DownloadRequest event with title",
  fn() {
    const dispatched: { type: string; detail: string }[] = [];
    const originalDispatchEvent = globalThis.dispatchEvent;
    // deno-lint-ignore no-explicit-any
    (globalThis as any).dispatchEvent = (e: Event) => {
      dispatched.push({
        type: e.type,
        detail: (e as CustomEvent).detail,
      });
    };

    const { container } = render(<TopBar {...baseProps} />);
    const icon = container.querySelector(".bi-download")!;
    act(() => {
      fireEvent.click(icon);
    });

    assertEquals(dispatched.length, 1);
    assertEquals(dispatched[0].type, "DownloadRequest");
    assertEquals(dispatched[0].detail, "Test Post");

    // deno-lint-ignore no-explicit-any
    (globalThis as any).dispatchEvent = originalDispatchEvent;
    cleanup();
  },
  sanitizeResources: false,
  sanitizeOps: false,
});

Deno.test({
  name: "TopBar - click download dispatches empty string for empty title",
  fn() {
    const dispatched: { type: string; detail: string }[] = [];
    const originalDispatchEvent = globalThis.dispatchEvent;
    // deno-lint-ignore no-explicit-any
    (globalThis as any).dispatchEvent = (e: Event) => {
      dispatched.push({
        type: e.type,
        detail: (e as CustomEvent).detail,
      });
    };

    const { container } = render(<TopBar {...baseProps} title="" />);
    const icon = container.querySelector(".bi-download")!;
    act(() => {
      fireEvent.click(icon);
    });

    assertEquals(dispatched.length, 1);
    assertEquals(dispatched[0].type, "DownloadRequest");
    assertEquals(dispatched[0].detail, "");

    // deno-lint-ignore no-explicit-any
    (globalThis as any).dispatchEvent = originalDispatchEvent;
    cleanup();
  },
  sanitizeResources: false,
  sanitizeOps: false,
});
