/// <reference lib="dom" />
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const TITLE = "Release planning";
const BRANCH = "feature/release-planning";
const PROJECT = "hover-demo";

const metadata = (origin: string, threadId: string) => runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, origin);
  yield* client["orchestration.dispatchCommand"]({
    type: "thread.metadata.update", commandId: CommandId.make(randomUUID()),
    threadId: ThreadId.make(threadId), branch: BRANCH,
  });
  yield* client["orchestration.dispatchCommand"]({
    type: "thread.pull-request.link", commandId: CommandId.make(randomUUID()),
    threadId: ThreadId.make(threadId), host: "github.com", repository: "scenario/hover-demo",
    number: 42, url: "https://github.com/scenario/hover-demo/pull/42", source: "manual",
  });
}).pipe(Effect.scoped));

test("Thread chip hover cards show details across composer, sent context, links, and unreadable context", WEB,
async ({ t3, app, screen, browser }) => {
  const project = await t3.project(PROJECT);
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/scenario/hover-demo.git"], { cwd: project }));
  const source = await t3.thread({ project, title: TITLE, messages: ["Plan the next release"] });
  await metadata(app.baseUrl ?? "", source.threadId);
  const environment = await runPromise(environmentId(app.baseUrl ?? ""));
  const current = await t3.thread({ project, title: "Review release", messages: [`Review [${TITLE}](t3-thread://v2/${environment}/${source.threadId})`] });
  const popup = browser.locator('[data-slot="tooltip-viewport"]');
  const branchRow = browser.locator(`[data-slot="tooltip-viewport"] [title="${BRANCH}"]`);
  const capture = async (label: string) => {
    await browser.locator('[data-slot="tooltip-popup"]:not([data-starting-style]):not([data-ending-style])').waitFor();
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      if (popup) getComputedStyle(popup).opacity;
      await Promise.all((popup?.getAnimations({ subtree: true }) ?? []).map((animation) => animation.finished.catch(() => undefined)));
      return null;
    });
    await app.screenshot(label);
  };
  const details = async (label: string) => {
    await popup.waitFor();
    await expect.soft(popup).toContainText(TITLE, { timeout: 2000 });
    await expect.soft(popup).toContainText(PROJECT, { timeout: 2000 });
    await expect.soft(branchRow).toBeVisible({ timeout: 2000 });
    await expect.soft(popup).toContainText("Multi turn", { timeout: 2000 });
    await expect.soft(popup).toContainText("#42", { timeout: 2000 });
    await capture(label);
    await browser.keyboard.press("Escape");
  };

  await t3.open(current);
  await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
  await screen.getByRole("button", /^Agent Review/).tap();
  const chip = screen.getByRole("link", `Thread, ${TITLE}`, { exact: true });
  await chip.hover();
  await details("message-link-hover");
  const composer = screen.getByRole("textbox");
  await composer.pressSequentially("Compare with @Release");
  await screen.getByRole("option", TITLE, { exact: false }).tap();
  await chip.last().hover();
  await details("composer-chip-hover");
  await composer.press("Enter");
  await screen.getByRole("button", "Edit from here").waitFor({ timeout: 60_000 });
  await chip.last().hover();
  await details("sent-chip-hover");

  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await runPromise(makeState(SECOND_HOME).cli(["project", "add", project, "--title", PROJECT]));
    await app.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "List", { exact: true }).tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 });
    await t3.open(current);
    await screen.getByRole("button", "New thread in hover-demo", { exact: true }).tap();
    const detailsToggle = screen.getByRole("button", "Toggle thread details panel", { exact: true });
    if (await detailsToggle.getAttribute("aria-pressed") === "true") await detailsToggle.tap();
    await composer.pressSequentially("Compare with @Release");
    await screen.getByRole("option", TITLE, { exact: false }).tap();
    await screen.getByRole("combobox", "Run on", { exact: true }).tap();
    const machines = screen.getByRole("option", "Scenario", { exact: true });
    const target = (await machines.nth(0).getAttribute("aria-selected")) === "true" ? 1 : 0;
    await machines.nth(target).tap();
    await chip.last().hover();
    await popup.waitFor();
    await expect.soft(popup).toContainText("On another machine, so this machine's agent can't read it.");
    await details("unreadable-chip-hover");
  } finally {
    await server.stop();
  }
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.archive", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(source.threadId),
    });
  }).pipe(Effect.scoped));
  await t3.open(current);
  await screen.getByRole("button", /^Agent Review/).tap();
  await chip.first().hover();
  await popup.waitFor();
  await expect.soft(popup).toContainText(TITLE, { timeout: 2000 });
  await expect.soft(popup).toContainText(PROJECT, { timeout: 2000 });
  await expect.soft(branchRow).toBeHidden({ timeout: 2000 });
  await capture("unloaded-thread-hover");
});
