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

test("Terminal URLs exclude closing Markdown emphasis", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  let thread;
  for (let attempt = 0; attempt < 4; attempt++) {
    try {
      thread = await t3.thread({ project, title: "Terminal Markdown URLs", messages: ["hello"] });
      break;
    } catch (error) {
      if (!String(error).includes("not advertised") || attempt === 3) throw error;
    }
  }
  if (!thread) throw new Error("Replay thread did not start");
  await browser.setViewport({ width: 1200, height: 800 });
  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 input.focus();
  await browser.keyboard.type("PS1=''; printf '\\033[2J\\033[H**https://example.com/docs**\\n*https://example.com/docs*\\nsee **https://example.com/docs**.\\n'\n");
  await browser.evaluate(() => {
    const panel = document.createElement("pre");
    panel.id = "opened-urls";
    panel.style.cssText = "position:fixed;right:20px;top:100px;z-index:99999;background:#17202c;color:#fff;padding:16px;border:1px solid #8294aa;font:16px monospace";
    panel.textContent = "Observed window.open destinations:\n";
    document.body.append(panel);
    (window as any).__openedUrls = [];
    window.open = ((url: string) => {
      (window as any).__openedUrls.push(String(url));
      panel.textContent += String(url) + "\n";
      return null;
    }) as typeof window.open;
    return null;
  });
  const canvas = await browser.evaluate(() => {
    const el = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas");
    if (!el) throw new Error("No terminal canvas");
    const box = el.getBoundingClientRect();
    const context = el.getContext("2d")!;
    const size = Number(context.font.match(/([\d.]+)px/)?.[1] ?? 13);
    const height = Math.round(size * 1.35);
    return { x: box.x, y: box.y, cell: context.measureText("M").width, height, slack: (box.height - 8) % height };
  });
  for (let row = 0; row < 3; row++) {
    await browser.mouse.move(canvas.x + 4 + canvas.cell * 12, canvas.y + 4 + canvas.slack + canvas.height * (row + 0.5));
    await browser.keyboard.down("Control");
    await app.screenshot(`hover-line-${row + 1}`);
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.keyboard.up("Control");
  }
  await app.screenshot("opened-destinations");
  await expect.poll(() => browser.evaluate(() => (window as any).__openedUrls)).toEqual([
    "https://example.com/docs", "https://example.com/docs", "https://example.com/docs",
  ]);
});
