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

const URL = "https://github.com/pingdotgg/t3code/pull/47144";
test("PR links preserve Alt and Shift ordinary link handling", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Link demonstration");
  const thread = await t3.thread({project, title:"PR link reproduction", messages:[`Review [PR link](${URL}) and [diff anchor](${URL}/files#diff-abcR5).`]});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Review/).tap();
  await screen.getByRole("link", "PR link", {exact:true}).waitFor();
  await browser.evaluate(() => {
    const log = document.createElement("pre");
    log.id = "click-evidence";
    log.style.cssText = "position:fixed;bottom:8px;left:260px;z-index:99999;background:#101820;color:#fff;padding:12px;font:14px monospace;border:1px solid #889;pointer-events:none";
    log.textContent = "Input audit: waiting for link click";
    document.body.append(log);
    document.addEventListener("click", event => {
      const link = (event.target as Element).closest('a[href*="/pull/47144"]');
      if (!link) return;
      Object.assign(log, {lastClick:event, lastLink:link.getAttribute("href")});
    }, true);
    return null;
  });
  const results = [];
  for (const label of ["PR link", "diff anchor"]) {
    for (const modifier of ["Alt", "Shift", "Plain"]) {
      if (modifier !== "Plain") await browser.keyboard.down(modifier);
      await screen.getByRole("link", label, {exact:true}).tap();
      if (modifier !== "Plain") await browser.keyboard.up(modifier);
      const audit = await browser.evaluate(() => {
        const log = document.getElementById("click-evidence") as HTMLElement & {lastClick:MouseEvent;lastLink:string};
        const event = log.lastClick;
        log.textContent = `Real browser click: ${event.altKey ? "Alt" : event.shiftKey ? "Shift" : "Plain"}\nApp cancelled default: ${event.defaultPrevented}\nLink: ${log.lastLink}`;
        return {alt:event.altKey, shift:event.shiftKey, prevented:event.defaultPrevented};
      });
      if (modifier === "Plain" || audit.prevented) await browser.locator('[data-active-tab="true"]').waitFor();
      await browser.evaluate(async () => {
        if (!document.querySelector('[class*="animate-skeleton"]')) return null;
        await new Promise<void>(resolve => {
          const observer = new MutationObserver(() => {
            if (!document.querySelector('[class*="animate-skeleton"]')) { observer.disconnect(); resolve(); }
          });
          observer.observe(document.body, {subtree:true, childList:true, attributes:true});
        });
        return null;
      });
      await app.screenshot(`${label}-${modifier}`);
      const panel = await browser.evaluate(() => document.querySelector('[data-active-tab="true"]') !== null);
      results.push({label, modifier, ...audit, panel});
      if (panel) await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
    }
  }
  await expect(results).toEqual([
    ...["PR link", "diff anchor"].flatMap(label => [
      {label, modifier:"Alt", alt:true, shift:false, prevented:false, panel:false},
      {label, modifier:"Shift", alt:false, shift:true, prevented:false, panel:false},
      {label, modifier:"Plain", alt:false, shift:false, prevented:true, panel:true},
    ]),
  ]);
});
