/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

const lines = ["**see https://example.com**", "**see https://example.com.**", "**see ./src/app.ts**", "**(see ./src/app.ts)**", "(**see https://example.com**)", "(**see ./src/app.ts**)"];
const read = (file: string) => runPromise(Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  return (yield* fs.exists(file)) ? yield* fs.readFileString(file) : "";
}));

test("Terminal links exclude closing Markdown emphasis and wrappers", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", {
    "src/app.ts": "export const greeting = 'hello';\n",
    ...Object.fromEntries(lines.map((line, i) => [`case-${i}.txt`, `${line}\n`.repeat(100)])),
  });
  const thread = await t3.thread({ project, title: "Terminal emphasis links", messages: ["hello"] });
  await t3.open(thread);
  await browser.setViewport({ width: 1100, height: 800 });
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await expect.poll(async () => {
    await input.focus();
    await browser.keyboard.type("unset PROMPT_COMMAND; PS1='demo$ '; echo ready > shell-ready\n");
    return read(`${project}/shell-ready`);
  }, { timeout: 30000 }).toBe("ready\n");
  await browser.evaluate(() => {
    document.body.dataset.openedUrls = "[]";
    window.open = (url) => {
      const urls = JSON.parse(document.body.dataset.openedUrls ?? "[]");
      urls.push(String(url));
      document.body.dataset.openedUrls = JSON.stringify(urls);
      return null;
    };
  });
  const pathResults: boolean[] = [];
  for (let i = 0; i < lines.length; i++) {
    await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.remove(`${T3_HOME}/editor-args.txt`, { force: true })));
    await input.focus();
    await browser.keyboard.type(`cat case-${i}.txt; echo done > done-${i}\n`);
    await expect.poll(() => read(`${project}/done-${i}`), { timeout: 30000 }).toBe("done\n");
    const box = await browser.evaluate(() => {
      const rect = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
      if (!rect) throw new Error("Terminal canvas missing");
      return { x: rect.x, y: rect.y, height: rect.height };
    });
    await browser.mouse.move(box.x + 100, box.y + box.height / 2);
    await browser.keyboard.down("Control");
    // Wait for the real surface's asynchronous file validation before capture/click.
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1200)));
    await app.screenshot(`case-${i + 1}-hover`);
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.keyboard.up("Control");
    if (lines[i].includes("./src")) {
      await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1200)));
      pathResults.push((await read(`${T3_HOME}/editor-args.txt`)).includes(`${project}/src/app.ts`));
    }
  }
  const urls = await browser.evaluate(() => JSON.parse(document.body.dataset.openedUrls ?? "[]"));
  await expect({ urls, pathResults }).toEqual({ urls: ["https://example.com", "https://example.com", "https://example.com"], pathResults: [true, true, true] });
});
