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

test("Terminal OSC 52 writes the client clipboard", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("clipboard-demo");
  await t3.thread({ project, title: "Terminal clipboard", messages: ["Ready"] });
  await t3.open();
  await screen.getByRole("button", "Terminal clipboard, Done, clipboard-demo").tap({ timeout: 120_000 });
  await screen.getByRole("button", "Toggle terminal drawer", { exact: false }).tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await terminal.focus();
  // The canvas input exists before font loading finishes and attaches its event listeners.
  await browser.evaluate(async () => {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    const input = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Terminal input"]')!;
    input.blur();
    window.focus();
    input.focus();
    return null;
  });
  await browser.evaluate(() => {
    const panel = document.createElement("div");
    panel.id = "clipboard-observation";
    panel.setAttribute("role", "status");
    panel.style.cssText = "position:fixed;top:70px;right:24px;z-index:99999;background:#132338;color:white;border:2px solid #75baff;padding:18px;font:18px monospace;white-space:pre;pointer-events:none";
    panel.textContent = "Client clipboard spy\nWrites: 0\nContent: OLD-CLIPBOARD";
    document.body.append(panel);
    let writes = 0;
    Object.defineProperty(navigator.clipboard, "writeText", { configurable: true, value: async (text: string) => {
      panel.textContent = `Client clipboard spy\nWrites: ${++writes}\nContent: ${text}`;
    }});
    window.focus();
  });
  await browser.keyboard.type("export PS1='> '; printf '\\033[2J\\033[H'");
  await browser.keyboard.press("Enter");
  await browser.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return null; });
  await browser.keyboard.type("printf '\\033]52;c;VDMtT1NDNTItdGVzdA==\\a'; echo OSC-DONE");
  await app.screenshot("osc52-command");
  await browser.keyboard.press("Enter");
  try {
    await expect(screen.getByRole("status").filter({ hasText: "Client clipboard spy" })).toHaveText("Client clipboard spy\nWrites: 1\nContent: T3-OSC52-test");
  } finally {
    await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); return null; });
    await browser.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 500)); return null; });
    await app.screenshot("osc52-stable");
    await browser.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 500)); return null; });
    await app.screenshot("osc52-clipboard");
    await browser.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 500)); return null; });
    await app.screenshot("osc52-final");
  }
});
