import { expect } from "e2e";
import { writeFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Full-screen HTML fits content and reflows at every zoom", WEB, async ({t3,app,screen,browser}) => {
  await browser.setViewport({width:1920,height:1080});
  const project = await t3.project("Visual pages");
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  for (const [index,title] of ["Tall slide", "Short page"].entries()) {
    const attachmentId = `visual-${index === 0 ? '11111111' : '22222222'}-1111-4111-8111-111111111111-html`;
    const html = `<!doctype html><html><head><meta charset="utf-8"><style>*{box-sizing:border-box}html{background:#152335;color:#eef3fa;font:18px/1.6 system-ui}body{margin:0;padding:32px}h1{font-size:36px;margin:0 0 16px}.slide{height:900px;background:linear-gradient(145deg,#206c86,#243c70);padding:40px;border-radius:16px;display:flex;flex-direction:column;justify-content:space-between}button{font:inherit;padding:10px 24px;color:white;background:#246d87;border:1px solid #9edbef;border-radius:8px}nav{display:flex;justify-content:space-between;margin-top:24px}</style></head><body><h1>${title}</h1><p>Full-screen reading should use a comfortable width. Zoom should reflow this paragraph across the card, preserving every word and keeping navigation reachable beneath the slide. Compare the line breaks and the right edge at each zoom level.</p>${index === 0 ? '<section class="slide"><h2>A tall visual story</h2><div>Explore the whole page<br>Navigation follows below ↓</div></section><nav><button>← Previous</button><button>Next →</button></nav>' : '<p>A compact page needs a compact card.</p>'}<script>const report=()=>parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{height:document.documentElement.scrollHeight}},'*');new ResizeObserver(report).observe(document.body);addEventListener('load',report);</script></body></html>`;
    await mkdir(join(T3_HOME,"userdata/attachments"),{recursive:true});
    await writeFile(join(T3_HOME,"userdata/attachments",attachmentId+".html"),html);
    const update = (update: unknown) => frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update}}});
    update({sessionUpdate:"tool_call",toolCallId:`page-${index}`,kind:"other",title:"t3-code.html_render",status:"pending",rawInput:{title}});
    update({sessionUpdate:"tool_call_update",toolCallId:`page-${index}`,status:"completed",rawOutput:{htmlRender:{attachmentId,title,height:index===0?1400:240}}});
  }
  frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Two visual pages are ready."}}}}});
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  await writeFile(join(APP_DIR,"apps/server/scripts/dev-replay/showcase_transcript.ndjson"),frames.map(x=>JSON.stringify(x)).join('\n')+'\n');
  await t3.thread({project,title:"HTML reading",messages:["Publish tall and short visual pages"],model:"showcase"});
  await t3.open();
  await screen.getByRole("button", "HTML reading, Done, Visual pages").tap();
  await screen.getByRole("button","Open full screen").first().tap();
  await app.screenshot("tall-100-percent");
  const widths: number[]=[];
  const measure = () => browser.evaluate(() => {const f=document.querySelector('[role="dialog"] iframe') as HTMLIFrameElement;return f.getBoundingClientRect().width;});
  widths.push(await measure());
  await screen.getByRole("button","Zoom out").tap();
  await screen.getByRole("button","Zoom out").tap();
  await app.screenshot("tall-50-percent"); widths.push(await measure());
  await screen.getByRole("button","Reset zoom").tap();
  for(let i=0;i<2;i++) await screen.getByRole("button","Zoom in").tap();
  await app.screenshot("tall-150-percent"); widths.push(await measure());
  for(let i=0;i<2;i++) await screen.getByRole("button","Zoom in").tap();
  await app.screenshot("tall-200-percent"); widths.push(await measure());
  await browser.evaluate(()=>{const f=document.querySelector('[role="dialog"] iframe')!;let p=f.parentElement!;while(p && !['auto','scroll'].includes(getComputedStyle(p).overflowY))p=p.parentElement!;p.scrollTop=p.scrollHeight;});
  await app.screenshot("tall-bottom-navigation");
  await screen.getByRole("button","Close",{exact:true}).tap();
  await screen.getByRole("button","Open full screen").nth(1).tap();
  await app.screenshot("short-100-percent");
  const shortHeight=await browser.evaluate(()=>document.querySelector('[role="dialog"] iframe')!.getBoundingClientRect().height);
  expect(Math.max(...widths)-Math.min(...widths)).toBeLessThan(4);
  expect(widths[0]).toBeLessThanOrEqual(1144);
  expect(shortHeight).toBeLessThan(400);
});
