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

test("Thread search uses visible labels for nested Markdown links", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Link search demo");
  const egret = await t3.thread({ project, title: "Learn About Egrets", messages: ["Start"] });
  const draft = await t3.thread({ project, title: "Bracketed link example", messages: ["Start"] });
  await t3.open(egret);
  await screen.getByRole("textbox").pressSequentially("See [Egret](https://en.wikipedia.org/wiki/Egret_(bird)) today");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await t3.open(draft);
  await screen.getByRole("textbox").pressSequentially("Read [the [draft] plan](https://egret.dev/b)");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await browser.keyboard.press("Control+k");
  const palette = screen.getByRole("dialog", "Command palette");
  const input = palette.getByRole("combobox");
  const texts: Record<string, string> = {};
  for (const query of ["egret.dev", "egret", "egret today", "bird", "draft plan", "the draft"]) {
    await input.fill(query);
    // Wait for the debounced server search and its rendered result before capture.
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); return null; });
    await app.screenshot(query.replaceAll(".", "-").replaceAll(" ", "-"));
    texts[query] = await browser.evaluate(() => document.querySelector('[role="dialog"]')?.textContent ?? "");
  }
  expect(texts["egret.dev"]).not.toContain("Bracketed link example");
  expect(texts["egret today"]).toContain("See Egret today");
  expect(texts["egret today"]).not.toContain("Egret) today");
  expect(texts["the draft"]).toContain("Read the [draft] plan");
  expect(texts["the draft"]).not.toContain("https://egret.dev");
});
