/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Identically named new project actions keep separate shortcuts", WEB, async ({ t3, app, browser, screen }) => {
  const a = await t3.project("Project A");
  const b = await t3.project("Project B");
  const threadA = await t3.thread({ project: a, title: "Project A action", messages: ["Start"] });
  const threadB = await t3.thread({ project: b, title: "Project B action", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  for (const [thread, key, command] of [[threadA, "ControlOrMeta+Shift+t", "echo a"], [threadB, "ControlOrMeta+Shift+y", "echo b"]] as const) {
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await screen.getByRole("button", "Add project script", { exact: true }).tap();
    await browser.locator("#script-name").fill("Test");
    await browser.locator("#script-keybinding").press(key);
    await browser.locator("#script-command").fill(command);
    await screen.getByRole("button", "Save action", { exact: true }).tap();
    await screen.getByRole("button", "Run Test", { exact: true }).waitFor();
  }
  await screen.getByRole("button", "Script actions", { exact: true }).tap();
  await app.screenshot("project-b-shortcut");
  await t3.open(threadA);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await screen.getByRole("button", "Script actions", { exact: true }).tap();
  await app.screenshot("project-a-shortcut-after-adding-project-b");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("ControlOrMeta+Shift+t");
  const terminal = screen.getByLabel("Terminal input");
  const terminalText = async () => {
    const exists = await browser.evaluate(() => !!document.querySelector('textarea[aria-label="Terminal input"]'));
    if (!exists) return "";
    await browser.evaluate(() => {
      delete document.body.dataset.terminalCopy;
      window.addEventListener("copy", event => {
        document.body.dataset.terminalCopy = event.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 ?? "");
  };
  try {
    await expect.poll(terminalText, { timeout: 5000 }).toContain("echo a");
  } finally {
    await app.screenshot("project-a-original-shortcut-runs-command");
  }
  await screen.getByRole("button", "Script actions", { exact: true }).tap();
  await expect(screen.getByRole("menuitem", /Test.*Ctrl\+Shift\+T/)).toBeVisible();
});
