/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

test("Files opens and saves a 521-character workspace-relative path", WEB, async ({ t3, app, browser, screen }) => {
  const relativePath = `${"a".repeat(200)}/${"b".repeat(200)}/${"c".repeat(110)}/demo.txt`;
  const project = await t3.project("demo-project", { [relativePath]: "readable", "short.txt": "short ok" });
  const thread = await t3.thread({ project, title: "Deep workspace file", messages: ["Start"] });
  // Hide the machine-local workspace root in public captures.
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = 'p.text-muted-foreground code.break-all { font-size: 0 !important; } p.text-muted-foreground code.break-all::after { content: "demo-project"; font-size: 12px; }';
      document.head.append(style);
    });
  });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "short.txt", { exact: false }).tap();
  await screen.getByText("short ok", { exact: true }).waitFor();
  await screen.getByRole("button", "Expand all folders").tap();
  await screen.getByRole("treeitem", "demo.txt", { exact: false }).tap();
  try {
    await expect(screen.getByText("readable", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("deep-file-open");
  }
  const editor = browser.locator('diffs-container [data-content][contenteditable="true"]');
  await editor.waitFor();
  await editor.tap();
  await browser.keyboard.press("Control+End");
  await browser.keyboard.type(" and saved");
  await expect.poll(() => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readFileString(`${project}/${relativePath}`)))).toBe("readable and saved");
  await app.screenshot("deep-file-saved");
  await t3.open(thread);
  await expect(screen.getByText("readable and saved", { exact: true })).toBeVisible();
  await app.screenshot("deep-file-reopened");
});
