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("已正式接通的设置不应再显示未接通降级文案，planned 设置应明确标记为待接线", () => {
    act(() => {
      root.render(
        <PageOptionsSidebar
          documentId="doc-1"
          options={buildOptions({
            showHeadingNumbers: true,
            protectEditing: true,
            showBlockRefCount: true,
            embedDefaultBlockId: "block-1",
          })}
          stats={buildStats()}
          onToggle={() => undefined}
          onExport={() => undefined}
          onOpenHistory={() => undefined}
        />,
      );
    });

    expect(container.textContent).toContain("标题编号");
    expect(container.textContent).not.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("当前：block-1");
    expect(container.textContent).not.toContain("这是已保存字段，但当前编辑器语义暂未正式接通。");
    expect(container.textContent).toContain("显示块引用数字");
    expect(container.textContent).toContain("当前为占位能力");
  });

  it("纯占位设置不应继续制造“已开启/已关闭但没有实际效果”的交互假象", () => {
    const toggled: string[] = [];

    act(() => {
      root.render(
        <PageOptionsSidebar
          documentId="doc-1"
          options={buildOptions({ showBlockRefCount: true })}
          stats={buildStats()}
          onToggle={(key) => {
            toggled.push(key);
          }}
          onExport={() => undefined}
          onOpenHistory={() => undefined}
        />,
      );
    });

    const customTab = container.querySelectorAll("button")[1];
    expect(customTab).not.toBeNull();
    act(() => {
      customTab?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    const placeholderToggle = Array.from(container.querySelectorAll("button")).find((button) =>
      button.textContent?.includes("显示块引用数字"),
    );
    expect(placeholderToggle?.textContent).toContain("待接线");

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

    expect(toggled).toEqual([]);
  });
});
