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

test("Settle counts only selected threads that are not settled", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo-project");
  const alpha = await t3.thread({ project, title: "go alpha", messages: ["go alpha"] });
  const beta = await t3.thread({ project, title: "go beta", messages: ["go beta"] });
  await browser.setViewport({ width: 1280, height: 900 });
  await t3.open(beta);
  const row = (title: string) => screen.getByRole("button", new RegExp(`^${title},`));
  const context = async (title: string) => {
    await browser.evaluate((name) => {
      const el = [...document.querySelectorAll<HTMLElement>("[data-sidebar-row]")].find(el => el.getAttribute("aria-label")?.startsWith(`${name},`));
      if (!el) throw new Error(`Missing sidebar row ${name}`);
      const box = el.getBoundingClientRect();
      el.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: box.x + 100, clientY: box.y + 15 }));
    }, title);
  };
  await row("go alpha").waitFor();
  await context("go alpha");
  await screen.getByRole("menuitem", "Settle thread", { exact: true }).tap();
  await screen.getByRole("button", /^Settled/).tap();
  await row("go alpha").waitFor();
  await row("go beta").tap({ modifiers: ["Control"] });
  await row("go alpha").tap({ modifiers: ["Control"] });
  await context("go beta");
  await screen.getByRole("menuitem", /^Settle \(/).waitFor();
  await app.screenshot("mixed-selection");
  const mixed = await browser.evaluate(() => [...document.querySelectorAll('[role="menuitem"]')].find(el => el.textContent?.startsWith("Settle ("))?.textContent?.trim());
  await screen.getByRole("menuitem", /^Settle \(/).tap();
  await row("go beta").waitFor();
  await row("go beta").tap();
  await row("go beta").tap({ modifiers: ["Control"] });
  await row("go alpha").tap({ modifiers: ["Control"] });
  await context("go beta");
  await screen.getByRole("menuitem", /^Settle \(/).waitFor();
  await app.screenshot("settled-only-selection");
  const settled = await browser.evaluate(() => {
    const el = [...document.querySelectorAll('[role="menuitem"]')].find(el => el.textContent?.startsWith("Settle ("));
    return { text: el?.textContent?.trim(), disabled: el?.getAttribute("aria-disabled") };
  });
  expect({ mixed, settled }).toEqual({ mixed: "Settle (1)", settled: { text: "Settle (0)", disabled: "true" } });
});
