/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { readFile, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const short = "Example:\n\n    value with two trailing spaces  \n\n# Rollout\n\nDeploy.\n";
// A numbered Markdown comment exceeds the 20-line collapse threshold without changing code.
// The title remains the last block, exercising the preview's former trimEnd.
const long = `<!--\n${Array.from({ length: 24 }, (_, i) => `Padding line ${i + 1}`).join("\n")}\n-->\n\nExample:\n\n    value with two trailing spaces  \n\n# Rollout\n`;

test("Plan code spaces survive expanded and collapsed cards and Copy code", WEB, async ({ t3, app, browser, screen }) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent.enabled = true;
  await writeFile(settingsPath, JSON.stringify(settings));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some((provider) => provider.instanceId === "claudeAgent" && provider.enabled)),
      Stream.runHead,
    );
  }).pipe(Effect.scoped));
  const project = await t3.project("plan-space-proof", { "short-plan.txt": short, "long-plan.txt": long });
  const results: Array<{ label: string; code: string; pasted: string }> = [];
  for (const [file, title, expected] of [["short-plan.txt", "Short plan", "value with two trailing spaces  "], ["long-plan.txt", "Long plan", "value with two trailing spaces  "]] as const) {
    const started = await runPromise(makeState(T3_HOME).cli([
      "thread", "start", project,
      `Reproduce a plan rendering issue. Read ${file}. Call EnterPlanMode, then use the Write tool to write your plan file with exactly the contents of ${file}, preserving every space and newline (the code line ends with TWO spaces). Do not use Bash at all, including for byte verification. Use Read and Write only. Keep all numbered comment lines in the long file; they intentionally make it collapsible. Then call ExitPlanMode with no plan argument so it reads the file. Do not implement anything.`,
      "--title", title, "--provider", "claudeAgent", "--model", "claude-sonnet-5-5", "--wait", "--json",
    ], [0, 2]));
    const { threadId } = JSON.parse(started.stdout);
    await t3.open({ threadId });
    if (started.exitCode === 2) {
      await screen.getByRole("button", "Approve", { exact: true }).tap();
    }
    await screen.getByRole("heading", "Rollout", { exact: true }).waitFor();
    await browser.locator("pre code").waitFor();
    await browser.evaluate(async () => { await document.fonts.ready; return null; });
    // A real paste destination. No clipboard methods are replaced or intercepted.
    await browser.evaluate(() => {
      const panel = document.createElement("aside");
      panel.id = "paste-proof";
      panel.style.cssText = "position:fixed;right:12px;bottom:12px;width:560px;padding:16px;background:#101827;color:#fff;border:2px solid #96baff;z-index:9999;font:14px monospace";
      panel.innerHTML = '<b>Actual clipboard paste — spaces shown as ·</b><p>Copy code, then paste below with Ctrl+V.</p><textarea id="paste-target" aria-label="Clipboard paste destination" style="width:100%;height:50px;background:white;color:black"></textarea><pre id="paste-result" style="white-space:pre-wrap;overflow-wrap:anywhere;max-height:100px;overflow:auto"></pre>';
      panel.querySelector("textarea")!.addEventListener("input", (event) => {
        const value = (event.target as HTMLTextAreaElement).value;
        panel.querySelector("pre")!.textContent = `Last 55 characters: ${value.slice(-55).replaceAll(" ", "·").replaceAll("\n", "↵")}\nTrailing spaces: ${value.match(/ *$/)?.[0].length ?? 0}\nCharacters: ${value.length}`;
      });
      document.body.append(panel);
      return null;
    });
    for (const state of file === "short-plan.txt" ? ["expanded"] : ["collapsed", "expanded"] ) {
      if (file === "long-plan.txt" && state === "expanded") await screen.getByRole("button", "Expand plan", { exact: true }).tap();
      const code = await browser.evaluate(() => document.querySelector("pre code")?.textContent ?? document.querySelector("pre")?.textContent ?? "");
      await screen.getByRole("button", "Copy code", { exact: true }).tap();
      await screen.getByRole("textbox", "Clipboard paste destination", { exact: true }).tap();
      await browser.keyboard.press("ControlOrMeta+a");
      await browser.keyboard.press("ControlOrMeta+v");
      const pasted = await browser.evaluate(() => (document.querySelector("#paste-target") as HTMLTextAreaElement).value);
      results.push({ label: `${title} ${state}`, code, pasted });
      await app.screenshot(`${file === "short-plan.txt" ? "short" : "long"}-${state}-copy-paste`);
    }
  }
  // Assert after all captures so the failing base still records every render path.
  await expect(results.map(({ code, pasted }) => ({ code: code.replace(/\n$/, ""), pasted }))).toEqual([
    { code: "value with two trailing spaces  ", pasted: "value with two trailing spaces  " },
    { code: "value with two trailing spaces  ", pasted: "value with two trailing spaces  " },
    { code: "value with two trailing spaces  ", pasted: "value with two trailing spaces  " },
  ]);
});
