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

test("Bracketed terminal URLs exclude Markdown emphasis", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "print.sh": "printf '\\033[2J\\033[H(**https://example.com/docs**)\\n[**https://example.com/docs**]\\n(*https://example.com/docs*)\\n**https://example.com/docs**\\nhttps://example.com/a*b\\n'; sleep 120\n" });
  const thread = await t3.thread({ project, title: "Terminal URL emphasis", messages: ["Ready"] });
  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).openedUrls = [];
    const panel = document.createElement("pre");
    panel.id = "opened-url-evidence";
    panel.style.cssText = "position:fixed;top:80px;right:24px;z-index:99999;background:#18181b;color:white;padding:16px;border:1px solid #777;font:16px monospace";
    panel.textContent = "Observed window.open destinations:";
    document.body.append(panel);
    window.open = ((url: string) => {
      (window as any).openedUrls.push(String(url));
      panel.textContent += "\n" + url;
      return null;
    }) as typeof window.open;
  });
  await input.focus();
  await browser.keyboard.type("bash print.sh\n");
  await app.screenshot("terminal-output");
  // The cursor follows five printed rows; its position gives the actual cell height.
  const box = await browser.evaluate(() => {
    const c = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
    const r = c.getBoundingClientRect();
    const input = document.querySelector('[aria-label="Terminal input"]') as HTMLTextAreaElement;
    return { x:r.x, y:r.y, h:(parseFloat(input.style.top)-4)/5 };
  });
  for (let row=0; row<5; row++) {
    await browser.mouse.move(box.x+90,box.y+4+(row+0.5)*box.h);
    await browser.keyboard.down("Control");
    await app.screenshot(`hover-row-${row+1}`);
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.keyboard.up("Control");
  }
  await app.screenshot("opened-url-destinations");
  await expect.poll(() => browser.evaluate(() => (window as any).openedUrls)).toEqual([
    "https://example.com/docs", "https://example.com/docs", "https://example.com/docs", "https://example.com/docs", "https://example.com/a*b"
  ]);
});
