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

test("GitHub fragment links scroll to Unicode headings in a rendered file", WEB, async ({ t3, app, screen, browser }) => {
  const headings = ["Plain heading", "Area of r²", "Step ①", "می‌خواهم"];
  const filler = "A filler paragraph.\n\n".repeat(22);
  const markdown = "# Anchors\n\n[Plain](#plain-heading) · [Area](#area-of-r) · [Step](#step-) · [Persian](#می‌خواهم)\n\n" + headings.map(h => filler + "## " + h + "\n\n").join("") + filler;
  const project = await t3.project("Anchor demo", { "anchors.md": markdown });
  const thread = await t3.thread({ project, title: "GitHub heading anchors", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "anchors.md").tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("heading", "Anchors", { exact: true }).waitFor();
  const originalUrl = await browser.evaluate(() => location.href);
  await app.screenshot("anchors-before-clicks");
  const results = [];
  for (const [index, link] of ["Plain", "Area", "Step", "Persian"].entries()) {
    await browser.evaluate(() => {
      let node = Array.from(document.querySelectorAll("h1")).find(h => h.textContent === "Anchors")?.parentElement;
      while (node) { if (node.scrollHeight > node.clientHeight && /auto|scroll/.test(getComputedStyle(node).overflowY)) node.scrollTop = 0; node = node.parentElement; }
    });
    await screen.getByRole("link", link, { exact: true }).tap();
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 650)));
    const result = await browser.evaluate((heading) => {
      const node = Array.from(document.querySelectorAll("h2")).find(h => h.textContent === heading)!;
      let parent = node.parentElement;
      while (parent && !(parent.scrollHeight > parent.clientHeight && /auto|scroll/.test(getComputedStyle(parent).overflowY))) parent = parent.parentElement;
      return { heading, id: node.id, offset: node.getBoundingClientRect().top - (parent?.getBoundingClientRect().top ?? 0), url: location.href };
    }, headings[index]);
    results.push(result);
    await app.screenshot(`clicked-${link.toLowerCase()}`);
  }
  console.log(JSON.stringify(results));
  expect(results.map(r => ({ heading: r.heading, scrolledToHeading: r.offset >= -5 && r.offset < 120, stayedInThread: r.url === originalUrl }))).toEqual(headings.map(heading => ({ heading, scrolledToHeading: true, stayedInThread: true })));
});
