/// <reference lib="dom" />
import { mkdtemp, symlink } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A Codex citation opens the literal filename with a trailing space", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo", {
    "draft.md": "WITHOUT trailing space\n",
    "draft.md ": "WITH trailing space\n",
  });
  const evidence = await mkdtemp("/tmp/factory-pr-43768-evidence-1/run-");
  const workspace = `${evidence}/citation-demo`;
  await symlink(project, workspace, "dir");
  const thread = await t3.thread({ project, title: "Literal filename citation", messages: [
    `See :codex-file-citation{path="${workspace}/draft.md "} and the plain one :codex-file-citation{path="${workspace}/draft.md"}.`,
  ] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent See/).tap();
  const citation = screen.getByRole("link", /^draft\.md/).first();
  await citation.waitFor();
  await app.screenshot("citations-rendered");
  await citation.tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return null;
  });
  await expect.poll(editorText).toBeTruthy();
  await app.screenshot("citation-file-opened");
  await expect.poll(editorText).toContain("WITH trailing space");
});
