import { expect } from "e2e";
import { chromium } from "playwright-core";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("Middle click pastes only inside the composer", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("scratch");
  const thread = await t3.thread({project, title: "Middle click demonstration", messages: ["Show a short example"], model: "multi-turn"});
  await t3.open(thread);
  const connection = await chromium.connectOverCDP("http://127.0.0.1:9181");
  const page = connection.contexts().flatMap(c => c.pages()).find(p => p.url().includes(thread.threadId))!;
  await page.bringToFront();
  const composer = screen.getByRole("textbox");
  const results: Record<string,string> = {};
  const prepare = async () => {
    await composer.fill("sentinel");
    await page.getByRole("textbox").press("End");
    // Real X11 PRIMARY, not a synthetic paste event or browser clipboard API.
    execFileSync("xclip", ["-selection", "primary"], {input:"PASTED", stdio:["pipe", "ignore", "ignore"], env:{...process.env, DISPLAY:":181"}});
    await page.waitForTimeout(500);
  };
  const clickAndCapture = async (label:string, point:{x:number,y:number}) => {
    await page.mouse.move(point.x, point.y);
    await page.mouse.down({button:"middle"});
    await page.waitForTimeout(200);
    await page.mouse.up({button:"middle"});
    await page.waitForTimeout(700);
    await app.screenshot(label);
    results[label] = (await page.getByRole("textbox").innerText()).trim();
  };
  const blankPoint = () => browser.evaluate(() => {
    const column = document.querySelector("[data-chat-column]")!.getBoundingClientRect();
    const editor = document.querySelector('[role="textbox"]')!.getBoundingClientRect();
    return {x:column.right-35, y:editor.top-90};
  });
  await prepare();
  await app.screenshot("ready-before-middle-click");
  await clickAndCapture("populated-timeline-blank-space", await blankPoint());

  await prepare();
  const message = await page.getByText("first fixture turn complete", {exact:true}).boundingBox();
  await clickAndCapture("rendered-message-text", {x:message!.x+60, y:message!.y+message!.height/2});

  await prepare();
  const editor = await page.getByRole("textbox").boundingBox();
  await clickAndCapture("inside-composer-native-paste", {x:editor!.x+140, y:editor!.y+20});

  await page.getByRole("button", {name:"New thread", exact:true}).click({modifiers:["Shift"]});
  await prepare();
  await clickAndCapture("empty-draft-blank-space", await blankPoint());

  await expect(results).toEqual({
    "populated-timeline-blank-space":"sentinel",
    "rendered-message-text":"sentinel",
    "inside-composer-native-paste":"sentinelPASTED",
    "empty-draft-blank-space":"sentinel",
  });
  await connection.close();
});
