/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

declare global {
 interface Window { destinationRead: { release: () => void; held: boolean } }
}

test("Moved drafts keep explicit choices and wait for an uncached destination before sending", WEB, async ({t3, app, browser, screen}) => {
 await t3.project("source-checkout", {"t3.json": '{"defaultThreadEnvMode":"local"}'});
 await t3.open();
 const picker = browser.locator("[data-draft-project-trigger]");
 const workspace = screen.getByRole("combobox", "Workspace", {exact:true});
 await picker.filter({hasText:"source-checkout"}).waitFor();
 await screen.getByRole("textbox").fill("Keep my explicit checkout choice");
 await workspace.tap();
 await screen.getByRole("option", "New worktree", {exact:true}).tap();
 await workspace.tap();
 await screen.getByRole("option", "Current checkout", {exact:true}).tap();
 await t3.project("explicit-target", {"t3.json": '{"defaultThreadEnvMode":"worktree"}'});
 await picker.tap();
 await screen.getByRole("option", "explicit-target", {exact:true}).tap();
 await picker.filter({hasText:"explicit-target"}).waitFor();
 await expect(workspace).toHaveText("Current checkout");
 await app.screenshot("explicit-checkout-survives-project-move");
 await picker.tap();
 await screen.getByRole("option", "source-checkout", {exact:true}).tap();
 await screen.getByRole("textbox").press("Control+Shift+N");
 await workspace.getByText("Current checkout").waitFor();
 await screen.getByRole("textbox").fill("Plan the implementation after loading the destination default");
 await browser.evaluate(() => {
  const send = WebSocket.prototype.send;
  const queued: Array<() => void> = [];
  window.destinationRead = {held:false, release:()=>{ for(const release of queued) release(); queued.length=0; }};
  WebSocket.prototype.send = function(data) {
   if(typeof data !== "string" || !data.includes('"relativePath":"t3.json"') || !data.includes("inherited-target")) return send.call(this,data);
   const parsed=JSON.parse(data);
   const frames=[parsed].flat();
   const held=frames.filter(f=>f.tag==="projects.readFile" && f.payload?.relativePath==="t3.json" && JSON.stringify(f).includes("inherited-target"));
   if(!held.length) return send.call(this,data);
   const others=frames.filter(f=>!held.includes(f));
   if(others.length) send.call(this, JSON.stringify(others));
   queued.push(()=>send.call(this,Array.isArray(parsed)?JSON.stringify(held):JSON.stringify(held[0])));
   window.destinationRead.held=true;
  };
  return null;
 });
 await t3.project("inherited-target", {"t3.json": '{"defaultThreadEnvMode":"worktree","newWorktreesStartFromOrigin":false}'});
 await picker.tap();
 await screen.getByRole("option", "inherited-target", {exact:true}).tap();
 await picker.filter({hasText:"inherited-target"}).waitFor();
 await screen.getByRole("textbox").press("Enter");
 await app.screenshot("send-while-destination-default-is-held");
 await browser.evaluate(()=>{window.destinationRead.release(); return null;});
 await screen.getByText("Plan the implementation after loading the destination default", {exact:true}).first().waitFor({timeout:60000});
 await screen.getByRole("button", "Stop generation").waitFor({timeout:60000});
 await app.screenshot("sent-draft-workspace");
 await expect(browser.locator('[aria-label^="Run context:"]')).toHaveAttribute("aria-label", /^Run context: Scenario, t3-/);
});
