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

// Synthetic state, real UI actions, and per-frame geometry from the real browser.
test("Bottom-scrolled settling and collapsed shelf departures", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Sidebar demo");
  const threads = [];
  for (let i = 1; i <= 24; i++) threads.push(await t3.thread({project, title: `Work item ${String(i).padStart(2, "0")}`, messages: ["hello"]}));
  const row = (i: number) => browser.locator(`[data-thread-item$=":${threads[i-1].threadId}"]`).first();
  const pause = () => browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 1200)));
  await t3.open(threads[23]);
  await row(24).hover();
  await row(24).getByRole("button", "Settle thread", {exact:true}).tap();
  await pause();
  await t3.open(threads[22]);
  await row(23).hover();
  await row(23).getByRole("button", "Snooze thread", {exact:true}).tap();
  await screen.getByRole("menuitem").first().tap();
  await pause();
  await t3.open(threads[0]);
  await pause();
  // Both shelves default to collapsed. Preserve the production scrolling behavior.
  await browser.evaluate(() => {
    const row = document.querySelector('[data-thread-item]')!;
    const viewport = row.closest('[data-slot="scroll-area-viewport"]')!;
    viewport.scrollTop = viewport.scrollHeight;
  });
  await pause();
  await app.screenshot("bottom-before-settle");
  const start = async (watchId: string, departingId: string) => browser.evaluate(({watchId, departingId}) => {
    const state = {frames: [] as {y:number; top:number; shelf:boolean}[], done: false};
    (window as any).__departure = state;
    const until = performance.now() + 1600;
    const sample = () => {
      const watch = document.querySelector(`[data-thread-item$=":${watchId}"]`);
      const viewport = watch?.closest('[data-slot="scroll-area-viewport"]');
      const shelf = document.querySelector(`[data-sidebar-row$=":${departingId}"][data-sidebar-parent^="shelf:"]`);
      if (watch && viewport) state.frames.push({y:watch.getBoundingClientRect().y, top:viewport.scrollTop, shelf:!!shelf});
      if (performance.now() < until) requestAnimationFrame(sample); else state.done = true;
    };
    sample();
    return null;
  }, {watchId, departingId});
  const finish = async () => { await pause(); return browser.evaluate(() => {
    const frames = (window as any).__departure.frames as {y:number;top:number;shelf:boolean}[];
    return {maxJump: Math.max(0,...frames.slice(1).map((f,i)=>Math.abs(f.y-frames[i].y))), shelf:frames.some(f=>f.shelf), frames};
  }); };
  await row(3).hover();
  await start(threads[1].threadId, threads[2].threadId);
  await row(3).getByRole("button", "Settle thread", {exact:true}).tap();
  const settling = await finish();
  await app.screenshot("bottom-after-settle");
  await browser.mouse.move(800,400);
  await pause();
  await start(threads[1].threadId, threads[0].threadId);
  await browser.keyboard.press("Control+Shift+s");
  const openSettle = await finish();
  await app.screenshot("open-after-settle");
  // Open a remaining bottom row by link, then snooze it into the collapsed shelf.
  await t3.open(threads[1]);
  await pause();
  await row(2).hover();
  await row(2).getByRole("button", "Snooze thread", {exact:true}).tap();
  await app.screenshot("open-before-snooze");
  await start(threads[3].threadId, threads[1].threadId);
  await screen.getByRole("menuitem").first().tap();
  const snoozing = await finish();
  await browser.mouse.move(800,400);
  await pause();
  await app.screenshot("open-after-snooze");
  console.log(JSON.stringify({settling,openSettle,snoozing}));
  await expect(settling.maxJump).toBeLessThan(20);
  await expect(openSettle.shelf).toBe(false);
  await expect(snoozing.shelf).toBe(false);
});
