import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

function reportPdf() {
  const objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [" + Array.from({length:8},(_,i)=>`${4+i*2} 0 R`).join(" ") + "] /Count 8 >>", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"];
  for(let i=0;i<8;i++) {
    objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${5+i*2} 0 R >>`);
    const text = `BT /F1 24 Tf 60 710 Td (Synthetic quarterly report - Page ${i+1}) Tj /F1 12 Tf 0 -60 Td (PDF attachment preview continuity demonstration) Tj ET\n` + Array.from({length:35},(_,j)=>`BT /F1 11 Tf 60 ${610-j*14} Td (Section ${i+1}.${j+1} - Sample report data for preview verification.) Tj ET\n`).join("");
    objects.push(`<< /Length ${text.length} >>\nstream\n${text}endstream`);
  }
  let pdf="%PDF-1.4\n"; const offsets=[0];
  objects.forEach((obj,i)=>{offsets.push(pdf.length);pdf+=`${i+1} 0 obj\n${obj}\nendobj\n`;});
  const xref=pdf.length;
  pdf+=`xref\n0 ${objects.length+1}\n0000000000 65535 f \n`+offsets.slice(1).map(n=>`${String(n).padStart(10,"0")} 00000 n \n`).join("")+`trailer\n<< /Size ${objects.length+1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
  return pdf;
}

test("Sent PDF stays mounted while an unrelated command runs", WEB, async ({t3,app,browser,screen})=>{
  const project=await t3.project("pdf-demo");
  const thread=await t3.thread({project,title:"PDF report",messages:["Ready"],model:"command-output"});
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read this report");
  await browser.evaluate((pdf)=>{
    const data=new DataTransfer(); data.items.add(new File([pdf],"report.pdf",{type:"application/pdf"}));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
  },reportPdf());
  await screen.getByRole("textbox").press("Enter");
  await browser.evaluate(async()=>{
    const until=Date.now()+30000;
    while(!Array.from(document.querySelectorAll('button')).some(b=>b.textContent?.includes('report.pdf')) || document.querySelector('[aria-label="Stop generation"]')) {
      if(Date.now()>until) throw Error("STEP_TIMEOUT: attachment turn did not finish");
      await new Promise(r=>setTimeout(r,100));
    }
  });
  await screen.getByRole("button","report.pdf",{exact:false}).first().tap();
  await browser.evaluate(async()=>{
    const until=Date.now()+30000;
    while(!document.querySelector('[role="region"][aria-label="report.pdf"] canvas')){
      if(Date.now()>until) throw Error("STEP_TIMEOUT: PDF canvas did not render");
      await new Promise(r=>setTimeout(r,100));
    }
    const node=document.querySelector('[role="region"][aria-label="report.pdf"]')!;
    node.scrollTop=2500;
  });
  await app.screenshot("pdf-before-command");
  await browser.evaluate(()=>{
    const node=document.querySelector('[role="region"][aria-label="report.pdf"]')!;
    const state={node,remounted:false,loading:0};
    (window as any).pdfProof=state;
    new MutationObserver(()=>{
      if(!node.isConnected) state.remounted=true;
      if(Array.from(document.querySelectorAll('[role="status"]')).some(n=>n.textContent?.includes('Loading file'))) state.loading++;
    }).observe(document.body,{childList:true,subtree:true});
  });
  await screen.getByRole("textbox").fill("run ls");
  await screen.getByRole("textbox").press("Enter");
  await browser.evaluate(async()=>{
    await new Promise(r=>setTimeout(r,5000));
    const until=Date.now()+30000;
    while(document.querySelector('[aria-label="Stop generation"]')){
      if(Date.now()>until) throw Error("STEP_TIMEOUT: command did not finish");
      await new Promise(r=>setTimeout(r,100));
    }
  });
  await app.screenshot("pdf-after-command");
  const result=await browser.evaluate(()=>{
    const s=(window as any).pdfProof;
    return {remounted:s.remounted,loading:s.loading,scroll:document.querySelector('[role="region"][aria-label="report.pdf"]')?.scrollTop};
  });
  expect(result).toEqual({remounted:false,loading:0,scroll:2500});
});
