/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { ProjectSnapshot } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.ts";

test("Different tabs preserve both pull request comment drafts", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({ reducedMotion: "reduce" });
  const settle = async () => {
    await browser.locator('[role="status"][aria-label^="Loading pull requests"]').waitFor({state:"hidden", timeout:120000});
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
      return null;
    });
  };
  const workspace = await t3.project("Review drafts");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd: workspace}));
  const origin = app.baseUrl!;
  const environment = await runPromise(environmentId(origin));
  const project = await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const {projects} = yield* HttpClient.execute(HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
    return projects.find(p => p.workspaceRoot === workspace)!;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const path = (number: number) => `/pull-requests?${new URLSearchParams({repository: "pingdotgg/t3code", number: String(number), selectedProjectId: project.id, selectedEnvironmentId: environment, selectedHost: "github.com"})}`;
  await t3.open(path(47774));
  await screen.getByRole("button", "Comment on pull request", {exact:true}).waitFor({timeout: 120000});
  await browser.evaluate(() => {localStorage.removeItem("t3code:pull-request-review-drafts:v1"); return null;});
  await browser.reload();
  await screen.getByRole("button", "Comment on pull request", {exact:true}).waitFor();
  // Open A before either tab edits, so both stores start empty.
  await browser.evaluate(async (path) => {
    const tab = window.open(path, "draft-tab-a")!;
    (window as any).draftTabA = tab;
    await new Promise<void>((resolve, reject) => {
      const timer = setTimeout(() => reject(new Error("Tab A did not load")), 120000);
      const ready = () => {
        if (!tab.document.querySelector('button[aria-label="Comment on pull request"]')) return;
        clearTimeout(timer); resolve(); return true;
      };
      tab.addEventListener("load", () => {
        if (ready()) return;
        const observer = new tab.MutationObserver(() => { if (ready()) observer.disconnect(); });
        observer.observe(tab.document, {childList:true, subtree:true});
      });
    });
    return null;
  }, path(47941));
  await screen.getByRole("button", "Comment on pull request", {exact:true}).tap();
  await screen.getByRole("combobox", "Comment on this pull request", {exact:true}).fill("Unsent comment on B (#47774)");
  await settle();
  await app.screenshot("b-draft-saved-before-a-edits");
  await browser.evaluate(async () => {
    const tab = (window as any).draftTabA as Window;
    (tab.document.querySelector('button[aria-label="Comment on pull request"]') as HTMLButtonElement).click();
    const field = await new Promise<HTMLTextAreaElement>(resolve => {
      const find = () => tab.document.querySelector('textarea[aria-label="Comment on this pull request"]') as HTMLTextAreaElement | null;
      if (find()) return resolve(find()!);
      const observer = new tab.MutationObserver(() => { if (find()) {observer.disconnect(); resolve(find()!);} });
      observer.observe(tab.document, {childList:true, subtree:true});
    });
    Object.getOwnPropertyDescriptor(tab.HTMLTextAreaElement.prototype, "value")!.set!.call(field, "Unsent comment on A (#47941)");
    field.dispatchEvent(new tab.Event("input", {bubbles:true}));
    field.dispatchEvent(new tab.Event("change", {bubbles:true}));
    return null;
  });
  await browser.reload();
  await screen.getByRole("button", "Comment on pull request", {exact:true}).tap();
  const field = screen.getByRole("combobox", "Comment on this pull request", {exact:true});
  await field.waitFor();
  await settle();
  await app.screenshot("b-draft-after-a-saves-and-b-reloads");
  const persisted = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:pull-request-review-drafts:v1")!).state.commentBodies);
  expect(Object.values(persisted)).toContain("Unsent comment on A (#47941)");
  await expect(field).toHaveValue("Unsent comment on B (#47774)");
  await browser.evaluate(() => { (window as any).draftTabA?.close(); return null; });
});
