import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

async function headingsOdt() {
  const headings = [1, 2, 3, 4, 5, 6, 9, "invalid", "missing"].map((level) =>
    `<text:h${level === "missing" ? "" : ` text:outline-level="${level}"`}>${typeof level === "number" ? `Level ${level} heading` : `${level} level heading`}</text:h>${typeof level === "number" && level <= 4 ? `<text:p>Body paragraph following level ${level}.</text:p>` : ""}`,
  ).join("");
  return new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("content.xml", `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3"><office:body><office:text>${headings}</office:text></office:body></office:document-content>`)
    .generateAsync({ type: "uint8array" });
}

test("ODT previews retain explicit heading levels and fallback levels", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("heading-demo", { "headings.odt": await headingsOdt() });
  const thread = await t3.thread({ project, title: "Review heading hierarchy", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "headings.odt").tap();
  await screen.getByText("1 page", { exact: false }).waitFor({ timeout: 120_000 });
  await screen.getByRole("button", "Maximize panel").tap();
  await screen.getByRole("button", "Decrease reading size").tap();
  await app.screenshot("heading hierarchy");
  const frame = browser.frameLocator('iframe[title^="headings.odt"]');
  const levels: Record<string, string[]> = {};
  for (let level = 1; level <= 6; level++) {
    levels[`h${level}`] = await frame.locator(`h${level}`).allTextContents();
  }
  await expect(levels).toEqual({
    h1: ["Level 1 heading"],
    h2: ["Level 2 heading", "invalid level heading", "missing level heading"],
    h3: ["Level 3 heading"], h4: ["Level 4 heading"], h5: ["Level 5 heading"],
    h6: ["Level 6 heading", "Level 9 heading"],
  });
});
