/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Chunked Markdown keeps the first reference and original fence content", WEB, async ({ t3, app, browser, screen }) => {
  const tasks = "[ref]: /dst\n\n" + "x".repeat(4100) + "\n\n# Tasks\n\n- [ ] Verify reference preview\n- [ ] Leave this unchecked\n";
  const project = await t3.project("markdown-proof", {
    "tasks.md": tasks,
    "dup.md": "[id]: /first\n\n" + "x".repeat(4100) + "\n\n# Next\n[id]: /later\n\n[id]\n",
    "fence.md": "[ref]: /dst\n\n```text\nshown",
  });
  const thread = await t3.thread({ project, title: "Markdown reference proof", 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", "fence.md", { exact: true }).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByText("shown", { exact: false }).waitFor();
  const fence = await browser.evaluate(() => [...document.querySelectorAll("pre")].map(e => e.textContent).find(t => t?.includes("shown"))?.trim());
  await app.screenshot("unclosed-fence");
  await screen.getByRole("treeitem", "dup.md", { exact: true }).tap();
  await screen.getByRole("heading", "Next", { exact: true }).waitFor();
  await browser.evaluate(() => { document.querySelector("h1")?.scrollIntoView({ block: "center" }); return null; });
  const destination = await browser.evaluate(() => [...document.querySelectorAll("a")].find(e => e.textContent === "id")?.getAttribute("href"));
  await browser.evaluate(() => { const a = [...document.querySelectorAll("a")].find(e => e.textContent === "id"); if(a) { const label = document.createElement("span"); label.textContent = `  href="${a.getAttribute("href")}"`; label.style.cssText = "color:#ef4444;font-size:16px"; a.after(label); } return null; });
  await app.screenshot("first-reference-destination");
  await screen.getByRole("treeitem", "tasks.md", { exact: true }).tap();
  await screen.getByRole("heading", "Tasks", { exact: true }).waitFor();
  await browser.evaluate(() => { [...document.querySelectorAll("h1")].find(e => e.textContent === "Tasks")?.scrollIntoView({ block: "center" }); return null; });
  await screen.getByRole("checkbox", "Toggle task").nth(0).tap();
  await expect.poll(() => readFile(`${project}/tasks.md`, "utf8")).toBe(tasks.replace("- [ ] Verify", "- [x] Verify"));
  await app.screenshot("checkbox-saved-correct-source");
  await screen.getByRole("checkbox", "Toggle task").nth(0).tap();
  await expect.poll(() => readFile(`${project}/tasks.md`, "utf8")).toBe(tasks);
  await expect({ fence, destination }).toEqual({ fence: "shown", destination: "/first" });
});
