/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { test, WEB, runPromise, rpcClient } from "./t3.ts";

const URL = "https://github.com/pingdotgg/t3code/issues/1";
const LINE = `See ${URL} for details.`;

test("Modified issue links retain ordinary link behavior", WEB, async ({ t3, app, browser }) => {
  const project = await t3.project("issue-link-demo");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  // Replay supplies the exact static Markdown this UI reproduction needs; no provider behavior is under test.
  const fixture = path.join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  await fs.writeFile(fixture, original.replaceAll("first fixture turn complete", LINE));
  await new Promise((resolve) => setTimeout(resolve, 6000));
  try {
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter((event) => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some((provider) => provider.instanceId === "devReplay" && provider.models?.some((model) => model.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("45 seconds")));
  let thread;
    thread = await t3.thread({ project, title: "Issue link modifiers", messages: [`Reply with exactly this single line: ${LINE}`] });
  await browser.setViewport({ width: 1280, height: 800 });
  const results: Array<{ modifier: string; prevented: boolean; panel: boolean }> = [];
  for (const modifier of ["Alt", "Shift", "Control", "plain"]) {
    await t3.open(thread);
    const link = browser.locator(`a[href="${URL}"]`).last();
    await link.waitFor();
    const close = browser.locator('button[aria-label="Toggle right panel"][aria-pressed="true"]');
    if (await close.count()) await close.tap();
    await browser.locator('[data-workspace-area="panel"]').waitFor({ state: "hidden" });
    await browser.evaluate(() => {
      document.documentElement.removeAttribute("data-link-prevented");
      document.addEventListener("click", (event) => {
        if ((event.target as Element).closest('a[href="https://github.com/pingdotgg/t3code/issues/1"]')) {
          setTimeout(() => document.documentElement.setAttribute("data-link-prevented", String(event.defaultPrevented)), 0);
        }
      }, { once: true, capture: true });
    });
    if (modifier !== "plain") await browser.keyboard.down(modifier);
    await link.tap();
    if (modifier !== "plain") await browser.keyboard.up(modifier);
    // Match the triage's observation interval, allowing the panel and browser default action to settle.
    await new Promise((resolve) => setTimeout(resolve, 3500));
    const prevented = await browser.evaluate(() => document.documentElement.getAttribute("data-link-prevented") === "true");
    const panel = await browser.locator('[data-active-tab="true"]').filter({ hasText: "#1" }).isVisible();
    results.push({ modifier, prevented, panel });
    await app.screenshot(`${modifier.toLowerCase()}-click`);
  }
  expect(results).toEqual([
    { modifier: "Alt", prevented: false, panel: false },
    { modifier: "Shift", prevented: false, panel: false },
    { modifier: "Control", prevented: false, panel: false },
    { modifier: "plain", prevented: true, panel: true },
  ]);
  } finally {
    await fs.writeFile(fixture, original);
    await new Promise((resolve) => setTimeout(resolve, 6000));
  }
});
