import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

test(
  "A long Markdown preview links a footnote in a numbered list",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const markdown = [
      "See the source[^source].",
      "",
      "Background paragraph. ".repeat(220),
      "",
      "## Sources",
      "",
      "100. Source details",
      "",
      "     [^source]: Numbered source note.",
      "",
    ].join("\n");
    const project = await t3.project("documentation", { "sources.md": markdown });
    const thread = await t3.thread({
      project,
      title: "Source notes",
      messages: ['See :codex-file-citation{path="sources.md"}'],
    });
    await t3.open(thread);

    await screen.getByRole("button", /^Agent See/).tap();
    await screen.getByRole("link", /^sources\.md/).tap();
    await screen.getByRole("button", "Show rendered markdown").tap();
    await screen.getByText("See the source", { exact: false }).waitFor();
    await app.screenshot("numbered-list-footnote");
    await expect(browser.locator("a[data-footnote-ref]")).toHaveCount(1);
    await expect(browser.locator("section[data-footnotes]")).toContainText("Numbered source note.");
    const point = await browser.evaluate(() => {
      const candidates = [...document.querySelectorAll("sup")].map((element) => {
        const range = document.createRange();
        range.selectNodeContents(element);
        const rect = range.getBoundingClientRect();
        return { text: element.textContent, x: rect.x, y: rect.y, width: rect.width, height: rect.height };
      });
      const visible = candidates.find((rect) => rect.text === "1" && rect.x > 740 && rect.y > 80 && rect.y < 160);
      if (!visible) throw new Error(JSON.stringify(candidates));
      return { x: visible.x + visible.width / 2, y: visible.y + visible.height / 2 };
    });
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down();
    await browser.mouse.up();
    await screen.getByText("Numbered source note.", { exact: false }).waitFor();
    await app.screenshot("footnote-destination");
  },
);
