/// <reference lib="dom" />
import { expect } from "e2e";
import { mkdir, writeFile, readFile, access } from "node:fs/promises";
import { homedir } from "node:os";
import { test, WEB } from "./t3.ts";

const REL = "~\\.proof38510-3/NOTES.md";
const HOMEFILE = `${homedir()}/.proof38510-3/NOTES.md`;
const exists = async (p: string) => access(p).then(() => true, () => false);

test("Home backslash mentions are read-only and folder paste retains browsing", WEB, async ({ t3, app, screen, browser }) => {
  await mkdir(`${homedir()}/.proof38510-3`, { recursive: true });
  await writeFile(HOMEFILE, "# Notes\n");
  const project = await t3.project("server", {
    "verify.sh": `#!/bin/bash\nclear\nprintf 'DISK CHECK AFTER EDIT + CTRL-S\\n\\nHome file: '\ncat "$HOME/.proof38510-3/NOTES.md"\nprintf '\\nProject-local copy: '\nif test -f '~\\.proof38510-3/NOTES.md'; then cat '~\\.proof38510-3/NOTES.md'; else printf 'ABSENT (correct)\\n'; fi\nprintf '\\n'\ntouch verified.done\n`,
  });
  const thread = await t3.thread({ project, title: "Home file preview", messages: ["Ready for file preview"] });
  await t3.open(thread);
  const paste = async (text: string) => {
    await browser.evaluate(async (text) => navigator.clipboard.writeText(text), text);
    await browser.keyboard.press("ControlOrMeta+V");
  };
  await screen.getByRole("textbox").tap();
  await paste(`@${REL} `);
  await screen.getByRole("button", `Preview ${REL}`).tap();
  const content = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent;
    }
    return document.body.textContent;
  });
  // Wait for the actual file read before capturing.
  await expect.poll(content).toContain("# Notes");
  await app.screenshot("home-file-opened");
  const crumbs = await browser.evaluate(() => [...document.querySelectorAll("[data-file-crumb]")].map(e => e.textContent?.trim()));
  const point = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const e = host.shadowRoot?.querySelector("[data-content]");
      if (e) { const r = e.getBoundingClientRect(); return {x:r.x+30,y:r.y+10}; }
    }
    return null;
  });
  if (!point) throw new Error("File content has not mounted");
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down(); await browser.mouse.up();
  await browser.keyboard.press("Home");
  await browser.keyboard.type("Edited in preview ");
  await browser.keyboard.press("ControlOrMeta+s");
  if (crumbs[0] === "server") await expect.poll(() => exists(`${project}/${REL}`)).toBe(true);
  await app.screenshot("after-edit-and-save");
  // Let the real terminal display the files on disk, rather than hiding the copy in an assertion.
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await expect(terminal).toHaveAttribute("data-workspace-focus-default", "");
  await terminal.focus();
  await browser.keyboard.type("PS1='$ '; clear; bash verify.sh\n");
  await expect.poll(() => exists(`${project}/verified.done`)).toBe(true);
  await app.screenshot("disk-check-after-save");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByRole("button", "Add project").tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  const field = screen.getByRole("combobox");
  await field.fill("~/");
  await browser.keyboard.press("End");
  await paste("~\\.proof38510-3/");
  await screen.getByRole("button", /Create & Add/).waitFor();
  await app.screenshot("folder-field-paste");
  const folderValue = await browser.evaluate(() => (document.activeElement as HTMLInputElement)?.value);
  const copy = await exists(`${project}/${REL}`);
  expect({ crumbs, copy, home: await readFile(HOMEFILE, "utf8"), folderValue }).toEqual({
    crumbs: ["~", ".proof38510-3", "NOTES.md"], copy: false, home: "# Notes\n", folderValue: "~/~\\.proof38510-3/",
  });
});
