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

const sections = Array.from({ length: 60 }, (_, i) => `## Section ${i + 1}\n\nRead [the guide][guide] before step ${i + 1}. ${"This section describes the steps carefully so readers can follow the guide and complete their work. ".repeat(4)}\n\n`).join("");
const guide = (closer: string) => `---\ntitle: x\n${closer}\n[guide]: https://example.com/guide\n\n${sections}`;

test("Reference links after frontmatter resolve beyond the first preview chunk", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("markdown-demo", {"GUIDE.md": guide("..."), "GUIDE-dashes.md": guide("---")});
  const thread = await t3.thread({project, title: "Review guide", messages: ["Start"]});
  await browser.setViewport({width: 1440, height: 1000});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact: false}).waitFor();
  for (const file of ["GUIDE-dashes.md", "GUIDE.md"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, {exact: false}).tap();
    const toggle = screen.getByRole("button", "Show rendered markdown", {exact: true});
    await toggle.tap();
    await screen.getByRole("heading", "Section 1", {exact: true}).waitFor();
    if (file === "GUIDE-dashes.md") await screen.getByRole("button", "Hide file explorer", {exact: true}).tap();
    for (let step = 0; step < 60; step++) {
      if (await screen.getByRole("heading", "Section 20", {exact: true}).count()) break;
      await browser.evaluate(async () => {
        const viewport = document.querySelector(".chat-markdown h2")?.closest(".scrollbar-gutter-both") ?? [...document.querySelectorAll("h2")].find(el => el.textContent?.startsWith("Section "))?.closest(".scrollbar-gutter-both");
        if (!viewport) throw new Error("Markdown scroll viewport missing");
        viewport.scrollTop += 600;
        await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      });
    }
    await screen.getByRole("heading", "Section 20", {exact: true}).waitFor();
    await browser.evaluate(() => {
      const heading = [...document.querySelectorAll("h2")].find(el => el.textContent === "Section 20");
      heading?.scrollIntoView({block: "start"});
    });
    await app.screenshot(file === "GUIDE.md" ? "dots-section-20" : "dashes-control-section-20");
    await expect.poll(() => browser.evaluate(() => {
      const heading = [...document.querySelectorAll("h2")].find(el => el.textContent === "Section 20");
      return heading?.nextElementSibling?.querySelector("a")?.getAttribute("href") ?? null;
    })).toBe("https://example.com/guide");
    await screen.getByRole("button", "Show markdown source", {exact: true}).tap();
  }
});
