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

test("Mixed-case PR anchors reveal the same timeline items as lowercase links", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("anchor-case-check");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  const links = [
    "https://github.com/pingdotgg/t3code/pull/44449#issuecomment-7228026616",
    "https://github.com/pingdotgg/t3code/pull/44449#ISSUECOMMENT-7228026616",
    "https://github.com/pingdotgg/t3code/pull/44399#pullrequestreview-6092880583",
    "https://github.com/pingdotgg/t3code/pull/44399#PullRequestReview-6092880583",
  ];
  const thread = await t3.thread({ project, title: "Anchor case check", messages: [links.join("\n\n")] });
  const results: { label: string; targets: number; targetText: string }[] = [];
  const labels = ["lowercase-comment-control", "uppercase-comment", "lowercase-empty-review-control", "mixed-case-empty-review"];
  for (const [index, link] of links.entries()) {
    await t3.open(thread);
    await screen.getByRole("button", /^Agent https:\/\/github/).tap();
    await browser.locator(`a[href="${link}"]`).first().tap();
    await screen.getByRole("button", "Timeline", { exact: true }).waitFor();
    // Wait for the real GitHub activity, whether it resolves a target or reports a missing item.
    await browser.locator('[data-pr-link-target="true"], [role="status"]').filter({ hasText: /Thread transfer impact|The linked item is not in the loaded activity\.|Valid, and this PR made it reachable/ }).first().waitFor();
    await app.screenshot(labels[index]!);
    results.push(await browser.evaluate((label) => {
      const nodes = document.querySelectorAll('[data-pr-link-target="true"]');
      return { label, targets: nodes.length, targetText: nodes[0]?.textContent ?? "" };
    }, labels[index]!));
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  }
  expect(results.map(({ label, targets }) => ({ label, targets }))).toEqual(labels.map(label => ({ label, targets: 1 })));
  expect(results[1]?.targetText).toEqual(results[0]?.targetText);
  expect(results[3]?.targetText).toEqual(results[2]?.targetText);
  expect(results[3]?.targetText).toContain("Valid, and this PR made it reachable");
});
