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

test("Terminal URLs exclude nested closing wrappers and preserve balanced parentheses", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("url-proof", {
    "print.sh": "printf '\\033[2J\\033[H'; for i in $(seq 1 100); do printf '%s\\n' \"$1\"; done; touch printed\n",
  });
  const thread = await t3.thread({ project, title: "Terminal URL punctuation", messages: ["hello"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await browser.evaluate(() => {
    (window as any).openedTargets = [];
    window.open = ((url: string) => {
      (window as any).openedTargets.push(String(url));
      let panel = document.getElementById("activation-proof");
      if (!panel) {
        panel = document.createElement("pre"); panel.id = "activation-proof";
        panel.style.cssText = "position:fixed;top:70px;right:20px;z-index:99999;background:#17202c;color:white;padding:20px;font:16px monospace;border:2px solid #8ab4f8";
        document.body.append(panel);
      }
      panel.textContent = "Actual window.open targets:\n" + (window as any).openedTargets.join("\n");
      return null;
    }) as typeof window.open;
  });
  const cases = ["[(https://example.com/path)]", "[(https://example.com/wiki/Dune_(2021))]"];
  for (const [index, line] of cases.entries()) {
    await unlink(`${project}/printed`).catch(() => {});
    await input.focus();
    await browser.keyboard.type(`bash print.sh '${line}'\n`);
    await expect.poll(async () => readFile(`${project}/printed`, "utf8").then(() => true, () => false), { timeout: 30000 }).toBe(true);
    const canvas = await browser.evaluate(() => {
      const b = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
      return b ? { x:b.x,y:b.y,width:b.width,height:b.height } : null;
    });
    if (!canvas) throw new Error("No terminal canvas");
    await browser.mouse.move(canvas.x + 65, canvas.y + canvas.height / 2 - index * 40);
    await browser.keyboard.down("Control");
    await browser.mouse.down(); await browser.mouse.up();
    await browser.keyboard.up("Control");
    await expect.poll(() => browser.evaluate(() => (window as any).openedTargets.length)).toBe(index+1);
    await app.screenshot(`url-${index}-activation`);
  }
  expect(await browser.evaluate(() => (window as any).openedTargets)).toEqual(["https://example.com/path", "https://example.com/wiki/Dune_(2021)"]);
});
