/// <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("Option arrows stay in vim insert mode on macOS", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "light", reducedMotion: "reduce" });
  const capture = async (label: string) => {
    let previous = "";
    await expect.poll(async () => {
      const pixels = await browser.evaluate(() => {
        const input = document.querySelector('[aria-label="Terminal input"]');
        const canvas = input?.parentElement?.querySelector("canvas");
        if (!canvas) throw new Error("Terminal canvas is missing");
        return canvas.toDataURL();
      });
      const settled = pixels === previous;
      previous = pixels;
      return settled;
    }, { interval: 500 }).toBe(true);
    await app.screenshot(label);
  };
  const project = await t3.project("terminal-demo", { "arrow-probe.mjs": String.raw`
import { writeFileSync } from "node:fs";
const keys = [];
process.stdin.setRawMode(true);
process.stdout.write("\x1b[?1049h\x1b[2J\x1b[HAlternate-screen keyboard input\r\n");
process.stdin.on("data", chunk => {
  if (chunk.toString() === "q") {
    process.stdout.write("\x1b[?1049l");
    process.stdin.setRawMode(false);
    process.exit(0);
  }
  const hex = [...chunk].map(byte => byte.toString(16).padStart(2, "0")).join(" ");
  keys.push(hex);
  writeFileSync("arrow-bytes.json", JSON.stringify(keys));
  process.stdout.write(hex + "\r\n");
});
writeFileSync("probe-ready", "ready");
` });
  const thread = await t3.thread({ project, title: "Option arrows in vim", messages: ["hello"] });
  const read = (file: string) => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${project}/${file}`);
  }).pipe(Effect.orElseSucceed(() => "")));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return read("shell-ready");
  }, { timeout: 30000 }).toBe("ready\n");
  await terminal.focus();
  await browser.keyboard.type(`export PS1='$ '; clear; vim --clean -c 'call writefile(["ready"], "vim-ready")' result.txt`);
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("vim-ready")).toBe("ready\n");
  await browser.keyboard.type("ione two three");
  await capture("vim-insert-before-option");
  await browser.keyboard.press("Alt+ArrowLeft");
  await capture("after-option-left");
  await browser.keyboard.type("X");
  await capture("option-left-then-X-in-vim");
  await browser.keyboard.press("Escape");
  await browser.keyboard.type(":wq!");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("result.txt")).not.toBe("");
  await browser.keyboard.type(`vim --clean -c 'call writefile(["ready"], "vim-ready-2")' result.txt`);
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("vim-ready-2")).toBe("ready\n");
  await browser.keyboard.type("A");
  await capture("vim-before-cmd-arrows");
  await browser.keyboard.press("Meta+ArrowLeft");
  await browser.keyboard.press("Meta+ArrowRight");
  await browser.keyboard.type("Z");
  await capture("cmd-arrows-in-vim");
  await browser.keyboard.press("Escape");
  await browser.keyboard.type(":q!");
  await browser.keyboard.press("Enter");
  await browser.keyboard.type("node arrow-probe.mjs");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("probe-ready")).toBe("ready");
  await capture("alternate-screen-before-keys");
  for (const key of ["Meta+ArrowLeft", "Meta+ArrowRight", "Alt+ArrowLeft", "Alt+ArrowRight"]) {
    await browser.keyboard.press(key);
    await capture(`alternate-screen-${key.replaceAll("+", "-")}`);
  }
  await browser.keyboard.type("q");
  await browser.keyboard.type("bash --noprofile --norc");
  await browser.keyboard.press("Enter");
  await expect.poll(async () => {
    await browser.keyboard.type("echo ready > bash-ready");
    await browser.keyboard.press("Enter");
    return read("bash-ready");
  }).toBe("ready\n");
  await browser.keyboard.type("export PS1='$ '; clear");
  await browser.keyboard.press("Enter");
  await browser.keyboard.type("echo one two three");
  await browser.keyboard.press("Alt+ArrowLeft");
  await browser.keyboard.type("X");
  await browser.keyboard.press("Alt+ArrowRight");
  await browser.keyboard.type("Y");
  await browser.keyboard.press("Meta+ArrowLeft");
  await browser.keyboard.type("printf 'shell navigation: '; ");
  await browser.keyboard.press("Meta+ArrowRight");
  await browser.keyboard.type(" > shell-result");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("shell-result")).toBe("one two XthreeY\n");
  await browser.keyboard.type("cat shell-result");
  await browser.keyboard.press("Enter");
  await capture("shell-word-and-line-navigation");
  await expect.poll(() => read("result.txt")).toBe("one two threXe\n");
  await expect.poll(() => read("arrow-bytes.json")).toBe(JSON.stringify([
    "1b 5b 31 3b 39 44", "1b 5b 31 3b 39 43", "1b 5b 31 3b 33 44", "1b 5b 31 3b 33 43",
  ]));
});
