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

test("Nested quote spacing preserves fenced thread examples", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Quote examples");
  const thread = await t3.thread({ project, title: "Nested quote spacing", messages: ["Start"] });
  await t3.open("/settings/chat");
  await screen.getByRole("switch", "Rich text composer", { exact: true }).tap();
  await t3.open(thread);
  const env = await runPromise(environmentId(app.baseUrl ?? ""));
  const link = `<t3-thread://v2/${env}/t>`;
  const after = `<t3-thread://v2/${env}/after>`;
  const composer = screen.getByRole("textbox");
  const paste = async (text: string) => {
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+A");
    await browser.keyboard.press("Backspace");
    await browser.evaluate(async (value) => { await navigator.clipboard.writeText(value); }, text);
    await browser.keyboard.press("ControlOrMeta+V");
  };
  const read = () => browser.evaluate(() => {
    const editor = document.querySelector('[data-testid="composer-editor"]')!;
    return { chips: editor.querySelectorAll('a[href]').length, text: Array.from(editor.children, (line) => line.textContent ?? "").join("\n") };
  });
  await paste(after);
  const control = await read();
  if (control.chips !== 1) throw new Error(`Control paste did not create one thread chip: ${JSON.stringify(control)}`);
  const cases = [
    { label: "same-prefix-control", text: `>> ~~~\n>> ${link}\n>> ~~~`, chips: 0 },
    { label: "compact-open-spaced-inner", text: `>> ~~~\n> > ${link}\n>> ~~~`, chips: 0 },
    { label: "spaced-open-compact-inner", text: `> > ~~~\n>> ${link}\n> > ~~~`, chips: 0 },
    { label: "compact-open-with-outside-link", text: `>> ~~~\n> > ${link}\n>> ~~~\n${after}`, chips: 1 },
    { label: "spaced-open-with-outside-link", text: `> > ~~~\n>> ${link}\n> > ~~~\n${after}`, chips: 1 },
  ];
  const results = [];
  for (const item of cases) {
    await paste(item.text);
    await app.screenshot(item.label);
    results.push({ ...item, result: await read() });
  }
  for (const item of results) {
    expect(item.result.chips, item.label).toBe(item.chips);
    expect(item.result.text, item.label).toContain(item.text.split("\n").slice(0, 3).join("\n"));
  }
});
