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

const paragraphs = Array.from({ length: 60 }, (_, i) =>
  `Paragraph ${i + 1}. This synthetic document checks footnotes across Markdown chunks. Each paragraph supplies enough ordinary prose to separate the opening reference from its trailing definition.${i === 25 ? " Another label.[^second]" : ""}${i === 45 ? " Repeated first reference.[^1]" : ""}`,
);
const markdown = ["A footnote reference.[^1]", ...paragraphs, "A final repeated reference.[^1]", "[^1]: The footnote text.", "[^second]: The second footnote text."].join("\n\n");

test("Footnotes resolve across chunked Markdown previews", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("footnote-demo", { "footnotes.md": markdown });
  const thread = await t3.thread({ project, title: "Review footnotes", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor({ timeout: 120_000 });
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("footnotes.md");
  await screen.getByRole("option", "footnotes.md", { exact: false }).tap();
  await screen.getByRole("button", "Show rendered markdown", { exact: true }).tap();
  await screen.getByText("A footnote reference.", { exact: false }).waitFor();
  await app.screenshot("opening-footnote-reference");
  const refs = browser.locator("a[data-footnote-ref]");
  await expect(refs.nth(0)).toHaveText("1");
  const point = await browser.evaluate(() => {
    const rect = document.querySelector("sup:has(a[data-footnote-ref])")!.getBoundingClientRect();
    return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
  });
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await expect(screen.getByText("The footnote text.", { exact: false })).toBeVisible();
  await app.screenshot("footnotes-after-reference-click");
  await expect(browser.locator("section[data-footnotes]")).toHaveCount(1);
  await expect(browser.locator("a[data-footnote-backref]")).toHaveCount(4);
  const back = await browser.evaluate(() => {
    const rect = document.querySelector("a[data-footnote-backref]")!.getBoundingClientRect();
    return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
  });
  await browser.mouse.move(back.x, back.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await expect(screen.getByText("A footnote reference.", { exact: false })).toBeVisible();
  await app.screenshot("opening-reference-after-backref");
});
