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

test("Footnotes resolve across Markdown chunks and navigate both ways", WEB, async ({ t3, app, browser, screen }) => {
  const paragraphs = Array.from({ length: 60 }, (_, i) => `Paragraph ${i + 1}. This is background prose for the document, separated by blank lines so the preview renders multiple chunks of Markdown. ${i === 30 ? "A second label.[^other] Repeat the opening reference.[^1]" : ""}`);
  const markdown = ["A footnote reference.[^1]", ...paragraphs, "Final repeated reference.[^1]", "[^1]: The footnote text.", "[^other]: The second footnote text."].join("\n\n");
  const project = await t3.project("footnotes", { "footnotes.md": markdown });
  const thread = await t3.thread({ project, title: "Footnote preview", messages: ['See :codex-file-citation{path="footnotes.md"}'] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent See/).tap();
  await screen.getByRole("link", /^footnotes\.md/).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByText("A footnote reference.", { exact: false }).waitFor();
  await app.screenshot("opening-reference");
  const visibleText = (selector: string) => browser.evaluate((query) => {
    const element = document.querySelector<HTMLElement>(query);
    if (!element) return null;
    const range = document.createRange();
    range.selectNodeContents(element);
    const rect = range.getBoundingClientRect();
    return rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.bottom <= innerHeight ? element.textContent : null;
  }, selector);
  const click = (selector: string) => browser.evaluate((query) => {
    document.querySelector<HTMLElement>(query)?.click();
  }, selector);
  const first = 'a[id="user-content-user-content-fnref-1"]';
  const second = 'a[id="user-content-user-content-fnref-2"]';
  await expect.poll(() => visibleText(first)).toBe("1");
  await click(first);
  await expect(screen.getByText("The footnote text.", { exact: false })).toBeVisible();
  await app.screenshot("trailing-footnotes");
  await expect.poll(() => browser.evaluate(() => document.querySelectorAll("section[data-footnotes]").length)).toBe(1);
  await click('a[aria-label="Back to reference 1"]');
  await expect.poll(() => visibleText(first)).toBe("1");
  await app.screenshot("back-to-opening");
  await click(first);
  await expect(screen.getByText("The footnote text.", { exact: false })).toBeVisible();
  await click('a[aria-label="Back to reference 1-2"]');
  await expect.poll(() => visibleText(second)).toBe("2");
  await app.screenshot("repeated-reference-numbering");
  await click(second);
  await expect(screen.getByText("The second footnote text.", { exact: false })).toBeVisible();
  await click('a[aria-label="Back to reference 2"]');
  await expect.poll(() => visibleText(second)).toBe("2");
});
