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

test("Cancelling issue editors returns keyboard focus to the activated Edit button", WEB, async ({t3, app, browser, screen}) => {
  const workspaceRoot = await t3.project("focus-proof");
  const thread = await t3.thread({project:workspaceRoot,title:"Keyboard focus proof",model:"default",messages:["Ready"]});
  const projectId = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client["issueTrackers.connect"]({tracker:"linear",token:process.env.LINEAR_API_KEY!});
    const item = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if(item._tag !== "Some" || item.value.kind !== "snapshot") throw new Error("No snapshot");
    const project = item.value.snapshot.projects.find(p=>p.workspaceRoot===workspaceRoot)!;
    yield* client["issueTrackers.bindProject"]({projectId:project.id,binding:{tracker:"linear",scope:"T3CF"}});
    return project.id;
  }).pipe(Effect.scoped));
  await t3.open(thread);
  await t3.open(`/issues?selectedProjectId=${projectId}&tracker=linear&scope=T3CF&key=T3CF-1079`);
  const results = [];
  for(const [field, cancel, tabs] of [["title","Escape",0],["title","Enter",2],["description","Escape",0],["description","Enter",1]] as const){
    const button = screen.getByRole("button",`Edit ${field}`,{exact:true});
    await button.waitFor();
    await browser.evaluate((label)=>{(document.querySelector(`button[aria-label="${label}"]`) as HTMLButtonElement).focus();return null;},`Edit ${field}`);
    await browser.keyboard.press("Enter");
    await screen.getByRole("textbox",field === "title" ? "Issue title" : "Description",{exact:true}).waitFor();
    for(let i=0;i<tabs;i++) await browser.keyboard.press("Tab");
    await browser.keyboard.press(cancel);
    await button.waitFor();
    await app.screenshot(`${field}-${cancel}-cancel-focus`);
    results.push(await browser.evaluate((label)=>({field:label,focus:document.activeElement?.getAttribute("aria-label"),panelOpen:!!document.querySelector('button[aria-label="Edit title"]')}),`Edit ${field}`));
  }
  expect(results).toEqual(["Edit title","Edit title","Edit description","Edit description"].map(field=>({field,focus:field,panelOpen:true})));
});
