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

test("Saved right panel width returns after reloading narrow and widening", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("panel-demo");
  const thread = await t3.thread({ project, title: "Saved panel width", messages: ["Hello"], model: "default" });
  await browser.setViewport({ width: 1600, height: 1000 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  const panel = '[data-preview-panel-mode="inline"]:has([data-right-panel-tabbar])';
  await browser.locator(panel).waitFor();
  const measure = () => browser.evaluate((selector) => {
    const box = document.querySelector(selector)!.getBoundingClientRect();
    return { width: box.width, left: box.left, y: box.top + 100 };
  }, panel);
  const initial = await measure();
  await browser.mouse.move(initial.left + 2, initial.y);
  await browser.mouse.down();
  await browser.mouse.move(initial.left + 2 - (853 - initial.width), initial.y);
  await browser.mouse.up();
  const saved = (await measure()).width;
  if (Math.abs(saved - 853) > 2) throw new Error(`Drag did not save 853px: ${saved}`);
  await app.screenshot("saved-wide");
  await browser.setViewport({ width: 1000, height: 1000 });
  await t3.open(thread);
  await browser.locator(panel).waitFor();
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("reloaded-narrow");
  await browser.setViewport({ width: 1600, height: 1000 });
  await browser.evaluate(() => new Promise<null>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(null)))));
  await app.screenshot("widened-restores-saved-width");
  expect(Math.abs((await measure()).width - saved)).toBeLessThan(2);
});
