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

test("Active reorder preserves the open client's activity timestamp", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Activity proof");
  const other = await t3.thread({ project, title: "New thread", messages: ["hello"], model: "multi-turn" });
  const thread = await t3.thread({ project, title: "Greeting", messages: ["hello"], model: "multi-turn" });
  await t3.open("/settings/general");
  await screen.getByRole("switch", "Working section", { exact: true }).tap();
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor({ state: "visible" });
  const read = () => browser.evaluate(async (id: string) => {
    const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
    const { environmentThreadDetails } = await import("/src/state/threads.ts");
    const environmentId = location.pathname.split("/")[1];
    const state = appAtomRegistry.get(environmentThreadDetails.threadAtom({ environmentId, threadId: id }));
    const p = state?.projection;
    return p ? { activity: p.updatedAt.epochMilliseconds, stored: p.thread.updatedAt.epochMilliseconds, order: p.thread.activeOrderKey ?? null } : null;
  }, thread.threadId);
  await expect.poll(read).not.toBeNull();
  const before = await read();
  const points = await browser.evaluate(({ source, destination }) => {
    const rect = (id: string) => {
      const element = [...document.querySelectorAll("[data-sidebar-row]")].find(e => e.getAttribute("data-sidebar-row")?.includes(id));
      if (!element) throw new Error("Sidebar thread row missing");
      const r = element.getBoundingClientRect();
      return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
    };
    return { source: rect(source), destination: rect(destination) };
  }, { source: thread.threadId, destination: other.threadId });
  await browser.mouse.move(points.source.x, points.source.y);
  await browser.mouse.down();
  for (let i = 1; i <= 15; i++) {
    await browser.mouse.move(points.source.x, points.source.y + (points.destination.y + 25 - points.source.y) * i / 15);
  }
  await browser.mouse.up();
  await expect.poll(async () => (await read())?.order).not.toBe(before?.order);
  const after = await read();
  await browser.evaluate((data) => {
    const panel = document.createElement("pre");
    panel.style.cssText = "position:fixed;bottom:24px;left:320px;right:24px;padding:24px;background:#101820;color:#fff;border:2px solid #879bad;z-index:99999;font:16px/1.7 monospace;white-space:pre-wrap";
    panel.textContent = "READ-ONLY CLIENT STATE INSPECTION — Active reorder\n" +
      "Activity before: " + new Date(data.before.activity).toISOString() + "\n" +
      "Activity after:  " + new Date(data.after.activity).toISOString() + "\n" +
      "Thread stored:   " + new Date(data.after.stored).toISOString() + "\n" +
      "Active order:    " + data.after.order + "\n" +
      "Activity preserved: " + (data.before.activity === data.after.activity);
    document.body.append(panel);
  }, { before, after });
  await app.screenshot("activity-after-reorder");
  expect(after?.activity).toBe(before?.activity);
});
