import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Removing a checkout clears the other project's subscribed sidebar label", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Checkout demo");
  const { cli } = makeState(T3_HOME);
  const started = JSON.parse((await runPromise(cli(["thread", "start", project, "first", "--title", "Checkout owner", "--worktree", "main", "--branch", "feature-checkout", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]))).stdout);
  const owner = { threadId: started.threadId };
  const details = JSON.parse((await runPromise(cli(["thread", "show", owner.threadId, "--json"]))).stdout);
  const checkout = details.thread.worktreePath;
  await runPromise(cli(["project", "add", checkout, "--title", "Shared checkout"]));
  const observer = await t3.thread({ project: checkout, title: "Watching checkout", messages: ["first"] });
  await t3.open(observer);
  const row = screen.getByRole("button", /^Watching checkout,/);
  await row.getByText("feature-", { exact: false }).waitFor();
  await app.screenshot("subscribed-checkout");
  await screen.getByRole("button", /^Checkout owner,/).secondaryTap();
  await screen.getByRole("menuitem", "Delete").tap();
  await screen.getByRole("button", "Confirm").tap();
  await screen.getByRole("heading", "Delete the worktree too?").waitFor();
  await screen.getByRole("button", "Confirm").tap();
  await screen.getByRole("button", /^Checkout owner,/).waitFor({ state: "hidden" });
  await screen.getByRole("alertdialog").waitFor({ state: "hidden" });
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 8; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("Capture did not settle");
  };
  await stableCapture("checkout-removed");
  await row.hover();
  const hoverCard = browser.locator('[data-slot="tooltip-popup"]');
  await hoverCard.waitFor();
  await stableCapture("hover-after-removal");
  await expect(row).not.toContainText(/feature-\s*checkout/);
  await expect(hoverCard).not.toContainText(/feature-\s*checkout/);
});
