import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Standalone work rows remember opened and closed state across thread switches", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some((provider) => provider.instanceId === "devReplay" && provider.models.some((model) => model.slug === "showcase"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  // Redact only the machine-local workspace prefix from recorded tool output.
  await browser.addInitScript(() => {
    const redact = () => {
      for (const pre of document.querySelectorAll("pre")) {
        const walk = document.createTreeWalker(pre, NodeFilter.SHOW_TEXT);
        let node;
        while ((node = walk.nextNode())) {
          const original = node.textContent ?? "";
          const redacted = original.replace(/\/[^\s"']*\/workspaces\/w-[^/]+/g, "/workspace");
          if (original !== redacted) node.textContent = redacted;
        }
      }
    };
    new MutationObserver(redact).observe(document, { childList: true, subtree: true, characterData: true });
  });
  const showcase = await t3.thread({ project, title: "Showcase", model: "showcase", messages: ["showcase"] });
  await t3.thread({ project, title: "Other work", model: "multi-turn", messages: ["multi turn"] });
  await t3.open(showcase);
  await screen.getByRole("button", /^Worked for/).tap();
  const read = screen.getByRole("button", /^Read demo\/package.json/);
  const thought = screen.getByRole("button", /^(Thought$|The user wants a short tour)/);
  const tasks = screen.getByRole("button", /^Tasks 3\/3/);
  const group = screen.getByRole("button", "Changed 1 file and ran 1 command", { exact: true });
  await read.tap();
  await thought.tap();
  await tasks.tap();
  await group.tap();
  const command = screen.getByRole("button", /^vp test run/);
  await command.tap();
  await screen.getByRole("button", /^Worked for/).hover();
  await app.screenshot("opened-before-switch");
  const roundTrip = async () => {
    await screen.getByRole("button", /^Other work,.*demo$/).press("Enter");
    await screen.getByText("multi turn", { exact: true }).waitFor();
    await screen.getByRole("button", /^Showcase,.*demo$/).press("Enter");
    await read.waitFor();
  };
  await roundTrip();
  await screen.getByRole("button", /^Worked for/).hover();
  await app.screenshot("opened-after-thread-round-trip");
  await expect(read).toHaveAttribute("aria-expanded", "true");
  await expect(thought).toHaveAttribute("aria-expanded", "true");
  await expect(tasks).toHaveAttribute("aria-expanded", "true");
  await read.tap();
  await thought.tap();
  await tasks.tap();
  await roundTrip();
  await screen.getByRole("button", /^Worked for/).hover();
  await app.screenshot("closed-after-thread-round-trip");
  await expect(read).toHaveAttribute("aria-expanded", "false");
  await expect(thought).toHaveAttribute("aria-expanded", "false");
  await expect(tasks).toHaveAttribute("aria-expanded", "false");
});
