import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

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

test(
  "Changes updates its breakdown when an edit moves from code to docs",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "app.ts": "export {};\n" });
    const thread = await t3.thread({ project, title: "Review changes", messages: ["Start"] });
    const write = (file: string, contents: string) =>
      runPromise(
        Effect.flatMap(FileSystem.FileSystem, (fs) =>
          fs.writeFileString(`${project}/${file}`, contents),
        ),
      );
    await write("app.ts", "export {};\n// Changed\n");
    await t3.open(thread);

    const changes = screen.getByRole("button", /^Changes\b/);
    const changesLabel = changes.getByText("Changes", { exact: true });
    const breakdown = browser.locator('[data-slot="tooltip-popup"]');
    await changes.getByText("+1", { exact: true }).waitFor();
    await changesLabel.hover({ timeout: 15_000 });
    await breakdown.getByText("Code", { exact: true }).waitFor();

    // Plain writes, not `git restore`: an index change could publish a clean status in between.
    await write("app.ts", "export {};\n");
    await write("README.md", "Updated documentation\n");
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    const commit = screen.getByRole("dialog", "Commit changes");
    await commit.getByRole("button", "Open README.md in editor").waitFor();
    await commit.getByRole("button", "Cancel", { exact: true }).tap();
    await commit.waitFor({ state: "hidden" });

    await changesLabel.hover({ timeout: 15_000 });
    await breakdown.getByText("Total", { exact: true }).waitFor();
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      await Promise.all(popup?.getAnimations({ subtree: true }).map((animation) => animation.finished) ?? []);
    });
    await app.screenshot("changes-after-replacing-file-edit");
    await expect(breakdown.getByText("Docs", { exact: true })).toBeVisible();
    await expect(breakdown.getByText("Code", { exact: true })).toBeHidden();
  },
);
