import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Review commit subjects omit an emoji that straddles the limit", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("emoji-review");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project });
  git("checkout", "-b", "feature/emoji");
  writeFileSync(`${project}/a.txt`, "Review this change.\n");
  git("add", "a.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "a".repeat(299) + "🚀");
  const thread = await t3.thread({ project, title: "Review emoji commit", model: "showcase", messages: ["Show this change"] });
  await t3.open(thread);
  await screen.getByRole("button", "Changes vs main", { exact: false }).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitem", "Commits", { exact: true }).hover();
  const commit = screen.getByRole("menuitemradio", /^aaaa/);
  await commit.hover();
  await browser.locator('[data-slot="tooltip-viewport"]').waitFor();
  await browser.evaluate(async () => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    return null;
  });
  await app.screenshot("commit-subject-tooltip");
  const tooltip = await browser.evaluate(() => document.querySelector('[data-slot="tooltip-viewport"]')?.textContent ?? "");
  await commit.tap();
  await screen.getByRole("button", /^Diff scope: aaaa/).waitFor();
  await app.screenshot("selected-commit");
  const scope = await browser.evaluate(() => document.querySelector('button[aria-label^="Diff scope: aaaa"]')?.getAttribute("aria-label") ?? "");
  expect({ tooltip, scope }).toEqual({ tooltip: "a".repeat(299), scope: "Diff scope: " + "a".repeat(299) });
});
