/// <reference lib="dom" />
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { CommandId, IssueTrackerKind, ProjectId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());

const linkItems = Effect.fn("scenario.linkItems")(
  function* (origin: string, threadId: ThreadId) {
    const client = yield* rpcClient(T3_HOME, origin);
    const { thread } = yield* client["orchestration.getThreadProjection"]({ threadId });
    for (let index = 1; index <= 30; index++) {
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.issue.link",
        commandId: CommandId.make(yield* uuid),
        threadId,
        tracker: IssueTrackerKind.make("github"),
        host: "github.com",
        scope: "example/demo",
        key: String(index),
        projectId: ProjectId.make(thread.projectId),
        url: `https://github.com/example/demo/issues/${index}`,
        displayKey: `#${index}`,
        title: `Linked issue ${index}`,
        source: "manual",
      });
    }
    for (let number = 101; number <= 108; number++) {
      const key = { threadId, host: "github.com", repository: "example/demo", number };
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.pull-request.link",
        commandId: CommandId.make(yield* uuid),
        ...key,
        url: `https://github.com/example/demo/pull/${number}`,
        source: "manual",
      });
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.pull-request-link.sync",
        commandId: CommandId.make(yield* uuid),
        ...key,
        snapshot: {
          state: "open",
          title: `Pull request ${number}`,
          headBranch: `change-${number}`,
          baseBranch: "main",
          isDraft: false,
          updatedAt: null,
          syncedAt: "2026-01-01T00:00:00.000Z",
        },
        stack: null,
      });
    }
  },
  Effect.scoped,
  Effect.provide(NodeCrypto.layer),
);

test(
  "Unlinking a pull request keeps the Linked items list where it was",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Linked work", messages: ["first"], model: "default" });
    await runPromise(linkItems(app.baseUrl ?? "", ThreadId.make(thread.threadId)));
    // Tall enough that the panel's first issue is far above the pull requests.
    await browser.setViewport({ width: 1440, height: 1180 });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByRole("button", "Linked items L", { exact: true }).tap();
    await screen.getByText("Pull requests", { exact: true }).waitFor();
    await screen.getByText("Linked issue 5", { exact: true }).hover();
    for (let step = 0; step < 30; step++) await browser.mouse.wheel(0, 120);
    const listScrollTop = () =>
      browser.evaluate(() => {
        const issue = [...document.querySelectorAll("a")].find(
          (link) => link.textContent?.includes("Linked issue 1") === true,
        );
        let list = issue?.parentElement ?? null;
        while (list && list.scrollHeight <= list.clientHeight + 1) list = list.parentElement;
        return list?.scrollTop ?? -1;
      });
    await screen.getByText("Pull request 106", { exact: true }).hover();
    const before = await listScrollTop();
    await app.screenshot("before-unlink");
    await screen.getByRole("button", "Actions for #106", { exact: true }).tap();
    await screen.getByRole("menuitem", "Unlink from thread", { exact: true }).tap();
    await screen.getByText("Pull request 106", { exact: true }).waitFor({ state: "detached" });
    // Focus that the removed row held is recovered on the next animation frame.
    await expect
      .poll(() => browser.evaluate(() => document.activeElement !== document.body))
      .toBe(true);
    await app.screenshot("after-unlink");
    // Only the removed row's height may come off the bottom of the list.
    const afterMouse = await listScrollTop();
    // Unlinking from the keyboard hands focus to the row that took the removed one's place.
    for (let step = 0; step < 30; step++) await browser.mouse.wheel(0, 120);
    await screen.getByText("Pull request 105", { exact: true }).hover();
    const beforeKeyboard = await listScrollTop();
    await screen.getByRole("button", "Actions for #105", { exact: true }).tap();
    await app.screenshot("keyboard-actions-menu");
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1000)));
    await browser.keyboard.press("End");
    await app.screenshot("keyboard-unlink-selected");
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1000)));
    await browser.keyboard.press("Enter");
    await screen.getByText("Pull request 105", { exact: true }).waitFor({ state: "detached" });
    await browser.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
    await app.screenshot("after-keyboard-unlink");
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1000)));
    const focus = await browser.evaluate(() => {
      const active = document.activeElement as HTMLElement;
      const rect = active.getBoundingClientRect();
      let list = active.parentElement;
      while (list && list.scrollHeight <= list.clientHeight + 1) list = list.parentElement;
      const box = list?.getBoundingClientRect();
      return { label: active.getAttribute("aria-label") ?? "", fullyVisible: !!box && rect.top >= box.top && rect.bottom <= box.bottom };
    });
    expect(afterMouse, "Mouse unlink preserves position").toBeGreaterThan(before - 100);
    expect(focus.label, "Keyboard focus stays at neighboring PR").toMatch(/^Actions for #10[47]$/);
    expect(focus.fullyVisible, "Recovered focus is fully visible").toBe(true);
    expect(await listScrollTop(), "The list stays at the pull requests").toBeGreaterThan(
      beforeKeyboard - 100,
    );
  },
);
