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

const group = "https://gitlab.com/groups/gitlab-org/-/work_items/7023";
const projectLink = "https://gitlab.com/gitlab-org/cli/-/work_items/8806";
test("GitLab group work items remain ordinary web links", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("gitlab-cli");
  execFileSync("git", ["remote", "add", "origin", "https://gitlab.com/gitlab-org/cli.git"], {cwd: project});
  const thread = await t3.thread({project, title: "GitLab work item links", messages: ["Show the two GitLab work item links"]});
  await t3.open(thread);
  await screen.getByRole("link", "the group work item", {exact:true}).waitFor();
  await app.screenshot("links-before-click");
  await browser.evaluate(() => {
    (window as any).__groupClick = null;
    document.addEventListener("click", (event) => {
      const a = (event.target as Element).closest("a");
      if (a?.textContent?.includes("the group work item")) { (window as any).__groupClick = event; (window as any).__groupHref = a.href; }
    }, {capture:true});
  });
  await screen.getByRole("link", "the group work item", {exact:true}).tap();
  const click = await browser.evaluate(() => ({prevented: (window as any).__groupClick?.defaultPrevented, href: (window as any).__groupHref}));
  if (click?.prevented) await screen.getByText("Could not load this issue", {exact:false}).waitFor();
  await app.screenshot("group-link-clicked");
  await screen.getByRole("link", "a project work item", {exact:true}).tap();
  await screen.getByText("Align generated CLI docs with the CLI style guide", {exact:false}).first().waitFor();
  await app.screenshot("project-work-item-control");
  expect(click).toEqual({prevented:false, href:group});
});
