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

test("Ctrl+Delete joins adjacent list items and persists the joined draft", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("list-editing");
  const thread = await t3.thread({ project, title: "List editing", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  const composer = screen.getByRole("textbox");
  const results = [];
  for (const [kind, prefix] of [["ordered", "1. "], ["bullet", "- "]] as const) {
    await composer.tap();
    await browser.keyboard.press("Control+a");
    await browser.keyboard.press("Backspace");
    await browser.keyboard.type(prefix + "a");
    await browser.keyboard.press("Shift+Enter");
    await browser.keyboard.type("b");
    await app.screenshot(kind + "-two-items");
    await browser.keyboard.press("ArrowUp");
    await browser.keyboard.press("End");
    await browser.evaluate(() => {
      const selection = window.getSelection();
      if (selection?.anchorNode?.textContent !== "a" || selection.anchorOffset !== 1) {
        throw new Error("Caret was not at the end of a: " + JSON.stringify({ text: selection?.anchorNode?.textContent, offset: selection?.anchorOffset }));
      }
      return null;
    });
    await browser.keyboard.press("Control+Delete");
    results.push(await browser.evaluate(() => {
      const editor = document.querySelector('[contenteditable="true"][role="textbox"]') ?? document.querySelector('[contenteditable="true"]');
      return { text: editor?.textContent, items: editor?.querySelectorAll("li").length };
    }));
    await app.screenshot(kind + "-modified-delete");
    await t3.open(thread);
    await composer.waitFor();
    await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    results.push(await browser.evaluate(() => {
      const editor = document.querySelector('[contenteditable="true"][role="textbox"]') ?? document.querySelector('[contenteditable="true"]');
      return { text: editor?.textContent, items: editor?.querySelectorAll("li").length };
    }));
    await app.screenshot(kind + "-reopened-draft");
  }
  expect(results).toEqual(Array.from({ length: 4 }, () => ({ text: "ab", items: 1 })));
});
