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

test("Escaped whitespace footnote back-links return to Second and Third", WEB, async ({ t3, app, browser, screen }) => {
  const padding = Array.from({ length: 150 }, () => "lead ".repeat(10).trim()).join("\n\n");
  const markdown = `# One\n\nFirst[^a\\ b].\n\n${padding}\n\n# Two\n\nSecond[^a\\\tb].\n\n${padding}\n\n# Three\n\nThird[^real].\n\n${padding}\n\n[^a\\ b]: One\n\n[^a\\\tb]: Redundant\n\n[^real]: Real\n`;
  const project = await t3.project("footnotes", { "notes.md": markdown });
  const thread = await t3.thread({ project, title: "Footnote navigation", messages: ['See :codex-file-citation{path="notes.md"}'] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent See/).tap();
  await screen.getByRole("link", /^notes\.md/).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("heading", "One", { exact: true }).waitFor();
  const bottom = async () => {
    await browser.evaluate(() => {
      const scroller = [...document.querySelectorAll<HTMLElement>(".scrollbar-gutter-both")].find(e => e.querySelector("h1, section[data-footnotes]"));
      if (!scroller) throw new Error("Markdown scroller missing");
      scroller.scrollTop = scroller.scrollHeight;
      return null;
    });
    await browser.locator('a[href="#user-content-fnref-1-2"]').waitFor();
    await browser.locator('a[data-footnote-ref]').waitFor({ state: "detached" });
  };
  const visibleReference = (id: string) => browser.evaluate((target) => {
    const e = [...document.querySelectorAll<HTMLElement>("a[data-footnote-ref][id]")].find(node => node.id.replace(/^(user-content-)+/, "") === target.replace(/^(user-content-)+/, ""));
    if (!e) return false;
    const scroller = e.closest(".scrollbar-gutter-both");
    if (!scroller) return false;
    const a = (e.closest("p") ?? e).getBoundingClientRect(), b = scroller.getBoundingClientRect();
    return a.bottom > b.top && a.top < b.bottom;
  }, id);
  await bottom();
  await app.screenshot("footnotes-before-navigation");
  await browser.locator('a[href="#user-content-fnref-1-2"]').tap();
  // A capture after each interaction shows the destination, including the base's no-op.
  await app.screenshot("second-occurrence-destination");
  const second = await visibleReference("user-content-fnref-1-2");
  await bottom();
  await browser.locator('a[href="#user-content-fnref-2"]').tap();
  await app.screenshot("ordinary-note-destination");
  const third = await visibleReference("user-content-fnref-2");
  expect({ second, third }, "Both back-links must bring their actual reference into view").toEqual({ second: true, third: true });
});
