/// <reference lib="dom" />
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Idle detached checkout reports no branch instead of busy", WEB, async ({ t3, app, screen, browser }) => {
  // Mask synthetic absolute paths in public evidence; cleanup labels remain untouched.
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = `code { font-size: 0 !important; } code::after { content: "[synthetic path redacted]"; font-size: 12px; } #scheduled-task-checkout { -webkit-text-security: disc; }`;
      document.head.append(style);
    });
  });
  const project = await t3.project("repo");
  await runPromise(run("git", ["worktree", "add", "-b", "side", `${project}-side`], { cwd: project }));
  await runPromise(run("git", ["worktree", "add", "--detach", `${project}-detached`], { cwd: project }));
  await t3.thread({project, title: "Setup", messages: ["Say hello."], model: "multi-turn"});
  await t3.open("/settings/scheduled-tasks");
  for (const suffix of ["side", "detached"]) {
    await screen.getByRole("button", "New task").tap();
    await screen.getByRole("textbox", "Name").fill(`Checkout ${suffix}`);
    await screen.getByRole("combobox", "Workspace").tap();
    await screen.getByRole("option", "Use a specific checkout").tap();
    await screen.getByRole("textbox", "Checkout path").fill(`${project}-${suffix}`);
    await screen.getByRole("textbox", "Prompt").fill("Say hello.");
    await screen.getByRole("button", "Create task").tap();
    await screen.getByRole("button", `Actions for Checkout ${suffix}`).tap();
    await screen.getByRole("menuitem", "Run now").tap();
    await screen.getByText("succeeded", {exact:true}).nth(suffix === "side" ? 0 : 1).waitFor({timeout:120_000});
  }
  await t3.open("/settings/worktrees");
  await screen.getByRole("switch", "Delete worktrees with deleted threads").tap();
  await t3.open("/settings/maintenance");
  await screen.getByRole("button", "Delete now").tap();
  await screen.getByRole("button", "Last run", {exact:false}).tap();
  await screen.getByRole("heading", "repo-detached", {exact:true}).waitFor();
  await screen.getByRole("heading", "repo-detached", {exact:true}).scrollIntoView();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {}))); });
  await screen.getByRole("heading", "repo-detached", {exact:true}).scrollIntoView();
  await screen.getByText("Checkout detached", {exact:true}).tap();
  await app.screenshot("cleanup-reasons");
  await expect(screen.getByText("Thread has no branch", {exact:true})).toBeVisible();
});
