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

test("Different selections on the same terminal row are both kept", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1200, height: 850 });
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("terminal-excerpts");
  const thread = await t3.thread({ project, title: "Terminal selections", model: "default", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await input.focus();
    await browser.keyboard.type("echo ready > shell-ready\n");
    return readFile(`${project}/shell-ready`, "utf8").catch(() => "");
  }, { timeout: 30000 }).toBe("ready\n");
  await input.focus();
  await browser.keyboard.type('PS1=""; clear; echo "error: foo   hint: bar"; touch output-ready\n');
  await expect.poll(() => readFile(`${project}/output-ready`, "utf8").then(() => true).catch(() => false)).toBe(true);
  const select = async (column: number, label: string) => {
    const point = await browser.evaluate((column) => {
      const canvas = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
      const box = canvas.getBoundingClientRect();
      const ctx = canvas.getContext("2d")!;
      return { x: box.x + 4 + ctx.measureText("M").width * column, y: box.y + 12 };
    }, column);
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down(); await browser.mouse.up();
    await browser.mouse.down(); await browser.mouse.up();
    await app.screenshot(label);
    await browser.evaluate(({x,y}) => {
      const canvas = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
      canvas.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 2 }));
    }, point);
    await screen.getByRole("menuitem", "Add to chat").tap();
  };
  await select(8.5, "selected-foo");
  await app.screenshot("first-excerpt-added");
  await select(19.5, "selected-bar");
  await app.screenshot("different-text-same-row");
  const count = () => browser.evaluate(() => document.querySelectorAll('[aria-label^="Terminal excerpt,"]').length);
  expect(await count()).toBe(2);
  await select(8.5, "selected-foo-again");
  await app.screenshot("identical-text-deduplicates");
  expect(await count()).toBe(2);
});
