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

test("Folder actions keep their height and receive mouse clicks", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1280,height:800});
  await browser.emulateMedia({colorScheme:"dark"});
  const project = await t3.project("demo-project");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const alpha = await t3.thread({project,title:"Alpha task",messages:["Hello"]});
  await t3.thread({project,title:"Beta task",messages:["Hello"]});
  await t3.thread({project,title:"Gamma task",messages:["Hello"]});
  await t3.thread({project,title:"Delta task",messages:["Hello"]});
  await t3.open("/settings/labs");
  await screen.getByRole("switch", "Boring sidebar (group by project)").check();
  await t3.open(alpha);
  const click = async (x:number,y:number) => {
    await browser.mouse.move(x,y); await browser.mouse.down(); await browser.mouse.up();
  };
  const pause = async (ms=800) => browser.evaluate(async(ms)=>{await new Promise(r=>setTimeout(r,ms));return null;},ms);
  const note = async (text:string) => browser.evaluate(text=>{
    let box = document.getElementById("proof-measurements");
    if(!box){box=document.createElement("pre");box.id="proof-measurements";document.body.append(box);}
    box.style.cssText="position:fixed;left:280px;top:320px;z-index:99999;background:#142033;color:white;border:1px solid #526985;padding:16px;font:15px/1.7 monospace;pointer-events:none;max-width:650px;white-space:pre-wrap";
    box.textContent="Live DOM measurements (capture annotation)\n"+text;return null;
  },text);
  const row = (name:string) => browser.locator('[data-testid="sidebar-row-folder"]').filter({hasText:name});
  await row("Beta task").waitFor();
  const geometry = async (name:string, action:string) => browser.evaluate(({name,action}) => {
  const row = [...document.querySelectorAll('[data-testid="sidebar-row-folder"]')].find(e=>e.textContent?.includes(name))!;
    const b = row.querySelector(`[aria-label="${action}"]`)!;
    const r=b.getBoundingClientRect();
    return {x:r.x+r.width/2,y:r.y+r.height/2,top:r.top,height:r.height};
  },{name,action});
  const betaRect = await geometry("Beta task","Snooze thread");
  await browser.mouse.move(betaRect.x-80,betaRect.y);
  await pause();
  const heights = [await geometry("Beta task","Snooze thread"),await geometry("Beta task","Settle thread")];
  const hit = await browser.evaluate(()=>{
    const r=[...document.querySelectorAll('[data-testid="sidebar-row-folder"]')].find(e=>e.textContent?.includes("Beta task"))!;
    return [...r.querySelectorAll('button[aria-label]')].map(b=>{const x=b.getBoundingClientRect();const target=document.elementFromPoint(x.x+x.width/2,x.y+x.height/2);return `${b.getAttribute("aria-label")}: ${x.width} x ${x.height}px; hit: ${target?.closest("button")?.getAttribute("aria-label") ?? target?.textContent}`;}).join("\n");
  });
  await note(hit);
  await app.screenshot("beta-hover-actions");
  // Approach the clock one pixel below its current top and hold through the recording.
  await browser.mouse.move(500,300);
  const clockUnhovered=await geometry("Beta task","Snooze thread");
  await browser.mouse.move(clockUnhovered.x,clockUnhovered.top+1);
  const edge = await browser.evaluate(async()=>{
    const row=[...document.querySelectorAll('[data-testid="sidebar-row-folder"]')].find(e=>e.textContent?.includes("Beta task"))!;
    const button=row.querySelector('[aria-label="Snooze thread"]')!;
    const samples:number[]=[];let changes=0;let last="";
    const until=performance.now()+2000;
    while(performance.now()<until){await new Promise(requestAnimationFrame);const r=button.getBoundingClientRect();const key=`${r.top},${r.height}`;if(last && key!==last)changes++;last=key;samples.push(r.height);}
    return {changes,heights:[...new Set(samples)]};
  });
  await note(`Clock top edge: pointer held at y=${clockUnhovered.top+1} for 2 seconds\nGeometry changes: ${edge.changes}; sampled heights: ${edge.heights.join(", ")}px`);
  await app.screenshot("clock-top-edge");
  const settle = await geometry("Beta task","Settle thread");
  await click(settle.x,settle.y);
  await pause();
  const betaSettled = await browser.locator('[data-testid="sidebar-settled-header"]').textContent();
  await note(`Clicked Beta Settle with mouse\n${betaSettled}\nCurrent thread: ${await browser.url().then(u=>u.includes(alpha.threadId)?"Alpha task":"Beta task")}`);
  await app.screenshot("beta-after-settle-click");
  await t3.open(alpha);
  await row("Gamma task").waitFor();
  const gamma = await geometry("Gamma task","Snooze thread");
  await browser.mouse.move(gamma.x-80,gamma.y);
  const snooze = await geometry("Gamma task","Snooze thread");
  await click(snooze.x,snooze.y);
  // Capture after allowing the menu's opening animation to finish, on both commits.
  await browser.evaluate(async()=>{await new Promise(r=>setTimeout(r,800)); return null;});
  const menuOpened = await browser.locator('[role="menu"]').count();
  await note(`Clicked Gamma Snooze with mouse\nSnooze menus open: ${menuOpened}`);
  await app.screenshot("gamma-after-snooze-click");
  await pause(1200);
  await browser.keyboard.press("Escape");
  // Prepare reverse-state rows through keyboard actions on both sides, independently of mouse defects.
  await t3.open(alpha);
  await row("Delta task").waitFor();
  const focusAction = async (name:string,action:string) => {
    await browser.evaluate(({name,action})=>{
      const r=[...document.querySelectorAll('[data-testid="sidebar-row-folder"]')].find(e=>e.textContent?.includes(name))!;
      (r.querySelector(`[aria-label="${action}"]`) as HTMLElement).focus();return null;
    },{name,action});
    await browser.keyboard.press("Enter");await pause();
  };
  await focusAction("Delta task","Settle thread");
  await focusAction("Gamma task","Snooze thread");
  await browser.locator('[role="menuitem"]').first().tap();
  await pause();
  for(const shelf of ["snoozed","settled"]){
    const toggle=browser.locator(`[data-testid="sidebar-${shelf}-shelf-toggle"]`);
    if(await toggle.getAttribute("aria-expanded")==="false") await toggle.tap();
  }
  await pause();
  const widths=[];
  for(const name of ["Gamma task","Delta task"]){
    const measure = async()=>browser.evaluate(name=>{
      const r=[...document.querySelectorAll('[data-testid="sidebar-row-folder"]')].find(e=>e.textContent?.includes(name))!;
      const title=[...r.querySelectorAll("span")].find(e=>e.getAttribute("dir") && e.textContent===name)!;
      return title.getBoundingClientRect().width;
    },name);
    await browser.mouse.move(500,300);await pause();
    const normal=await measure();
    await note(`${name} in ${name==="Gamma task"?"Snoozed":"Settled"}\nTitle width, not hovered: ${normal}px`);
    await app.screenshot(`${name.split(" ")[0].toLowerCase()}-reverse-idle`);
    const action=name==="Gamma task"?"Wake thread now":"Un-settle thread";
    const rect=await geometry(name,action);
    await browser.mouse.move(rect.x-80,rect.y);await pause();
    const hovered=await measure();widths.push({normal,hovered});
    await note(`${name} in ${name==="Gamma task"?"Snoozed":"Settled"}\nTitle width idle: ${normal}px; hovered: ${hovered}px\nChange: ${hovered-normal}px`);
    await app.screenshot(`${name.split(" ")[0].toLowerCase()}-reverse-hover`);
  }
  expect(heights.map(b=>b.height)).toEqual([24,24]);
  expect(menuOpened).toBe(1);
  expect(betaSettled).toContain("1");
  expect(widths.every(w=>w.normal===w.hovered)).toBe(true);
  expect(edge.changes).toBe(0);
});
