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

test("A workflow run uses the ordinary resizable right panel", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1920,height:1000});
  const project = await t3.project("Release review");
  let thread: {threadId:string} | undefined;
  await expect.poll(async()=>{
    try {thread=await t3.thread({project,title:"Release reference",messages:["Review the release"],model:"multi-turn"});return true;}catch(e){if(!String(e).includes("not advertised"))throw e;return false;}
  }).toBe(true);
  await runPromise(Effect.gen(function*(){
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`,{recursive:true});
    yield* fs.writeFileString(`${T3_HOME}/workflows/ask-demo.ts`, `const {workflow,step,ask,title}=T3;
export default workflow("ask-demo",{version:1,payload:Schema.Struct({name:Schema.String})},Effect.fn(function*(payload){
 yield* title("Review "+payload.name);
 yield* step("Prepare release · Validate change",{returns:Schema.String},Effect.succeed("Validation complete: the release notes, compatibility checks and rollback plan are ready for review."));
 yield* step("Check release notes",{returns:Schema.String},Effect.succeed("All checks passed."));
 return yield* ask("review",{title:"Review "+payload.name+": The release includes the workflow panel changes. Please review the validation output, confirm the release notes describe the new behaviour, and decide whether to ship now, request changes, or hold for a follow-up review.",choices:["Ship now","Request changes","Hold for review"]});
}));`);
    const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
    yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}});
  }).pipe(Effect.scoped));
  await t3.open("/workflows");
  await screen.getByRole("button","Definitions",{exact:true}).waitFor();
  await app.screenshot("no-selected-run");
  const cli=makeState(T3_HOME).cli;
  let id="";
  await expect.poll(async()=>{
    try {const r=JSON.parse((await runPromise(cli(["workflow","start","ask-demo","--input",'{"name":"PR 123"}',"--key","demo1","--json"]))).stdout); id=r.run.runId; return id;}catch{return "";}
  }).not.toBe("");
  await t3.open(`/workflows?run=${id}`);
  await screen.getByRole("button","Ship now",{exact:true}).waitFor();
  await app.screenshot("selected-run-default-width");
  const handles=()=>browser.evaluate(()=>[...document.querySelectorAll('[role="separator"][aria-orientation="vertical"]')].filter(e=>e.getAttribute("aria-label")!=="Resize Sidebar").map(e=>{const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};}));
  const initial=await handles();
  if(initial[0]) {
    await browser.mouse.move(initial[0].x,initial[0].y);await browser.mouse.down();
    for(let n=1;n<=10;n++) await browser.mouse.move(initial[0].x-n*30,initial[0].y);
    await browser.mouse.up();
  }
  await app.screenshot("run-panel-widened");
  await t3.open(`/workflows?run=${id}&pane=${encodeURIComponent(JSON.stringify([{thread:thread!.threadId}]))}`);
  await screen.getByRole("complementary","Beside the run").waitFor();
  await app.screenshot("run-and-thread-pane");
  const both=await handles();
  if(both.at(-1)) {
    const handle=both.at(-1)!;
    await browser.mouse.move(handle.x,handle.y); await browser.mouse.down();
    for(let n=1;n<=8;n++) await browser.mouse.move(handle.x-n*20,handle.y);
    await browser.mouse.up();
  }
  await app.screenshot("thread-pane-widened");
  await browser.setViewport({width:700,height:1000});
  await app.screenshot("narrow-run-and-thread-pane");
  await browser.setViewport({width:1920,height:1000});
  await t3.open(`/workflows?run=${id}`);
  await screen.getByRole("button","Ship now",{exact:true}).waitFor();
  await app.screenshot("remembered-run-width");
  await browser.keyboard.press("Control+Alt+b");
  await app.screenshot("keyboard-panel-closed");
  await browser.keyboard.press("Control+Alt+b");
  await app.screenshot("keyboard-panel-reopened");
  await browser.keyboard.press("Control+w");
  await app.screenshot("keyboard-close-command");
  await t3.open(`/workflows?run=${id}`);
  await screen.getByRole("button","Ship now",{exact:true}).waitFor();
  await browser.setViewport({width:700,height:1000});
  await app.screenshot("narrow-selected-run");
  await browser.setViewport({width:1920,height:1000});
  await t3.open(`/workflows?run=${id}`);
  await screen.getByRole("button","Ship now",{exact:true}).waitFor();
  await expect.poll(async()=> (await handles()).length).toBeGreaterThan(0);
});
