import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Compiler emitted source maps count as generated changes", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("source-map-demo");
  await t3.open("/settings/appearance");
  await screen.getByRole("button", /^Thread details: \d+ of \d+ on$/).waitFor();
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const git = (...args: string[]) => run("git", args, { cwd: project });
    yield* git("switch", "-c", "emitted-maps");
    for (const suffix of ["mjs.map", "cjs.map", "jsx.map", "d.ts.map", "d.mts.map", "d.cts.map", "js.map"]) {
      yield* fs.writeFileString(`${project}/example.${suffix}`, '{"version":3}\n');
    }
    yield* git("add", "--all");
    yield* git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add emitted source maps");
  }));
  const thread = await t3.thread({ project, title: "Review emitted source maps", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("combobox", /^Change comparison target/).tap();
  await screen.getByRole("option", "main", { exact: true }).tap();
  await screen.getByRole("button", /^(Expand|Collapse) example\.mjs\.map$/).waitFor();
  await screen.getByRole("button", "Refresh diff", { exact: true }).waitFor();
  await app.screenshot("branch-comparison-seven-source-maps");
  await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
  const changes = screen.getByRole("button", /^Changes\b/);
  await changes.getByText("+7", { exact: true }).waitFor();
  await changes.getByText("Changes", { exact: true }).hover({ timeout: 15_000 });
  const breakdown = browser.locator('[data-slot="tooltip-popup"]');
  await breakdown.getByText("Total", { exact: true }).waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
  });
  await app.screenshot("source-maps-changes-breakdown");
  await expect(breakdown.getByText("Code", { exact: true })).toBeHidden();
  await expect(breakdown.getByText("Generated", { exact: true })).toBeVisible();
  await expect(breakdown.getByText("+7", { exact: true })).toHaveCount(2);
});
