/// <reference lib="dom" />
import { expect } from "e2e";

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

test(
  "Dragging a side-panel tab cannot reorder the tabs in another thread",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const first = await t3.thread({ project, title: "First panel thread", messages: ["Start"], model: "default" });
    const second = await t3.thread({ project, title: "Second panel thread", messages: ["Start"], model: "default" });
    await browser.setViewport({ width: 1440, height: 900 });
    await t3.open(first);
    const openTabs = async () => {
      await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
      await screen.getByRole("button", "Files F", { exact: true }).tap();
      await screen.getByRole("button", "Add panel surface").tap();
      await screen.getByRole("menuitem", /^Diff/).tap();
      await screen.getByRole("button", "Close Diff", { exact: true }).waitFor();
    };
    await openTabs();
    await browser.locator(`[data-sidebar-row$=":${second.threadId}"]`).click();
    await openTabs();

    const tabs = () =>
      browser.evaluate(() =>
        Array.from(
          document.querySelectorAll("[data-right-panel-tab-list] [data-active-tab]"),
          (tab) => {
            const { left, top, width, height } = tab.getBoundingClientRect();
            return { x: left + width / 2, y: top + height / 2, label: tab.textContent };
          },
        ),
      );
    const [files, diff] = await tabs();
    if (files?.label !== "Files" || diff?.label !== "Diff")
      throw new Error("The tabs did not open");

    await browser.mouse.move(files.x, files.y);
    await browser.mouse.down();
    await browser.mouse.move(files.x + 12, files.y);
    await browser.mouse.move(diff.x + 8, diff.y);
    await expect.poll(async () => (await tabs())[1]?.x ?? diff.x).toBeLessThan(diff.x - 5);
    await browser.keyboard.press("ControlOrMeta+[");
    await browser.waitForURL(new RegExp(first.threadId.split(":")[1]!));
    await screen.getByRole("button", "Close Files", { exact: true }).waitFor();
    const beforeDrop = (await tabs()).map((tab) => tab.label).join(", ");
    if (beforeDrop !== "Files, Diff") throw new Error("The first thread's tabs did not load");
    await browser.mouse.up();

    await app.screenshot("first-thread-after-tab-drag");
    expect((await tabs()).map((tab) => tab.label)).toEqual(["Files", "Diff"]);

    const [firstFiles, firstDiff] = await tabs();
    if (!firstFiles || !firstDiff) throw new Error("The first thread's tabs did not load");
    await screen.swipe({ from: firstFiles, to: firstDiff, duration: 700 });
    await expect.poll(async () => (await tabs())[0]?.label).toBe("Diff");
    await app.screenshot("within-thread-reorder-still-works");
  },
);
