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

// Pauses after captures keep each navigation destination readable in the recording.
test("Escaped bracket footnotes navigate across Markdown chunks", WEB, async ({ t3, app, browser, screen }) => {
  const markdown = "First[^a\\]] " + "lead ".repeat(900) + "\n\n# Second\n\n[^a\\]]: Escaped note\n";
  const project = await t3.project("documentation", { "escaped.md": markdown });
  const thread = await t3.thread({ project, title: "Markdown footnotes", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await screen.getByRole("treeitem", "escaped.md", { exact: true }).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("button", "Hide file explorer").tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await screen.getByText(/^First.*lead/).waitFor();
  await app.screenshot("escaped-footnote-reference");
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
  const citation = browser.locator("a[data-footnote-ref]");
  await expect(citation).toHaveCount(1);
  const point = await browser.evaluate(() => {
    const link = document.querySelector("a[data-footnote-ref]")!;
    const range = document.createRange();
    range.selectNodeContents(link);
    const rect = range.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(browser.locator("section[data-footnotes]")).toContainText("Escaped note");
  await app.screenshot("escaped-footnote-destination");
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
  await browser.locator("a[data-footnote-backref]").tap();
  await expect.poll(() => browser.evaluate(() => {
    const link = document.querySelector("a[data-footnote-ref]");
    if (!link) return false;
    const range = document.createRange();
    range.selectNodeContents(link);
    const rect = range.getBoundingClientRect();
    return rect.width > 0 && rect.top >= 0 && rect.bottom <= innerHeight;
  })).toBe(true);
  await app.screenshot("escaped-footnote-return");
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
});
