import { act } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRoot, type Root } from "react-dom/client";
import { DocumentReadView } from "./document-read-view";
import type { PageOptionsState } from "@/types/page-options";

function buildOptions(overrides: Partial<PageOptionsState> = {}): PageOptionsState {
  return {
    wideLayout: false,
    smallText: false,
    showHeadingNumbers: false,
    showToc: false,
    showStructure: false,
    protectEditing: false,
    showWordCount: false,
    collapseBacklinks: false,
    pageFont: "default",
    layoutDensity: "normal",
    hideChildPages: false,
    showBlockRefCount: false,
    embedDefaultBlockId: null,
    ...overrides,
  };
}

describe("DocumentReadView media attachments", () => {
  let container: HTMLDivElement;
  let root: Root;

  beforeEach(() => {
    (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
    vi.stubGlobal("location", new URL("https://mnote.example.com/documents/doc_1"));
    container = document.createElement("div");
    document.body.appendChild(container);
    root = createRoot(container);
  });

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

  it("renders Office media as a Wolai-like attachment row that opens OnlyOffice in a new window", () => {
    act(() => {
      root.render(
        <DocumentReadView
          documentId="doc_1"
          options={buildOptions()}
          content={{
            blocks: [
              {
                id: "block_asset_1",
                type: "media",
                props: {
                  assetType: "file",
                  assetId: "asset_ppt_1",
                  documentId: "doc_1",
                  fileName: "2023自我介绍PPT_李爱波0831.pptx",
                  fileUrl: "https://storage.example.com/demo.pptx?token=abc",
                  mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                  fileSize: 12_110_520,
                },
              },
            ],
          }}
        />,
      );
    });

    const row = container.querySelector<HTMLAnchorElement>('[data-testid="mnote-office-attachment-row"]');
    expect(row).not.toBeNull();
    expect(row?.target).toBe("_blank");
    expect(row?.rel).toContain("noreferrer");
    expect(row?.textContent).toContain("2023自我介绍PPT_李爱波0831.pptx");
    expect(row?.textContent).toContain("11.55 MB");
    expect(row?.getAttribute("href")).toContain("/onlyoffice?");
    expect(row?.getAttribute("href")).toContain("fileType=pptx");
    expect(row?.getAttribute("href")).toContain("assetId=asset_ppt_1");
    expect(row?.getAttribute("href")).toContain("documentId=doc_1");
    expect(row?.querySelector('[aria-label="预览"]')).not.toBeNull();
  });
});
