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

test("Thread details follows the inline panel edge while closing", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Panel animation demo");
  const thread = await t3.thread({ project, title: "Panel close demonstration", messages: ["first"] });
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Advanced", { exact: true }).first().tap();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[aria-label="Panel animation duration"]')!;
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "300");
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {})));
  });
  await app.screenshot("panel-open");
  const samples = await browser.evaluate(async () => {
    const panel = document.querySelector<HTMLElement>('[data-preview-panel-mode="inline"]')!;
    const button = document.querySelector<HTMLButtonElement>('[aria-label="Toggle right panel"]')!;
    const samples: Array<{ms:number; edge:number; toggle:number}> = [];
    const start = performance.now();
    button.click();
    await new Promise<void>(resolve => {
      const frame = () => {
        const toggle = [...document.querySelectorAll<HTMLElement>('[aria-label="Toggle thread details panel"]')].find(el => el.getBoundingClientRect().width && getComputedStyle(el).visibility !== "hidden");
        if (toggle && panel.isConnected) samples.push({ ms:performance.now()-start, edge:panel.getBoundingClientRect().left, toggle:toggle.getBoundingClientRect().left });
        if (performance.now()-start < 350) requestAnimationFrame(frame); else resolve();
      };
      requestAnimationFrame(frame);
    });
    return samples;
  });
  // Repeat the same close for the still; the video above retains the uninterrupted transition.
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); });
  await browser.evaluate(() => {
    document.querySelector<HTMLButtonElement>('[aria-label="Toggle right panel"]')!.click();
  });
  await app.screenshot("closing-panel");
  await app.screenshot("panel-closed");
  const early = samples.filter(s => s.ms < 150 && s.edge < 1100);
  console.log("Closing frame samples", JSON.stringify(samples));
  expect(early.length).toBeGreaterThan(0);
  expect(Math.max(...early.map(s => s.toggle - s.edge))).toBeLessThan(0);
});
