import { expect, test } from "@playwright/test";
import { gotoLiveView, projectEmail, registerAndConfirm } from "./helpers";

test("a disconnected LiveView announces recovery and clears it after reconnect", async ({
  browser,
  request,
}, testInfo) => {
  const user = await registerAndConfirm(
    browser,
    request,
    projectEmail("resilience", testInfo.project.name),
    "E2E Resilience",
  );

  await gotoLiveView(user.page, "/requests");
  await expect
    .poll(() =>
      user.page.evaluate(() => {
        const liveSocket = (
          window as typeof window & {
            liveSocket?: { isConnected: () => boolean };
          }
        ).liveSocket;
        return liveSocket?.isConnected() ?? false;
      }),
    )
    .toBe(true);
  await user.context.setOffline(true);
  await user.page.evaluate(() => {
    const liveSocket = (
      window as typeof window & {
        liveSocket?: { socket?: { conn?: { close: () => void } } };
      }
    ).liveSocket;
    liveSocket?.socket?.conn?.close();
  });
  await expect(user.page.getByText("We can't find the internet")).toBeVisible();
  await expect(user.page.getByText("Attempting to reconnect").first()).toBeVisible();

  await user.context.setOffline(false);
  await user.page.evaluate(() => {
    const liveSocket = (
      window as typeof window & {
        liveSocket?: { connect: () => void };
      }
    ).liveSocket;
    liveSocket?.connect();
  });
  await expect(user.page.getByText("We can't find the internet")).toBeHidden();
  await expect(user.page.getByRole("heading", { name: "Who needs help?" })).toBeVisible();

  await user.context.close();
});
