import { expect } from "e2e";
import type { PlaywrightLiveSurface } from "@e2e-dev/web";
import { test, WEB } from "./t3.ts";

test("Middle-clicking a chat file chip opens no broken tab", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo-repo", Object.fromEntries(Array.from({ length: 4 }, (_, i) => [`src/module${i}.ts`, `export const module${i} = ${i};\n`])));
  await t3.open("/");
  await expect.poll(() => browser.evaluate(() => window.t3dev?.replayScenarios().includes("bench-heavy") ?? false)).toBe(true);
  await browser.evaluate(() => window.t3dev!.replay("bench-heavy"));
  await screen.getByRole("link", /^module0\.ts/).first().waitFor();
  await screen.getByRole("button", "Submit message").waitFor();
  const live = (browser as typeof browser & { proofLive: PlaywrightLiveSurface }).proofLive;
  const page = live.page();
  const context = live.context();
  const originalUrl = page.url();
  const beforeCount = context.pages().length;
  await page.getByRole("link", { name: /^module0\.ts/ }).first().scrollIntoViewIfNeeded();
  await app.screenshot("before-middle-click");
  const popupPromise = context.waitForEvent("page", { timeout: 2500 }).catch(() => null);
  await page.getByRole("link", { name: /^module0\.ts/ }).first().click({ button: "middle" });
  const popup = await popupPromise;
  if (popup) {
    await popup.getByText("Thread unavailable", { exact: true }).waitFor();
    await popup.bringToFront();
    await popup.screenshot({ path: "/tmp/factory-pr-47125-evidence-1/broken-tab.png" });
  }
  await app.screenshot("after-middle-click");
  await expect(context.pages().length).toBe(beforeCount);
  await expect(page.url()).toBe(originalUrl);
});
