import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Opening a cached unread thread offline retries its visit after reconnect", WEB, async ({ t3, app, screen, browser }) => {
  // Block only the app's WebSocket transport; HTTP and Vite remain available.
  await browser.addInitScript(() => {
    const Native = window.WebSocket;
    const sockets = new Set<WebSocket>();
    const state = { offline: false, sockets };
    Object.assign(window, { scenarioNetwork: state });
    window.WebSocket = class extends Native {
      constructor(url: string | URL, protocols?: string | string[]) {
        const parsed = new URL(String(url), location.href);
        const appSocket = parsed.pathname.startsWith("/ws");
        if (appSocket && state.offline) parsed.port = "1";
        super(parsed, protocols);
        if (appSocket) sockets.add(this);
      }
    };
  });
  const project = await t3.project("Reconnect demo");
  const target = await t3.thread({ project, title: "Unread completed work", messages: ["Complete this task"] });
  const other = await t3.thread({ project, title: "Observer workspace", messages: ["Keep this thread selected"] });
  await t3.open(other);
  const row = screen.getByRole("button", "Unread completed work", { exact: false });
  await row.waitFor({ state: "visible" });
  await app.screenshot("cached-unread");
  await browser.evaluate(() => {
    const state = (window as any).scenarioNetwork;
    state.offline = true;
    for (const socket of state.sockets) socket.close();
  });
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2500)));
  await row.tap();
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2500)));
  await app.screenshot("opened-offline");
  await browser.evaluate(() => { (window as any).scenarioNetwork.offline = false; });
  // Leave the same completed thread selected and allow the real 10-second throttle to expire.
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 18000)));
  await app.screenshot("reconnected-selected");
  // A freshly loaded client reads server state, after selecting a different thread so it
  // cannot itself mark the target read. No thread activity is generated.
  await screen.getByRole("button", "Observer workspace", { exact: false }).tap();
  await browser.reload();
  await screen.getByRole("button", "Unread completed work", { exact: false }).waitFor({ state: "visible" });
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2500)));
  await app.screenshot("server-read-state");
  await expect(screen.getByRole("button", "Unread completed work", { exact: false })).not.toContainText("Done");
});
