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

test("Bottom reorders preserve the release viewport and reclaim temporary space", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("scroll-proof");
  const threads = [];
  for (let i = 1; i <= 30; i++) threads.push(await t3.thread({ project, title: `Sample thread ${i}`, messages: ["first"] }));
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open(threads[0]);
  for (let i = 30; i >= 1; i--) {
    const row = screen.getByRole("button", new RegExp(`^Sample thread ${i},`));
    await row.focus();
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Enter");
  }
  const metrics = () => browser.evaluate(() => {
    const s = document.querySelector<HTMLElement>('[data-sidebar-row]')!.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
    return { top: s.scrollTop, max: s.scrollHeight - s.clientHeight, height: s.scrollHeight };
  });
  await browser.evaluate(() => {
    const s = document.querySelector('[data-sidebar-row]')!.closest('[data-slot="scroll-area-viewport"]')!;
    s.scrollTop = s.scrollHeight;
  });
  const initial = await metrics();
  const rounds = [];
  for (let round = 0; round < 3; round++) {
    const point = await browser.evaluate((title) => {
      const s = document.querySelector('[data-sidebar-row]')!.closest('[data-slot="scroll-area-viewport"]')!;
      const b = s.getBoundingClientRect();
      const rows = [...s.querySelectorAll<HTMLElement>('[data-thread-item]')].filter(n => n.getBoundingClientRect().top > b.top && n.getBoundingClientRect().bottom < b.bottom);
      const row = rows.find(n => n.textContent?.includes(title))!;
      const r = row.getBoundingClientRect();
      return { x: r.left + 100, y: r.top + r.height / 2, bottom: b.bottom - 5 };
    }, `Sample thread ${round % 2 === 0 ? 28 : 27}`);
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down();
    await browser.mouse.move(point.x, point.y + 12);
    await browser.mouse.move(point.x, point.bottom);
    await expect.poll(async () => (await metrics()).top).toBeGreaterThan(initial.max + 50);
    await expect.poll(async () => { const m = await metrics(); return m.max - m.top; }).toBe(0);
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 500)); });
    const target = await browser.evaluate((title) => {
      const s = document.querySelector('[data-sidebar-row]')!.closest('[data-slot="scroll-area-viewport"]')!;
      const b = s.getBoundingClientRect();
      const rows = [...s.querySelectorAll<HTMLElement>('[data-thread-item]')].filter(n => n.getBoundingClientRect().top > b.top && n.getBoundingClientRect().bottom < b.bottom - 100);
      const r = rows.find(n => n.textContent?.includes(title))!.getBoundingClientRect();
      return { x: r.left + 100, y: r.top + r.height / 2 };
    }, `Sample thread ${round % 2 === 0 ? 27 : 28}`);
    await browser.mouse.move(target.x, target.y);
    const before = await metrics();
    await app.screenshot(`round-${round + 1}-before-release`);
    await browser.mouse.up();
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 500)); });
    const after = await metrics();
    rounds.push({ before, after });
    await app.screenshot(`round-${round + 1}-after-release`);
  }
  await browser.evaluate((data) => {
    const badge = document.createElement('div');
    badge.style.cssText = 'position:fixed;right:20px;top:70px;padding:16px;background:#18202c;color:white;z-index:99999;font:16px monospace;white-space:pre';
    badge.textContent = 'Sidebar release measurements (px)\n' + data.map((r, i) => `Drop ${i + 1}: ${r.before.top} → ${r.after.top}; max ${r.after.max}`).join('\n');
    document.body.append(badge);
  }, rounds);
  await app.screenshot("release-measurements");
  for (const r of rounds) expect(Math.abs(r.after.top - r.before.top)).toBeLessThanOrEqual(1);
  expect(Math.max(...rounds.map(r => r.after.max)) - Math.min(...rounds.map(r => r.after.max))).toBeLessThanOrEqual(1);
  await browser.evaluate(() => {
    const s = document.querySelector('[data-sidebar-row]')!.closest('[data-slot="scroll-area-viewport"]')!;
    s.scrollTop -= 250;
  });
  await expect.poll(async () => (await metrics()).max).toBe(initial.max);
  await app.screenshot("space-reclaimed-after-scroll-up");
});
