/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const notebook = (outputs: unknown[]) => JSON.stringify({nbformat:4, nbformat_minor:5, metadata:{language_info:{name:"python"}}, cells:[{id:"results",cell_type:"code",source:[],metadata:{},execution_count:1,outputs}]});
const html = (text: string) => ({output_type:"display_data",metadata:{},data:{"text/html":text}});
test("Saved outputs retain loading space and every visible result renders", WEB, async ({t3,app,screen,browser}) => {
  await browser.addInitScript(() => {
    const original = Element.prototype.setAttribute;
    const held: Array<[Element,string,string]> = [];
    (window as any).releaseNotebookFrames = () => { for(const [node,name,value] of held) original.call(node,name,value); };
    Element.prototype.setAttribute = function(name,value) {
      if(this.tagName === "IFRAME" && name.toLowerCase() === "srcdoc" && value.includes("reserved space")) {
        held.push([this,name,value]); return;
      }
      original.call(this,name,value);
    };
  });
  const project = await t3.project("Notebook demo", {
    "loading.ipynb":notebook([html('<span>Saved output loading — reserved space</span>'),{output_type:"stream",name:"stdout",text:"Following output — stays below the loading frame"}]),
    "results.ipynb":notebook(Array.from({length:17},(_,i)=>html(`<span>Saved result ${i+1}</span>`)))
  });
  const thread = await t3.thread({project,title:"Review saved notebook outputs",messages:["Start"]});
  await browser.setViewport({width:1440,height:1120});
  await t3.open(thread);
  await screen.getByText("fixture turn complete",{exact:false}).waitFor();
  const open = async (name:string) => {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(name);
    await screen.getByRole("option",name,{exact:false}).tap();
  };
  await open("loading.ipynb");
  await browser.locator('[data-notebook-output="0-0"] iframe').waitFor({state:"attached",timeout:120000});
  await new Promise(r=>setTimeout(r,1000));
  const loadingHeight = await browser.evaluate(()=>document.querySelector('[data-notebook-output="0-0"] iframe')!.getBoundingClientRect().height);
  await app.screenshot("loading-frame-reserved-space");
  await browser.evaluate(()=>(window as any).releaseNotebookFrames());
  await browser.frameLocator('[data-notebook-output="0-0"] iframe').getByText("Saved output loading — reserved space").waitFor();
  await app.screenshot("loaded-frame");
  await open("results.ipynb");
  const last='[data-notebook-output="0-16"]';
  await browser.locator(last).waitFor({state:"attached",timeout:120000});
  await browser.locator('[data-notebook-output="0-14"] iframe').waitFor({timeout:30000});
  await browser.evaluate((selector)=>{const v=document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; v.scrollTop=170;},last);
  // Wait for the rendered frames to settle before capturing both sides.
  await new Promise(r=>setTimeout(r,1500));
  const bottom = await browser.evaluate((selector)=>{const o=document.querySelector(selector)!;const v=o.closest(".scrollbar-gutter-both")!;const a=o.getBoundingClientRect(),b=v.getBoundingClientRect();return {visible:a.top>=b.top&&a.bottom<=b.bottom,text:o.querySelector("iframe")?.contentDocument?.body?.textContent?.trim()||"blank"};},last);
  await app.screenshot("bottom-scroll-940-preview");
  await browser.setViewport({width:1440,height:1600});
  await browser.evaluate((selector)=>{document.querySelector(selector)!.closest(".scrollbar-gutter-both")!.scrollTop=0;},last);
  await new Promise(r=>setTimeout(r,1500));
  const tall = await browser.evaluate(()=>Array.from(document.querySelectorAll('[data-notebook-output]'),o=>o.querySelector("iframe")?.contentDocument?.body?.textContent?.trim()||"blank"));
  await app.screenshot("all-seventeen-visible");
  expect({loadingHeight,bottom,tall}).toEqual({loadingHeight:80,bottom:{visible:true,text:"Saved result 17"},tall:Array.from({length:17},(_,i)=>`Saved result ${i+1}`)});
});
