/// <reference lib="dom" />
import { readFileSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const html = `<style>body{margin:0;font:24px system-ui;color:#e2e8f0;background:#172033}section{height:500px;padding:40px;box-sizing:border-box;border-bottom:2px solid #64748b}h1{font-size:38px}</style>${Array.from({length:12},(_,i)=>`<section style="background:${i%2?'#24344b':'#172033'}"><h1>Tall page — section ${i+1} of 12</h1><p>Thread switching should keep the conversation at its end.</p></section>`).join('')}<footer style="padding:40px;background:#14532d">END OF TALL PAGE</footer>`;

test("Returning to a loaded tall HTML render stays at the end", WEB, async ({ t3, app, screen, browser }) => {
  // Extend only the free replay agent; the page is published by the real html_render MCP tool.
  const agentPath = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  const original = readFileSync(agentPath, "utf8");
  const injected = original.replace('const turns = loadTurns(session.model);', `
    if (session.model === "showcase") {
      const { execFileSync } = await import("node:child_process");
      const result = JSON.parse(execFileSync(process.execPath, [new URL("../src/bin.ts", import.meta.url).pathname, "acp-mcp-call", "html_render", ${JSON.stringify(JSON.stringify({html,title:"Tall HTML page",height:2000}))}], {env:process.env,encoding:"utf8"}));
      const update = (update) => send({method:"session/update",params:{sessionId,update}});
      update({sessionUpdate:"tool_call",toolCallId:"tall-render",kind:"other",title:"t3-code.html_render",status:"completed",rawInput:{},rawOutput:result});
      update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Tall page complete. End of conversation."}});
      return {stopReason:"end_turn"};
    }
    const turns = loadTurns(session.model);`);
  writeFileSync(agentPath, injected);
  try {
    const project = await t3.project("Scroll demonstration");
    const tall = await t3.thread({project,title:"Tall render thread",model:"showcase",messages:["Publish a tall page"]});
    await t3.thread({project,title:"Other thread",messages:["Other work"]});
    await t3.open(tall);
    await browser.locator('iframe[title="Tall HTML page"]').waitFor({state:"attached",timeout:60000});
    await browser.evaluate(async () => {
      await new Promise<void>((resolve,reject)=>{
        const check=()=>{const f=document.querySelector('iframe[title="Tall HTML page"]');if(f && f.getBoundingClientRect().height>5000)resolve();else setTimeout(check,50)};check();setTimeout(()=>reject(new Error("Tall page did not load")),30000);
      });
      const f=document.querySelector('iframe[title="Tall HTML page"]')!;
      let p=f.parentElement!;while(p && !(p.scrollHeight>p.clientHeight && ['auto','scroll'].includes(getComputedStyle(p).overflowY)))p=p.parentElement!;
      p.scrollTop=p.scrollHeight;
      return null;
    });
    await app.screenshot("loaded-at-end");
    const gaps:number[]=[];
    for(let i=0;i<3;i++) {
      await screen.getByRole("button", "Other thread", {exact:false}).tap();
      await browser.evaluate(()=>{(window as any).samples=[];const start=performance.now();const sample=()=>{const f=document.querySelector('iframe[title="Tall HTML page"]');if(f){let p=f.parentElement!;while(p && !(p.scrollHeight>p.clientHeight && ['auto','scroll'].includes(getComputedStyle(p).overflowY)))p=p.parentElement!;if(p)(window as any).samples.push({gap:p.scrollHeight-p.clientHeight-p.scrollTop,height:f.getBoundingClientRect().height});}if(performance.now()-start<2500)requestAnimationFrame(sample)};requestAnimationFrame(sample);return null;});
      await screen.getByRole("button", "Tall render thread", {exact:false}).tap();
      await app.screenshot(`return-${i+1}`);
      const samples=await browser.evaluate(async()=>{await new Promise(r=>setTimeout(r,2700));return (window as any).samples as {gap:number;height:number}[]});
      gaps.push(Math.max(0,...samples.filter(s=>s.height>5000).map(s=>s.gap)));
    }
    await app.screenshot("returned-at-end");
    console.log("RETURN_BOTTOM_GAPS",JSON.stringify(gaps));
    expect(Math.max(...gaps)).toBeLessThan(200);
  } finally {writeFileSync(agentPath,original);}
});
