/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

test(
  "Opening a diff file from its context menu keeps its leading space",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const file = " notes.txt";
    const editorArgs = `${T3_HOME}/editor-args.txt`;
    const project = await t3.project("demo", {
      [file]: "Notes being edited\n",
      "notes.txt": "A different file\n",
    });
    const thread = await t3.thread({
      project,
      title: "Open the changed notes",
      messages: ["first"],
    });
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        yield* fs.remove(editorArgs, { force: true });
        yield* fs.writeFileString(`${project}/${file}`, "New notes\n");
      }),
    );

    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByText("Diff", { exact: true }).tap();
    const title = browser.locator("[data-title]").filter({ hasText: "notes.txt" });
    await title.waitFor();
    await browser.evaluate((file) => {
      const title = Array.from(document.querySelectorAll("diffs-container"), (host) =>
        host.shadowRoot?.querySelector("[data-title]"),
      ).find((element) => element?.textContent === file);
      if (!title) throw new Error("The diff filename did not render");
      const bounds = title.getBoundingClientRect();
      title.dispatchEvent(
        new MouseEvent("contextmenu", {
          bubbles: true,
          cancelable: true,
          composed: true,
          button: 2,
          clientX: bounds.x + bounds.width / 2,
          clientY: bounds.y + bounds.height / 2,
        }),
      );
      return null;
    }, file);
    await screen.getByRole("menuitem", "Open with", { exact: true }).hover();
    await app.screenshot("open-with-on-diff-file");
    // The real-editor driver publishes arguments only after reading the live process.
    // The server also probes it with `--version`; wait for the launch that opens a file.
    const watching = Promise.withResolvers<void>();
    const openedPath = runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        return yield* fs.watch(T3_HOME, { onReady: watching.resolve }).pipe(
          Stream.filter((event) => event._tag === "Create" && event.path === "editor-args.txt"),
          Stream.mapEffect(() => fs.readFileString(editorArgs)),
          Stream.map((args) => args.split("\n").at(-2)),
          Stream.filter((opened) => opened?.startsWith(`${project}/`) === true),
          Stream.runHead,
        );
      }),
    );
    await watching.promise;
    await screen.getByRole("menuitem", "Cursor", { exact: true }).tap();

    expect(Option.getOrUndefined(await openedPath)).toBe(`${project}/${file}`);
  },
);
