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

test("Long Markdown keeps NBSP footnote citations linked", WEB, async ({ t3, app, browser, screen }) => {
  const label = "a\u00a0b";
  const document = (id: string) => `# First\n\nFirst[^${id}] near the beginning.\n\n${"Lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(92)}\n\n# Second\n\nAgain[^${id}]\n\n[^${id}]: Shared note.\n`;
  const project = await t3.project("footnotes", { "notes.md": document(label), "control.md": document("ab") });
  const thread = await t3.thread({ project, title: "Footnote rendering", messages: ['See :codex-file-citation{path="notes.md"} and :codex-file-citation{path="control.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", "First", { exact: true }).waitFor();
  await app.screenshot("nbsp-first-citation");
  const counts = await browser.evaluate(() => ({ refs: document.querySelectorAll('[data-footnote-ref]').length, backrefs: document.querySelectorAll('[data-footnote-backref]').length }));
  await browser.evaluate(() => { [...document.querySelectorAll('h1')].find(h => h.textContent === 'Second')?.scrollIntoView(); return null; });
  await app.screenshot("nbsp-footnote-and-backlinks");
  await browser.evaluate(() => { document.querySelector<HTMLElement>('[data-footnote-backref]')?.click(); return null; });
  await app.screenshot("nbsp-backlink-destination");
  await screen.getByRole("link", /^control\.md/).tap();
  await screen.getByRole("heading", "First", { exact: true }).waitFor();
  await app.screenshot("plain-label-control");
  expect(counts, "Both citations and both backlinks are rendered").toEqual({ refs: 2, backrefs: 2 });
});
