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

test("Expanded issue comment survives switching right-panel tabs", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Issue comments");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  const input = { project, title: "Issue review", messages: ["Start"] };
  const thread = await t3.thread({ ...input, model: "default" }).catch(() => t3.thread(input));
  const projectId = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const item = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if (item._tag !== "Some" || item.value.kind !== "snapshot") throw new Error("No snapshot");
    return item.value.snapshot.projects.find(p => p.workspaceRoot === project)!.id;
  }).pipe(Effect.scoped));
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await t3.open(`/issues?selectedProjectId=${projectId}&tracker=github&scope=pingdotgg/t3code&key=47258`);
  const expand = screen.getByRole("button", "Show full comment", { exact: true });
  await expand.waitFor({ timeout: 60000 });
  await expand.tap();
  await screen.getByRole("button", "Show less", { exact: true }).waitFor();
  await browser.evaluate(() => { [...document.querySelectorAll("button")].find(b => b.textContent === "Show less")?.scrollIntoView({ block: "center" }); return null; });
  await app.screenshot("expanded-before-switch");
  await screen.getByText("[Feature]: First-class ephemeral environments: T3 owns the machine's life, and threads outlive it", { exact: true }).tap();
  await browser.locator('[data-active-tab="true"]').filter({ hasText: "47266" }).waitFor();
  await browser.locator('[data-active-tab="false"]').filter({ hasText: "47258" }).tap();
  await screen.getByRole("button", "Refresh issue", { exact: true }).waitFor();
  await browser.evaluate(() => { [...document.querySelectorAll("button")].find(b => /^(Show less|Show full comment)$/.test(b.textContent ?? ""))?.scrollIntoView({ block: "center" }); return null; });
  await app.screenshot("comment-after-tab-roundtrip");
  await expect(screen.getByRole("button", "Show less", { exact: true })).toBeVisible();
});
