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

test("Closed panel terminals disappear behind files, after thread return, and after reload", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "package.json": '{"name":"terminal-proof","private":true}\n' });
    const cases = [];
    for (const mode of ["hidden-file", "thread-return", "reload"] as const) {
      cases.push({ mode, thread: await t3.thread({ project, title: mode, messages: ["Start"] }) });
    }
    const away = await t3.thread({ project, title: "Another thread", messages: ["Start"] });
    const outcomes: Record<string, boolean> = {};
    const listed = (id: string) => runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl);
      const event = Option.getOrThrow(yield* client.subscribeTerminalMetadata({}).pipe(
        Stream.filter((event) => event.type === "snapshot"), Stream.runHead));
      return event.type === "snapshot" ? event.terminals.filter((t) => t.threadId === id) : [];
    }).pipe(Effect.scoped));
    const navigate = async (id: string) => {
      await browser.locator(`[data-sidebar-row$="${id}"]`).click();
      await browser.waitForURL(new RegExp(encodeURIComponent(id) + "$"));
    };
    for (const { mode, thread } of cases) {
      const threadId = ThreadId.make(thread.threadId);
      await t3.open(thread);
      await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
      await screen.getByRole("button", "Terminal T", { exact: true }).tap();
      const input = browser.locator('[data-terminal-owner="right-panel"] [aria-label="Terminal input"]');
      await input.waitFor({ state: "visible" });
      const terminal = await runPromise(Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        return Option.getOrThrow(yield* client.subscribeTerminalMetadata({}).pipe(
          Stream.flatMap((event) => Stream.fromIterable(event.type === "snapshot" ? event.terminals : event.type === "upsert" ? [event.terminal] : [])),
          Stream.filter((t) => t.threadId === threadId && t.status === "running"), Stream.runHead));
      }).pipe(Effect.scoped));
      await input.focus();
      await browser.keyboard.type("echo marker-one");
      await browser.keyboard.press("Enter");
      await runPromise(Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        yield* client["terminal.observe"]({ threadId, terminalId: terminal.terminalId }).pipe(
          Stream.filter((e) => e.type === "snapshot" ? e.snapshot.history.includes("marker-one\r\n") : e.type === "output" && e.data.includes("marker-one")),
          Stream.runHead);
      }).pipe(Effect.scoped));
      await app.screenshot(`${mode}-marker-before-close`);
      await screen.getByRole("button", "Add panel surface").tap();
      await screen.getByRole("menuitem", /^Files/).tap();
      await screen.getByRole("treeitem", "package.json").tap();
      await input.waitFor({ state: "hidden" });
      await screen.getByText(/terminal-proof/).waitFor({ state: "visible" });
      if (mode !== "hidden-file") {
        await navigate(away.threadId);
        await app.screenshot(`${mode}-away-before-close`);
      }
      // A second independent WebSocket connection performs the drawer's real close RPC.
      await runPromise(Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        yield* client["terminal.close"]({ threadId, terminalId: terminal.terminalId, deleteHistory: true });
      }).pipe(Effect.scoped));
      if ((await listed(threadId)).some((t) => t.terminalId === terminal.terminalId)) throw new Error("Close did not remove server terminal");
      if (mode === "reload") {
        // Reload while away: the original thread's observations must survive document teardown.
        await browser.reload();
        await browser.locator(`[data-sidebar-row$="${away.threadId}"]`).waitFor();
      }
      if (mode !== "hidden-file") await navigate(threadId);
      await screen.getByText(/terminal-proof/).waitFor({ state: "visible" });
      if (mode === "reload") {
        await app.screenshot("reload-return-before-reloading-original-thread");
        await browser.reload();
        await screen.getByText(/terminal-proof/).waitFor({ state: "visible" });
      }
      const tab = screen.getByRole("button", terminal.label, { exact: true });
      try { await expect(tab).toBeHidden({ timeout: 4_000 }); outcomes[mode] = true; }
      catch { outcomes[mode] = false; }
      await app.screenshot(`${mode}-after-remote-close`);
      if (await tab.isVisible()) {
        await tab.tap();
        await input.waitFor({ state: "visible" });
        await runPromise(Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl);
          yield* client.subscribeTerminalMetadata({}).pipe(
            Stream.flatMap((e) => Stream.fromIterable(e.type === "snapshot" ? e.terminals : e.type === "upsert" ? [e.terminal] : [])),
            Stream.filter((t) => t.threadId === threadId && t.terminalId === terminal.terminalId && t.status === "running"), Stream.runHead);
        }).pipe(Effect.scoped));
        await app.screenshot(`${mode}-stale-tab-resurrected-shell`);
      } else {
        await app.screenshot(`${mode}-no-stale-tab-to-select`);
      }
    }
    expect(outcomes).toEqual({ "hidden-file": true, "thread-return": true, reload: true });
  });
