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

test("Later chunks retain the first definition after list and HTML boundaries", WEB, async ({ t3, app, screen, browser }) => {
  const cases = [
    { name: "empty-list", prefix: "-", duplicate: true },
    { name: "list-html", prefix: "- x\n<n>", duplicate: true },
    { name: "quote-html", prefix: ">x\n</e>", duplicate: true },
    { name: "empty-list-nodup", prefix: "-", duplicate: false },
    { name: "list-html-nodup", prefix: "- x\n<n>", duplicate: false },
    { name: "quote-html-nodup", prefix: ">x\n</e>", duplicate: false },
    { name: "control", prefix: "intro\n", duplicate: true },
  ];
  const files = Object.fromEntries(cases.map(c => [`${c.name}.md`, `${c.prefix}\n[release notes]: /first\n\n${"x".repeat(4100)}\n\n# Next\n\n${c.duplicate ? "[release notes]: /later\n\n" : ""}[Release][release notes]\n`]));
  const project = await t3.project("markdown-boundaries", files);
  const thread = await t3.thread({ project, title: "Markdown reference definitions", messages: ["Check the release documentation."] });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  const results: Record<string, string | null> = {};
  for (const c of cases) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(`${c.name}.md`);
    await screen.getByRole("option", `${c.name}.md`, { exact: false }).tap();
    await screen.getByRole("button", /^Show (rendered markdown|markdown source)$/).waitFor();
    const toggle = screen.getByRole("button", "Show rendered markdown");
    if (await toggle.count()) await toggle.tap();
    await screen.getByRole("heading", "Next", { exact: true }).waitFor();
    await screen.getByRole("heading", "Next", { exact: true }).scrollIntoView();
    results[c.name] = await browser.evaluate(() => {
      const panel = document.querySelector("[data-right-panel-surface-content]");
      return [...(panel?.querySelectorAll("a") ?? [])].find(a => a.textContent === "Release")?.getAttribute("href") ?? null;
    });
    const link = screen.getByRole("link", "Release", { exact: true });
    if (await link.count()) await link.hover();
    await app.screenshot(c.name);
    await screen.getByRole("button", `Close ${c.name}.md`, { exact: true }).tap();
  }
  expect(results).toEqual(Object.fromEntries(cases.map(c => [c.name, "/first"])));
});
