/// <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("Successful autosaves clear earlier errors across editor sessions and later failures reappear", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "notes.txt": "Original notes" });
  const thread = await t3.thread({ project, title: "Edit notes", messages: ["Start"] });
  const chmod = (mode: number) => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.chmod(`${project}/notes.txt`, mode)));
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    // Preserve the complete toast, anonymizing only its generated local workspace path.
    new MutationObserver(() => {
      for (const description of document.querySelectorAll('[data-slot="toast-description"]')) {
        for (const node of description.childNodes) {
          if (node.nodeType === Node.TEXT_NODE && node.textContent?.includes("/home/"))
            node.textContent = node.textContent.replace(/in '[^']*'/, "in 'demo'");
        }
      }
    }).observe(document, {subtree:true, childList:true, characterData:true});
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const message of [JSON.parse(data)].flat()) {
        if (message._tag !== "Request" || message.tag !== "projects.writeFile") continue;
        const onReply = (event: MessageEvent) => {
          if (typeof event.data !== "string") return;
          for (const reply of [JSON.parse(event.data)].flat()) {
            if (reply._tag !== "Exit" || String(reply.requestId) !== String(message.id)) continue;
            document.documentElement.dataset.writeResult = `${message.payload.contents}:${reply.exit._tag}`;
            this.removeEventListener("message", onReply);
          }
        };
        this.addEventListener("message", onReply);
      }
      return send.call(this, data);
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "Fork from this response", { exact: true }).waitFor({state:"attached"});
  const open = async () => {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("notes.txt");
    await screen.getByRole("option", "notes.txt", {exact:false}).tap();
    await browser.locator("diffs-container").waitFor({state:"attached"});
  };
  const edit = async (text: string) => {
    await browser.evaluate(() => {
      document.querySelector("diffs-container")?.shadowRoot?.querySelector<HTMLElement>('[data-content][contenteditable="true"]')?.focus();
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+a");
    await browser.keyboard.type(text);
  };
  const result = (n: string, state: string) => browser.locator(`html[data-write-result="${n}:${state}"]`).waitFor({state:"attached"});
  const error = screen.getByText("Could not save file", {exact:true});
  const visible = () => error.isVisible();
  const capture = async (label: string) => {
    // Let the toast's enter/exit transition finish before recording its visible state.
    await browser.evaluate(async () => {
      await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      await Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot(label);
  };
  await open();
  await chmod(0o444);
  await edit("Draft A1");
  await result("Draft A1","Failure");
  await error.waitFor({state:"visible"});
  await capture("01-first-failed-autosave");
  await chmod(0o644);
  await edit("Draft A2");
  await result("Draft A2","Success");
  await capture("02-same-session-success");
  const sameSessionCleared = !(await visible());
  // Dismiss the first error explicitly so both sides start the cross-session case alike.
  if (await visible()) await screen.getByRole("button", "Dismiss notification", {exact:true}).tap();
  await chmod(0o444);
  await edit("Draft B1");
  await result("Draft B1","Failure");
  await error.waitFor({state:"visible"});
  await capture("03-error-before-close");
  await screen.getByRole("button", "Close notes.txt", {exact:true}).tap();
  await capture("04-editor-closed-error-visible");
  await chmod(0o644);
  await open();
  // Make a new edit in the reopened editor while the old toast is still visible.
  await edit("Draft B2");
  await result("Draft B2","Success");
  await capture("05-reopened-editor-success");
  const reopenedCleared = !(await visible());
  if (await visible()) await screen.getByRole("button", "Dismiss notification", {exact:true}).tap();
  await chmod(0o444);
  await edit("Draft C1");
  await result("Draft C1","Failure");
  await error.waitFor({state:"visible"});
  await capture("06-subsequent-failure");
  const subsequentFailureVisible = await visible();
  await chmod(0o644);
  expect({sameSessionCleared, reopenedCleared, subsequentFailureVisible}).toEqual({sameSessionCleared:true, reopenedCleared:true, subsequentFailureVisible:true});
});
