/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Long submodule setup detail ends without a lone surrogate", WEB, async ({ t3, app, browser }) => {
  const source = await t3.project("submodule-source", { "hello.txt": "hello" });
  const project = await t3.project("proj", {
    "t3.json": JSON.stringify({ scripts: [{ name: "Slow setup", command: "sleep 120", runOnWorktreeCreate: true, async: false }] }),
  });
  const path = `deps/${"a".repeat(48)}/${"a".repeat(48)}/${"a".repeat(48)}/${"a".repeat(46)}🚀tail`;
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("-c", "protocol.file.allow=always", "submodule", "add", source, path);
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-am", "Add submodule");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { defaultProjectScripts: [{ id: "slow-setup", name: "Slow setup", command: "sleep 120", icon: "play", runOnWorktreeCreate: true, async: false }] } });
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli([
    "thread", "start", project, "hello", "--worktree", "main", "--provider", "devReplay", "--model", "showcase", "--json",
  ]));
  await t3.open(JSON.parse(started.stdout));
  await browser.locator('[data-worktree-setup-stage="setup-script"][data-worktree-setup-status="running"]').waitFor({ timeout: 60000 });
  const detail = await browser.evaluate(() => {
    const row = document.querySelector('[data-worktree-setup-stage="submodules"]');
    const element = [...(row?.querySelectorAll<HTMLElement>('span') ?? [])].find((span) => span.textContent?.startsWith('deps/'));
    if (!element) throw new Error(`Missing submodule detail: ${row?.outerHTML}`);
    document.querySelectorAll('pre').forEach((pre) => { pre.style.display = 'none'; });
    element.style.fontSize = "18px";
    element.style.lineHeight = "24px";
    element.style.direction = "rtl";
    element.style.outline = "2px solid #e44";
    return element.textContent ?? "";
  });
  await app.screenshot("submodule-detail-tail");
  expect(detail.length).toBeLessThanOrEqual(200);
  expect(detail.endsWith("…")).toBe(true);
  expect(detail.isWellFormed()).toBe(true);
});
