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

test("Footnotes after Setext headings keep their links across chunks", WEB, async ({ t3, app, screen, browser }) => {
  const document = (underline: string, ticks = true) => {
    const tick = ticks ? "`" : "";
    const paragraphs = Array.from({ length: 60 }, (_, i) =>
      `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Paragraph ${i + 1}.` +
      (i === 33 ? "\n\nSecond note[^second] and repeat[^1]." : ""));
    return `Using the ${tick} character\n${underline}\nA footnote reference.[^1] before typing ${tick}.\n\n${paragraphs.join("\n\n")}\n\n[^1]: The footnote text.\n[^second]: The second footnote.\n`;
  };
  const project = await t3.project("Footnote documentation", {
    "footnotes.md": document("===================="),
    "dash.md": document("-----"),
    "control.md": document("====================", false),
  });
  const start = () => t3.thread({ project, title: "Footnote preview", messages: ["Open the documentation."] });
  const thread = await start().catch(() => start()).catch(() => start());
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const results: number[] = [];
  for (const file of ["footnotes.md", "dash.md", "control.md"]) {
    await expect.poll(() => browser.evaluate((file) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector(`[data-item-path="${file}"]`);
        if (row) { (row as HTMLElement).click(); return true; }
      }
      return false;
    }, file)).toBe(true);
    await screen.getByRole("button", "Show rendered markdown").tap();
    await screen.getByText("A footnote reference.", { exact: false }).waitFor();
    await app.screenshot(file.replace(".md", ""));
    results.push(await browser.evaluate(() => {
      const paragraph = Array.from(document.querySelectorAll("p")).find((p) => p.textContent?.startsWith("A footnote reference."));
      return paragraph?.querySelectorAll('a[data-footnote-ref][href="#user-content-fn-1"]').length ?? 0;
    }));
    await screen.getByRole("button", "Show markdown source").tap();
  }
  expect(results).toEqual([1, 1, 1]);
});
