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

test("Files panel opens a file whose name ends in a space", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("proj", { "notes ": "TRAILING SPACE FILE CONTENT\n", "README.md": "File path reproduction\n" });
  const thread = await t3.thread({ project, title: "Trailing space file", model: "default", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files").tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const rows = host.shadowRoot?.querySelectorAll<HTMLElement>("[data-item-path]");
      for (const row of rows ?? []) {
        if (row.dataset.itemPath?.startsWith("notes")) { row.click(); return true; }
      }
    }
    return false;
  })).toBe(true);
  const preview = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content?.textContent) return content.textContent;
    }
    if (document.body.textContent?.includes("The file could not be accessed or read")) return "FILE ACCESS ERROR";
    return null;
  });
  await expect.poll(preview).not.toBeNull();
  await app.screenshot("opened-trailing-space-file");
  expect(await preview()).toContain("TRAILING SPACE FILE CONTENT");
});
