import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ScriptTable } from "@/components/artifact/ScriptTable";
import { ScriptElementTable } from "@/components/artifact/ScriptElementTable";
import type { ScriptElementRow, ScriptParagraphRow } from "@/lib/types";

const paragraph: ScriptParagraphRow = {
  id: 1,
  rowId: 1,
  index: 1,
  level: 1,
  depth: 0,
  name: "机制拆解",
  contentRange: ["图1-2", "标题", "正文: 第二段"],
  sections: {
    theme: { label: "主题", description: "解释份额换订单", descriptionParts: [{ type: "text", text: "解释" }, { type: "element", id: 10, name: "份额换订单", resolved: true, text: "[元素:10]" }], dimensions: [{ type: "主维度", name: "核心竞争力", value: "份额换订单" }] },
    form: { label: "形式", description: "案例拆解", descriptionParts: [{ type: "text", text: "案例拆解" }], dimensions: [] },
    function: { label: "作用", description: "承接上文", descriptionParts: [{ type: "text", text: "承接上文" }], dimensions: [] },
    feeling: { label: "感受", description: "建立可信度", descriptionParts: [{ type: "text", text: "建立可信度" }], dimensions: [] },
  },
  fullDescription: "通过元素解释机制。",
  fullDescriptionParts: [
    { type: "text", text: "通过" },
    { type: "element", id: 10, name: "份额换订单", resolved: true, text: "[元素:10]" },
    { type: "text", text: "解释机制。" },
  ],
};

const element: ScriptElementRow = {
  id: 10,
  rowId: 10,
  name: "份额换订单",
  primaryDimension: "核心竞争力",
  secondaryDimension: "商业模式",
  paragraphs: [{ id: 1, index: 1, name: "机制拆解" }],
};

describe("full script table", () => {
  it("matches the original complete table fields and element references", () => {
    const openElement = vi.fn();
    render(<ScriptTable paragraphs={[paragraph]} elements={[element]} onOpenElement={openElement} />);
    expect(screen.getAllByText("维度类型")).toHaveLength(4);
    expect(screen.getByText("核心竞争力")).toBeInTheDocument();
    expect(screen.getByText("图1-2")).toBeInTheDocument();
    expect(screen.getByText("正文: 第二段")).toBeInTheDocument();
    fireEvent.click(screen.getAllByRole("button", { name: "份额换订单" })[0]);
    expect(openElement).toHaveBeenCalledWith(10);
    expect(screen.getByText("创作目录大纲（段本身）")).toBeInTheDocument();
  });

  it("shows element dimensions and linked paragraphs", () => {
    render(<ScriptElementTable elements={[element]} selectedId={10} />);
    expect(screen.getByRole("row", { name: /份额换订单/ })).toHaveClass("isSelected");
    expect(screen.getByText("商业模式")).toBeInTheDocument();
    expect(screen.getByText("第 1 段")).toBeInTheDocument();
    expect(screen.getByText("机制拆解")).toBeInTheDocument();
  });
});
