/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const PROMPT = '    if ready:\n        print("go")';

test("Prompt links preserve multiline first-line indentation", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title:"Prompt links", messages:["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await t3.open("/new?prompt=" + encodeURIComponent(PROMPT));
  const editor = screen.getByRole("textbox");
  await editor.waitFor();
  const opened = await browser.evaluate(() => document.querySelector<HTMLElement>('[data-testid="composer-editor"]')?.innerText ?? "");
  await browser.evaluate((value) => {
    const panel = document.createElement("pre");
    panel.id = "prompt-proof";
    panel.style.cssText = "position:fixed;bottom:0;left:0;right:0;padding:16px;background:#111;color:#fff;z-index:99999;font:16px monospace;white-space:pre-wrap";
    panel.textContent = "Opened prompt (spaces shown as ·):\n" + value.replaceAll(" ", "·");
    document.body.append(panel);
    return null;
  }, opened);
  await app.screenshot("opened-prompt-indentation");
  await editor.tap();
  await browser.keyboard.press("Control+a");
  await browser.keyboard.press("Backspace");
  await browser.evaluate((text) => {
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", text);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles:true, cancelable:true }));
    Object.defineProperty(navigator.clipboard, "writeText", { configurable:true, value:async (value:string) => { document.body.dataset.copiedPromptLink = value; } });
    return null;
  }, PROMPT);
  await browser.keyboard.press("Control+k");
  await screen.getByRole("option", "Copy prompt link", { exact:true }).tap();
  await browser.locator('[data-testid="command-palette"]').waitFor({ state:"hidden" });
  const copied = await browser.evaluate(() => {
    const url = document.body.dataset.copiedPromptLink;
    if (!url) throw new Error("Copy prompt link did not write to clipboard");
    const prompt = new URL(url).searchParams.get("prompt") ?? "";
    document.getElementById("prompt-proof")!.textContent = "Copied link: " + url + "\nDecoded prompt (spaces shown as ·):\n" + prompt.replaceAll(" ", "·");
    return prompt;
  });
  await app.screenshot("copied-prompt-indentation");
  expect({ opened: opened.replaceAll("\n\n", "\n"), copied }).toEqual({ opened:PROMPT, copied:PROMPT });
});
