import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

test("Option arrows stay in vim insert mode and retain shell navigation", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("terminal-demo");
  await t3.thread({ project, title: "Terminal arrow navigation", messages: ["Ready"] });
  await t3.open();
  await screen.getByRole("button", "Terminal arrow navigation, Done, terminal-demo").tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByRole("textbox", "Terminal input").focus();
  const settle = () => browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 700)));
  await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 2000)));
  for (const direction of ["Left", "Right"]) {
    await browser.keyboard.type(`export PS1='$ '; clear; vim --clean ${direction}.txt`);
    await browser.keyboard.press("Enter");
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1500)));
    await browser.keyboard.press("i");
    await browser.keyboard.type("one two three");
    await browser.keyboard.press(`Alt+Arrow${direction}`);
    await browser.keyboard.type("X");
    await settle();
    await app.screenshot(`vim-option-${direction}-X`);
    await browser.keyboard.press("Escape");
    await browser.keyboard.type(":wq");
    await browser.keyboard.press("Enter");
    await settle();
    await browser.keyboard.type("one two three");
    if (direction === "Right") await browser.keyboard.press("Control+a");
    await browser.keyboard.press(`Alt+Arrow${direction}`);
    await browser.keyboard.type("X");
    await settle();
    await app.screenshot(`shell-option-${direction}-X`);
    await browser.keyboard.press("Control+c");
    await settle();
  }
  await expect.poll(async () => Promise.all(["Left", "Right"].map(async direction =>
    (await readFile(`${project}/${direction}.txt`, "utf8")).includes("X")
  ))).toEqual([true, true]);
});
