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

test("Terminal copy with a Russian keyboard layout", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("terminal-copy");
  await t3.thread({ project, title: "Terminal copy", messages: ["Ready"] });
  await t3.open();
  await screen.getByRole("button", "Terminal copy, Done, terminal-copy", { exact: true }).tap();
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.id = "hide-initial-prompt";
    style.textContent = "canvas { visibility: hidden !important }";
    document.head.append(style);
    const state = { painted: [] as string[], output: null as null | { x: number; y: number }, copied: "", commands: [] as string[], sent: [] as string[] };
    (window as any).copyProof = state;
    const paint = CanvasRenderingContext2D.prototype.fillText;
    CanvasRenderingContext2D.prototype.fillText = function(text, x, y, ...rest) {
      state.painted.push(text); if (text.trim() === "SELECTED_OUTPUT") state.output = { x, y };
      return paint.call(this, text, x, y, ...rest);
    };
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string" && data.includes('"tag":"terminal.write"')) state.sent.push(JSON.parse(data).payload.data);
      return send.call(this, data);
    };
    const exec = document.execCommand.bind(document);
    document.execCommand = (command, ...args) => { state.commands.push(command); return exec(command, ...args); };
    document.addEventListener("copy", () => { state.copied = (document.activeElement as HTMLTextAreaElement)?.value ?? ""; }, true);
  });
  await screen.getByRole("button", "Toggle terminal drawer", { exact: true }).tap();
  await browser.evaluate(async () => {
    const state = (window as any).copyProof;
    const until = Date.now() + 15000;
    while (!state.painted.some((text: string) => text.includes("terminal-copy"))) {
      if (Date.now() > until) throw new Error("Shell prompt was not ready");
      await new Promise(resolve => setTimeout(resolve, 50));
    }
  });
  await browser.locator('textarea[aria-label="Terminal input"]').press("Control+u");
  await browser.evaluate(() => {
    const data = new DataTransfer();
    data.setData("text/plain", "PS1='$ '; clear; echo SELECTED_OUTPUT");
    document.querySelector('.t3-ghostty-input')!.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
  });
  await browser.keyboard.press("Enter");
  await browser.evaluate(async () => {
    const state = (window as any).copyProof;
    const until = Date.now() + 15000;
    while (!state.output) {
      if (Date.now() > until) throw new Error("Terminal did not render SELECTED_OUTPUT");
      await new Promise(resolve => setTimeout(resolve, 50));
    }
    document.getElementById("hide-initial-prompt")!.remove();
  });
  const point = await browser.evaluate(() => {
    const canvas = document.querySelector('.t3-ghostty-input')!.parentElement!.querySelector('canvas')!;
    const rect = canvas.getBoundingClientRect();
    const output = (window as any).copyProof.output;
    return { x: rect.left + output.x + 25, y: rect.top + output.y - 5 };
  });
  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 browser.evaluate(() => (document.querySelector(".t3-ghostty-input") as HTMLTextAreaElement).focus());
  await app.screenshot("selected-output");
  const result = await browser.evaluate(() => {
    const state = (window as any).copyProof;
    state.sent = []; state.commands = []; state.copied = "";
    const input = document.querySelector('.t3-ghostty-input') as HTMLTextAreaElement;
    input.focus();
    const event = new KeyboardEvent("keydown", { key: "С", code: "KeyC", ctrlKey: true, shiftKey: true, bubbles: true, cancelable: true });
    input.dispatchEvent(event);
    return { copied: state.copied, commands: state.commands, defaultPrevented: event.defaultPrevented, platform: navigator.platform };
  });
  await browser.evaluate(async (result) => {
    await new Promise(resolve => setTimeout(resolve, 700));
    const state = (window as any).copyProof;
    const panel = document.createElement("pre");
    panel.style.cssText = "position:fixed;top:190px;left:300px;z-index:99999;background:#fff;color:#111;border:2px solid #555;padding:16px;font:16px/1.6 monospace";
    panel.textContent = `Keyboard reproduction — ${result.platform}\nCtrl+Shift+C · key С (U+0421) · code KeyC\nCopy command: ${result.commands.join(', ') || 'none'}\nCopy event selection: ${result.copied || '(no copy event)'}\nTerminal input sent: ${state.sent.length ? `YES — ${JSON.stringify(state.sent)}` : 'none'}`;
    document.body.append(panel);
  }, result);
  await app.screenshot("russian-copy-result");
  console.log(JSON.stringify({ ...result, sent: await browser.evaluate(() => (window as any).copyProof.sent) }));
  expect(result.copied).toBe("SELECTED_OUTPUT");
  expect(await browser.evaluate(() => (window as any).copyProof.sent.length)).toBe(0);
});
