import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("All projects exposes shared actions inherited by a project", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => {
    const sanitize = () => {
      if (!document.documentElement) return;
      if (!document.getElementById("evidence-style")) {
        const style = document.createElement("style");
        style.id = "evidence-style";
        style.textContent = "*,*::before,*::after { animation: none !important; transition: none !important; }";
        document.documentElement.append(style);
      }
      const walker = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.textContent?.startsWith("/home/")) node.textContent = "[synthetic workspace]";
      }
    };
    new MutationObserver(sanitize).observe(document, { childList: true, subtree: true, characterData: true });
    document.addEventListener("DOMContentLoaded", sanitize);
  });
  const capture = async (label: string) => {
    await browser.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); });
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 8; attempt++) {
      await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 500)));
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture was not stable: ${label}`);
  };
  const project = await t3.project("Sample project");
  await t3.thread({ project, title: "Action inheritance", messages: ["Hello"] });
  await t3.open();
  await screen.getByText("Action inheritance", { exact: true }).first().waitFor();
  await app.open("/settings/projects");
  await screen.getByText("All projects", { exact: true }).first().waitFor();
  await capture("all-projects-actions");
  await expect(screen.getByRole("button", "Add action", { exact: true })).toBeVisible();
  await screen.getByRole("button", "Add action", { exact: true }).tap();
  await screen.getByLabel("Name", { exact: true }).fill("Shared check");
  await screen.getByLabel("Command", { exact: true }).fill("echo shared-check");
  await screen.getByRole("button", "Save action", { exact: true }).tap();
  await expect(screen.getByText("Shared check", { exact: true })).toBeVisible();
  await capture("shared-action-saved");
  await app.open("/");
  await screen.getByTestId("sidebar-row-card").tap();
  await expect(screen.getByRole("button", "Run Shared check", { exact: true })).toBeVisible();
  await capture("inherited-shared-action");
  await app.open("/settings/projects");
  await screen.getByRole("combobox", "Search settings").fill("Actions");
  await capture("actions-search-results");
  await screen.getByRole("option").filter({ hasText: "Actions" }).first().tap();
  await expect(screen.getByRole("button", "Add action", { exact: true })).toBeVisible();
  await capture("actions-search-opens-editor");
  await screen.getByRole("button", "Edit Shared check", { exact: true }).tap();
  await screen.getByLabel("Name", { exact: true }).fill("Shared check updated");
  await screen.getByRole("button", "Save changes", { exact: true }).tap();
  await expect(screen.getByText("Shared check updated", { exact: true })).toBeVisible();
  await capture("shared-action-edited");
  await screen.getByRole("button", "Edit Shared check updated", { exact: true }).tap();
  await screen.getByRole("button", "Delete", { exact: true }).tap();
  await screen.getByRole("button", "Delete action", { exact: true }).tap();
  await expect(screen.getByText("No actions configured.", { exact: true })).toBeVisible();
  await capture("shared-action-deleted");
});
