/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Reopening a working thread paints its footer at the end", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Demo");
  const parent = await t3.thread({ project, title: "Long parent", model: "command-output", messages: Array.from({length:14}, (_,i) => `Long user turn ${i+1}\n` + "A detailed synthetic description of the work and its expected result. ".repeat(30)) });
  const child = await t3.thread({ project, title: "Short child", model: "multi-turn", messages:["Hello"] });
  await t3.open(child);
  // Hide host paths in recordings without changing layout or scroll measurements.
  await browser.evaluate(() => {
    const redact = () => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      let node;
      while ((node = walker.nextNode())) {
        if (node.textContent?.includes("/home/") && node.parentElement)
          node.parentElement.style.visibility = "hidden";
      }
    };
    new MutationObserver(redact).observe(document.body, {childList:true,subtree:true,characterData:true});
    redact();
  });
  await screen.getByRole("button", /^Long parent,/).tap();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await browser.keyboard.type("Showcase");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  const composer = screen.getByRole("textbox");
  await composer.fill("Start working");
  await composer.press("Enter");
  await screen.getByText("Working for", {exact:false}).waitFor();
  for(let i=1;i<=20;i++) {
    await composer.fill(`Queued follow-up ${i}`);
    await browser.keyboard.press("ControlOrMeta+Enter");
  }
  await screen.getByText(/^Show all \d+ queued$/).waitFor();
  const traces: number[][] = [];
  for(let run=0;run<6;run++) {
    await screen.getByRole("button", /^Short child,/).tap();
    if(run===0) await screen.getByRole("button", /^Working \d+$/).tap();
    await browser.evaluate(() => { [...document.querySelectorAll("button")].find(el=>el.textContent==="Dismiss")?.click(); });
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve,1300)));
    await browser.evaluate(() => {
      (window as any).__endTrace = [];
      (window as any).__recordEnd = true;
      const start = performance.now();
      const tick = () => {
        const el = document.querySelector<HTMLElement>(".messages-timeline-scroll");
        if(el && decodeURIComponent(location.pathname).includes((window as any).__parentId)) {
          const gap = el.scrollHeight-el.clientHeight-el.scrollTop;
          (window as any).__endTrace.push({ms:Math.round(performance.now()-start),gap});
        }
        if(performance.now()-start<1000) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    });
    await browser.evaluate((id) => { (window as any).__parentId=id; },parent.threadId);
    await screen.getByRole("button", /^Long parent,/).tap();
    await app.screenshot(`switch-${run+1}-opening`);
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve,1100)));
    const trace = await browser.evaluate<Array<{ms:number,gap:number}>>(() => (window as any).__endTrace);
    console.log(`Switch ${run+1}: ${JSON.stringify(trace)}`);
    if(trace.length===0) throw new Error("Frame recorder did not see the parent timeline");
    traces.push(trace.filter(x=>x.ms<500).map(x=>x.gap));
    await app.screenshot(`switch-${run+1}-settled`);
  }
  expect(Math.max(...traces.flat())).toBeLessThan(100);
});
