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

test("Chunked Markdown resolves a reference after a one-space-indented fence", WEB, async ({ t3, app, browser, screen }) => {
  const document = (indent: string) => "Read [guide]. " + "filler ".repeat(600) + "\n\n# Notes\n\n" + indent + "```sh\n echo x\n" + indent + "```\n[guide]: https://example.com/guide\n";
  const project = await t3.project("proj", { "indented.md": document(" "), "control.md": document("") });
  const thread = await t3.thread({ project, title: "Markdown preview", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const open = async (path: string, toggle = false) => {
    await browser.evaluate((path) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
        if (row) { row.click(); return; }
      }
      throw new Error("File tree row missing: " + path);
    }, path);
    await screen.getByRole("region", "Workspace panel: " + path).waitFor();
    if (toggle) await screen.getByRole("button", "Show rendered markdown").tap();
    await screen.getByRole("button", "Show markdown source").waitFor();
    await screen.getByText("Read", { exact: false }).last().waitFor();
  };
  await screen.getByRole("button", "Refresh workspace files").waitFor();
  await open("control.md", true);
  await screen.getByRole("link", "guide", { exact: true }).waitFor();
  await app.screenshot("control-reference");
  await open("indented.md");
  await app.screenshot("indented-reference");
  await expect(screen.getByRole("link", "guide", { exact: true })).toHaveAttribute("href", "https://example.com/guide");
});
