/// <reference lib="dom" />
import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

const MESSAGE = "See [the docs](https://example.com/) for details.";

test(
  "Shift-click and Alt-click on a chat link stay with the browser when links open in T3 Code",
  WEB,
  async ({ t3, app, browser, screen }) => {
    // The setting's control is desktop-only, so seed the stored web preference.
    await browser.addInitScript(() => {
      localStorage.setItem(
        "t3code:client-settings:v1",
        JSON.stringify({ browserLinkTarget: "app" }),
      );
    });
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Docs", messages: [MESSAGE] });
    await t3.open(thread);
    // A message sent through the CLI shows collapsed under its sender.
    await screen.getByRole("button", /^Agent See/).tap();
    const link = browser.locator('a[href="https://example.com/"]').last();

    // Records whether the app canceled each click. The app stops a click it takes, so listen in
    // the capture phase and read the result once its handler has run.
    await browser.evaluate(() => {
      document.documentElement.dataset.prevented = "";
      window.addEventListener(
        "click",
        (event) => {
          // @effect-diagnostics-next-line globalTimers:off - This callback runs inside the browser.
          setTimeout(() => {
            document.documentElement.dataset.prevented += event.defaultPrevented ? "1" : "0";
          });
        },
        true,
      );
      return null;
    });
    for (const key of ["Shift", "Alt"] as const) {
      await browser.keyboard.down(key);
      try {
        await link.tap();
      } finally {
        await browser.keyboard.up(key);
      }
      await app.screenshot(`${key.toLowerCase()}-click`);
    }
    await link.tap();
    await browser.locator('[data-workspace-area="panel"]').waitFor({ state: "visible" });
    await app.screenshot("plain-click");

    const prevented = await browser.evaluate(
      () => document.documentElement.dataset.prevented ?? "",
    );
    expect(
      prevented,
      "Shift and Alt clicks stay with the browser; a plain click opens the preview",
    ).toBe("001");
  },
);
