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

test("Unpinned cards can be pinned by pointer and keyboard without opening them", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const open = await t3.thread({ project, title: "Keep this thread open", messages: ["first"] });
  await t3.thread({ project, title: "Pin with pointer", messages: ["first"] });
  await t3.thread({ project, title: "Pin with keyboard", messages: ["first"] });
  await t3.open(open);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      const animations = document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity);
      await Promise.all(animations.map((animation) => animation.finished.catch(() => undefined)));
    });
    await app.screenshot(label);
  };
  const originalUrl = await browser.evaluate(() => location.href);
  const pointerCard = screen.getByRole("button", "Pin with pointer", { exact: false });
  await pointerCard.hover();
  await capture("hover-unpinned-card");
  const pin = pointerCard.getByRole("button", "Pin thread");
  await expect(pin).toBeVisible();
  await pin.hover();
  await screen.getByText("Pin thread", { exact: true }).waitFor();
  await browser.locator('[data-slot="tooltip-viewport"]').filter({ hasText: "Pin thread" }).waitFor();
  await capture("pin-thread-tooltip");
  await pin.tap();
  await expect(screen.getByRole("button", "Unpin thread")).toBeVisible();
  await expect(browser).toHaveURL(originalUrl);
  await capture("after-pointer-pin");
  await screen.getByRole("textbox").tap();
  const keyboardCard = screen.getByRole("button", "Pin with keyboard", { exact: false });
  await keyboardCard.focus();
  await browser.keyboard.press("Tab");
  await capture("keyboard-pin-focused");
  await expect(keyboardCard.getByRole("button", "Pin thread")).toBeFocused();
  await browser.keyboard.press("Enter");
  await expect(screen.getByRole("button", "Unpin thread")).toHaveCount(2);
  await expect(browser).toHaveURL(originalUrl);
  await capture("after-keyboard-pin");
});
