import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Terminal selection keeps focus and opens actions only on right-click", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("terminal-demo", { "selection-demo.sh": "printf '\\033[2J\\033[H'\nprintf 'TERMINAL_SELECTION_COPY_CHECK\\n'\nPS1='$ ' bash --noprofile --norc\n" });
  await t3.thread({ project, title: "Terminal selection", messages: ["Ready"] });
  await t3.open();
  await screen.getByRole("button", "Terminal selection, Done, terminal-demo", { exact: true }).tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1500)));
  await input.press("Control+u");
  await browser.keyboard.type("bash selection-demo.sh");
  await browser.keyboard.press("Enter");
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
  await app.screenshot("terminal-ready");
  const canvas = browser.locator("canvas").last();
  const bounds = (await canvas.boundingBox())!;
  await browser.mouse.move(bounds.x + 4, bounds.y + 12);
  await browser.mouse.down();
  for (let x = 14; x <= 231; x += 7) await browser.mouse.move(bounds.x + x, bounds.y + 12);
  await browser.mouse.up();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
  await app.screenshot("left-selection-released");
  const automaticMenu = await screen.getByRole("menuitem", "Copy", { exact: true }).isVisible();
  const terminalFocused = await browser.evaluate(() => document.activeElement?.getAttribute("aria-label") === "Terminal input");
  await browser.keyboard.press("Control+c");
  await screen.getByTestId("composer-editor").tap();
  await browser.keyboard.press("Control+v");
  await app.screenshot("ctrl-c-pasted-into-composer");
  await browser.keyboard.press("Escape");
  await browser.mouse.move(bounds.x + 4, bounds.y + 12);
  await browser.mouse.down();
  for (let x = 14; x <= 231; x += 7) await browser.mouse.move(bounds.x + x, bounds.y + 12);
  await browser.mouse.up();
  await browser.keyboard.press("Escape");
  await canvas.secondaryTap();
  await app.screenshot("explicit-right-click");
  expect(automaticMenu).toBe(false);
  expect(terminalFocused).toBe(true);
  await expect(screen.getByRole("menuitem", "Copy", { exact: true })).toBeEnabled();
  await expect(screen.getByRole("menuitem", "Add to chat", { exact: true })).toBeEnabled();
});
