import { act } from "react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createRoot, type Root } from "react-dom/client";
import { PageOptionsSidebar } from "./page-options-sidebar";
import type { PageOptionsState, DocumentStats } from "@/types/page-options";

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

function buildStats(): DocumentStats {
  return {
    wordCount: 3,
    characterCount: 12,
    blockCount: 1,
    todoTotal: 0,
    todoDone: 0,
  };
}

describe("PageOptionsSidebar", () => {
  let container: HTMLDivElement;
  let root: Root;

  beforeEach(() => {
    (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
      true;
    container = document.createElement("div");
    document.body.appendChild(container);
    root = createRoot(container);
  });

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

  it("对已保存但未完成编辑器语义的设置应显示降级说明", () => {
    act(() => {
      root.render(
        <PageOptionsSidebar
          documentId="doc-1"
          options={buildOptions({ showHeadingNumbers: true, embedDefaultBlockId: "block-1" })}
          stats={buildStats()}
          onToggle={() => undefined}
          onExport={() => undefined}
          onOpenHistory={() => undefined}
        />,
      );
    });

    expect(container.textContent).toContain("标题编号");
    expect(container.textContent).toContain("已保存字段");
    expect(container.textContent).toContain("编辑器语义暂未正式接通");

    const customTab = container.querySelectorAll("button")[1];
    expect(customTab).not.toBeNull();

    act(() => {
      customTab?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    expect(container.textContent).toContain("嵌入默认位置");
    expect(container.textContent).toContain("这是已保存字段");
    expect(container.textContent).toContain("当前编辑器语义暂未正式接通");
  });
});
