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

test("Queued Edit swaps immediately and closes after leaving and removing its trigger", WEB, async ({t3, app, browser, screen}) => {
  await runPromise(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* rpc["server.updateSettings"]({patch:{defaultRuntimeMode:"approval-required"}});
  }).pipe(Effect.scoped));
  const project = await t3.project("Tooltip demonstration");
  const question = await t3.thread({project,title:"Question queue",messages:["Ask a question"],model:"question"});
  const approval = await t3.thread({project,title:"Approval queue",messages:["Change the file"],model:"approval"});
  const cli = makeState(T3_HOME).cli;
  for (const thread of [question,approval]) await runPromise(cli(["thread","send",thread.threadId,"Queued follow-up"]));
  const pause = (ms:number) => browser.evaluate((ms) => new Promise<void>(resolve => setTimeout(resolve,ms)), ms);
  const moveTo = async (label:string, wrapper=false) => {
    const point = await browser.evaluate(({label,wrapper}) => {
      const button = document.querySelector(`[aria-label="${label}"]`) ?? Array.from(document.querySelectorAll("button")).find(b => b.textContent?.trim() === label);
      if (!button) throw new Error(`No button ${label}`);
      const rect = (wrapper ? button.parentElement! : button).getBoundingClientRect();
      return {x:rect.x+rect.width/2,y:rect.y+rect.height/2};
    },{label,wrapper});
    await browser.mouse.move(point.x,point.y);
  };
  const popup = () => browser.evaluate(() => Array.from(document.querySelectorAll('[data-slot="tooltip-popup"]')).filter(el => !el.hasAttribute("data-closed") && getComputedStyle(el).opacity !== "0").map(el=>el.textContent).join(" | "));
  const results:Record<string,boolean> = {};
  for (const [kind, thread] of [["disabled",question],["enabled",approval]] as const) {
    await t3.open(thread);
    await screen.getByRole("button","Edit queued message").waitFor();
    const expected = kind === "disabled" ? "Answer the question to edit queued messages" : "Edit in the composer";
    for (const from of kind === "disabled" ? ["Remove queued message"] : ["Remove queued message","Send now"]) {
      await browser.mouse.move(10,10); await pause(800);
      await moveTo(from); await pause(850);
      await app.screenshot(`${kind}-${from}-open`);
      await moveTo("Edit queued message",true);
      await pause(100);
      results[`${kind}-${from}-instant`] = (await popup()).includes(expected);
      await app.screenshot(`${kind}-${from}-to-edit-100ms`);
      await pause(700);
      results[`${kind}-${from}-explanation`] = (await popup()).includes(expected);
      await app.screenshot(`${kind}-${from}-edit-open`);
      await browser.mouse.move(10,10); await pause(850);
      results[`${kind}-${from}-leave-closes`] = (await popup()) === "";
      await app.screenshot(`${kind}-${from}-after-leave`);
    }
    // Exercise the same unmount on both commits while Edit is open.
    await moveTo("Edit queued message",true); await pause(850);
    await screen.getByRole("button","New thread",{exact:false}).first().tap();
    await browser.mouse.move(10,10); await pause(1000);
    results[`${kind}-unmount-closes`] = (await popup()) === "";
    await app.screenshot(`${kind}-empty-thread-after-teardown`);
  }
  await expect(results).toEqual(Object.fromEntries(Object.keys(results).map(key=>[key,true])));
});
