import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("A mouse notch glides over the minimap like the chat", WEB, async ({t3, app, browser}) => {
  const project = await t3.project("Wheel demo");
  const thread = await t3.thread({project, title:"Fourteen turns", messages:Array.from({length:14}, (_,i)=>`Explain step ${i+1} of the sample project.`)});
  await t3.open(thread);
  await browser.locator('[data-testid="timeline-minimap"]').waitFor({state:"visible"});
  const results = [];
  for (let repeat=0; repeat<3; repeat++) {
    for (const area of ["chat", "minimap"]) {
      const point = await browser.evaluate((area) => {
        const scroller = document.querySelector<HTMLElement>('.messages-timeline-scroll')!;
        scroller.scrollTop = (scroller.scrollHeight-scroller.clientHeight)/2;
        const strip=document.querySelector<HTMLElement>('[data-testid="timeline-minimap"] button[aria-label^="Jump to message:"]') ?? document.querySelector<HTMLElement>('[data-testid="timeline-minimap"] button')!;
        const r=(area==='chat'?scroller:strip).getBoundingClientRect();
        return {x: Math.round(area==='chat'?r.x+r.width/2:r.x+r.width/2), y:Math.round(r.y+r.height/2), offset:window.outerHeight-window.innerHeight, sx:window.screenX,sy:window.screenY};
      }, area);
      execFileSync('xdotool', ['mousemove', String(point.sx+point.x),String(point.sy+point.offset+point.y)]);
      await browser.evaluate(async () => {await new Promise(r=>setTimeout(r,400));});
      await browser.evaluate((area) => {
        const s=document.querySelector<HTMLElement>('.messages-timeline-scroll')!;
        const w=window as any;
        w.wheelSample={area,start:s.scrollTop,positions:[],events:[],height:s.scrollHeight,viewport:s.clientHeight};
        const sample=w.wheelSample;
        const handler=(e:WheelEvent)=>sample.events.push({trusted:e.isTrusted,deltaY:e.deltaY,wheelDeltaY:(e as any).wheelDeltaY,minimap:!!(e.target as Element)?.closest('[data-testid="timeline-minimap"]')});
        document.addEventListener('wheel',handler,true);
        let last=s.scrollTop;
        const start=performance.now();
        const frame=()=>{if(s.scrollTop!==last){sample.positions.push({ms:Math.round(performance.now()-start),delta:s.scrollTop-last});last=s.scrollTop;} if(performance.now()-start<800)requestAnimationFrame(frame);else {sample.end=s.scrollTop;document.removeEventListener('wheel',handler,true);}};
        requestAnimationFrame(frame);
      },area);
      execFileSync('xdotool',['click','5']);
      const sample=await browser.evaluate(async()=>{await new Promise(r=>setTimeout(r,1000));return (window as any).wheelSample;});
      results.push(sample);
      await browser.evaluate((sample)=>{
        let hud=document.getElementById('wheel-proof');
        if(!hud){hud=document.createElement('pre');hud.id='wheel-proof';hud.style.cssText='position:fixed;right:24px;top:90px;z-index:99999;background:#111;color:#fff;padding:16px;border:1px solid #777;font:14px monospace;pointer-events:none';document.body.append(hud);}
        hud.textContent=`Real X11 mouse wheel — ${sample.area}\nScroll range: ${sample.height} / ${sample.viewport}\n${JSON.stringify(sample.events)}\nFrames: ${sample.positions.length}\nDeltas: ${sample.positions.map((p:any)=>p.delta).join(', ')}\nDistance: ${sample.end-sample.start}px`;
      },sample);
      await app.screenshot(`${area}-${repeat+1}`);
    }
  }
  console.log('WHEEL_RESULTS',JSON.stringify(results));
  await expect(results.filter((r:any)=>r.area==='minimap').every((r:any)=>r.positions.length>1 && r.events.some((e:any)=>e.trusted&&e.minimap))).toBe(true);
});
