/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("A drawer-conditioned shortcut leaves Ctrl+R with the panel shell", WEB, async ({ t3, app, browser, screen }) => {
  const file = `${T3_HOME}/userdata/keybindings.json`;
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(file, '[{"key":"ctrl+r","command":"terminal.new","when":"terminalOpen"}]')));
  const project = await t3.project("terminal-demo");
  const thread = await t3.thread({ project, title: "Terminal shortcut", messages: ["Start"] });
  await browser.setViewport({width:1440,height:900});
  await t3.open("/settings/keybindings");
  await screen.getByRole("button", "Edit shortcut for Terminal: New: Ctrl+R").waitFor();
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Terminal T", {exact:true}).tap();
  const terminal = screen.getByLabel("Terminal input");
  const text = async () => {
    await browser.evaluate(() => { delete document.body.dataset.terminalCopy; window.addEventListener("copy", e => {document.body.dataset.terminalCopy=e.clipboardData?.getData("text/plain")??"";}, {once:true}); return null; });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.terminalCopy??"");
  };
  await terminal.focus();
  await browser.keyboard.type("bash --norc --noprofile");
  await browser.keyboard.press("Enter");
  await expect.poll(text).toContain("bash-");
  await browser.keyboard.type("PS1='bash$ '; clear");
  await browser.keyboard.press("Enter");
  await browser.keyboard.type("echo history-marker-48791");
  await browser.keyboard.press("Enter");
  await expect.poll(text).toContain("history-marker-48791\n");
  await terminal.focus();
  await browser.keyboard.press("Control+r");
  await browser.keyboard.type("hist");
  const result = await text();
  await app.screenshot("ctrl-r-with-drawer-closed");
  await expect(result).toContain("reverse-i-search");
});
