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

test("Terminal bold bracket URLs open without Markdown closing marks", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width: 1200, height: 800});
  const project = await t3.project("terminal-links");
  const thread = await t3.thread({project, title: "Terminal URL wrappers", messages: ["hello"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByLabel("Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  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 browser.evaluate(() => {
    const opened: string[] = [];
    Object.assign(window, {terminalOpened: opened});
    const panel = document.createElement("pre");
    panel.id = "activation-results";
    panel.style.cssText = "position:fixed;top:65px;right:20px;z-index:99999;background:#18202c;color:#fff;padding:16px;font:14px monospace;border:1px solid #8794ab;pointer-events:none";
    panel.textContent = "Ctrl-click activation addresses:";
    document.body.append(panel);
    window.open = ((url: string | URL | undefined) => {
      opened.push(String(url));
      panel.textContent = "Ctrl-click activation addresses:\n" + opened.map((value, index) => `${index + 1}. ${value}`).join("\n");
      return null;
    }) as typeof window.open;
  });
  await input.focus();
  await browser.keyboard.type("export PS1='$ '; unset PROMPT_COMMAND; printf '\\033[2J\\033[H'; printf '%s\\n' '**(https://example.com/docs)**' '**see (https://example.com/docs)**' '**[https://example.com/docs]**' 'https://example.com/search?q=)*'; echo printed > printed\n");
  await expect.poll(() => readFile(`${project}/printed`, "utf8").catch(() => ""), {timeout:15000}).toBe("printed\n");
  await app.screenshot("printed-urls");
  const geometry = await browser.evaluate(() => {
    const canvas = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
    const box = canvas.getBoundingClientRect();
    return {x:box.x, y:box.y, w:8, h:18};
  });
  for (let row = 0; row < 4; row++) {
    await browser.mouse.move(geometry.x + 4 + 12 * geometry.w, geometry.y + 4 + (row+.5)*geometry.h);
    await browser.keyboard.down("Control");
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.keyboard.up("Control");
    await app.screenshot(`url-line-${row+1}`);
  }
  const opened = await browser.evaluate(() => (window as unknown as {terminalOpened:string[]}).terminalOpened);
  expect(opened).toEqual(["https://example.com/docs", "https://example.com/docs", "https://example.com/docs", "https://example.com/search?q=)*"]);
});
