/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ThreadId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Setup: start-app receives a test-stage Connect credential file and requests a managed link.
// Only the browser clock moves; the server keeps its real 24-hour deadline.
test("Host and guest remain active through the final partial minute", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Guest expiry demo");
  const thread = await t3.thread({ project, title: "Guest expiry boundary", messages: ["Hello guest"], model: "multi-turn" });
  const cli = makeState(T3_HOME, process.env);
  const share = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { guestSharingEnabled: true } });
    // Waiting for the actual tunnel is setup, not an assertion about the expiry bug.
    for (let attempt = 0; attempt < 120; attempt++) {
      const result = yield* client["guestShare.create"]({ threadId: ThreadId.make(thread.threadId) }).pipe(Effect.result);
      if (result._tag === "Success") return result.success;
      yield* Effect.sleep("1 second");
    }
    throw new Error("Connect tunnel never became available for guest share creation");
  }).pipe(Effect.scoped));
  try {
    const capture = async (label: string) => {
      await browser.evaluate((deadline) => {
        const now = Date.now();
        const note = document.getElementById("proof-clock");
        if (note) note.textContent = `Browser UTC ${new Date(now).toISOString()} · server deadline ${deadline} · ${((Date.parse(deadline) - now) / 1000).toFixed(1)}s left`;
      }, share.share.expiresAt);
      await app.screenshot(label);
    };
    const expiresAt = share.share.expiresAt;
    const expiry = Date.parse(expiresAt);
    const minute = Math.floor(expiry / 60_000) * 60_000;
    const start = minute - 30_000;
    const inside = minute + (expiry - minute) / 2;
    await browser.addInitScript(({ start, expiresAt }) => {
      const RealDate = Date;
      let epoch = start;
      let origin = performance.now();
      class BrowserDate extends RealDate {
        constructor(...args: any[]) { super(...(args.length ? args : [epoch + performance.now() - origin]) as [any]); }
        static now() { return Math.floor(epoch + performance.now() - origin); }
      }
      window.Date = BrowserDate as DateConstructor;
      (window as any).setProofClock = (value: number) => { epoch = value; origin = performance.now(); window.dispatchEvent(new Event("focus")); document.dispatchEvent(new Event("visibilitychange")); };
      window.addEventListener("DOMContentLoaded", () => {
        const label = document.createElement("div");
        label.id = "proof-clock";
        label.style.cssText = "position:fixed;bottom:8px;left:8px;z-index:99999;background:#111827;color:white;padding:8px 12px;font:12px monospace;border:1px solid #64748b;border-radius:6px;pointer-events:none";
        label.textContent = `Browser clock advanced for proof · server deadline ${expiresAt}`;
        document.body.append(label);
      });
    }, { start, expiresAt });
    await t3.open(thread);
    const hostUrl = await browser.url();
    await screen.getByText("Guest link active", { exact: true }).waitFor();
    await capture("host-before-expiry-minute");
    const guestUrl = `${app.baseUrl}/guest#${share.url.split("#")[1]}`;
    await browser.goto(guestUrl);
    await screen.getByRole("textbox", "Your name").fill("Guest Tester");
    await screen.getByRole("button", "Join").tap();
    await screen.getByText("Guest expiry boundary", { exact: true }).waitFor();
    await capture("guest-before-expiry-minute");
    const observations: string[] = [];
    // Reload at a fixed instant inside the final partial minute, on both surfaces.
    await browser.addInitScript(({ inside }) => { (window as any).setProofClock(inside); }, { inside });
    await browser.reload();
    await screen.getByText("Guest expiry boundary", { exact: true }).waitFor();
    await capture("guest-before-actual-deadline");
    observations.push(await browser.evaluate(() => document.querySelector("header")?.innerText ?? document.body.innerText));
    await browser.goto(hostUrl);
    await screen.getByRole("button", "Stop sharing").waitFor();
    await capture("host-before-actual-deadline");
    observations.push(await browser.evaluate(() => document.body.innerText.includes("Guest Tester is a guest") ? "host active" : "host expired"));
    await browser.addInitScript(({ expiry }) => { (window as any).setProofClock(expiry + 2000); }, { expiry });
    await browser.reload();
    await screen.getByText("Guest link expired", { exact: true }).waitFor();
    await capture("host-after-actual-deadline");
    await browser.goto(guestUrl.split("#")[0] + "?share=" + share.share.id);
    await screen.getByText("Guest expiry boundary", { exact: true }).waitFor();
    await screen.getByText("Expired", { exact: true }).waitFor();
    await capture("guest-after-actual-deadline");
    expect(observations[0]).toContain("1m left");
    expect(observations[1]).toBe("host active");
  } finally {
    await runPromise(cli.cli(["connect", "logout"]));
  }
});
