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

test("Plain-text composer preserves literal typing and rich text remains available", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("composer-demo");
  const thread = await t3.thread({ project, title: "Composer formatting", messages: ["Ready"] });
  await t3.open("/settings/chat");
  await screen.getByRole("switch", "Rich text composer").tap();
  await screen.getByRole("combobox", "Send shortcut").tap();
  await screen.getByRole("option", "Enter", { exact: true }).tap();
  await app.screenshot("plain-text-settings");
  await t3.open(thread);
  const composer = screen.getByTestId("composer-editor");
  const text = () => browser.evaluate(() => {
    const editor = document.querySelector<HTMLElement>('[data-testid="composer-editor"]');
    if (!editor) throw new Error("Missing composer");
    return Array.from(editor.children, (block) => block.textContent ?? "").join("\n");
  });
  const replace = async (value: string) => {
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+A");
    await browser.keyboard.type(value);
  };
  await replace("1. item");
  await browser.keyboard.press("Shift+Enter");
  const newline = await text();
  await app.screenshot("plain-newline");
  await replace("word");
  await browser.keyboard.press("Shift+Home");
  await app.screenshot("selected-word");
  await browser.keyboard.press("*");
  const delimiter = await text();
  await app.screenshot("plain-selection-replacement");
  await replace("1. item");
  await browser.keyboard.press("Tab");
  const tab = await text();
  await app.screenshot("plain-tab");
  await replace("    1. item");
  await browser.keyboard.press("Shift+Tab");
  const shiftTab = await text();
  await app.screenshot("plain-shift-tab");
  await replace("Plain text sends with Enter");
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete").waitFor();
  await app.screenshot("plain-enter-sent");
  await t3.open("/settings/chat");
  await screen.getByRole("switch", "Rich text composer").tap();
  await app.screenshot("rich-text-settings");
  await t3.open(thread);
  await replace("1. item");
  await browser.keyboard.press("Shift+Enter");
  await app.screenshot("rich-list-newline");
  await replace("word");
  await browser.keyboard.press("Shift+Home");
  await app.screenshot("rich-selected-word");
  await browser.keyboard.press("*");
  await app.screenshot("rich-selection-formatting");
  await replace("1. item");
  await browser.keyboard.press("Tab");
  await app.screenshot("rich-list-tab");
  await replace("    1. item");
  await browser.keyboard.press("Shift+Tab");
  await app.screenshot("rich-list-shift-tab");
  expect({ newline, delimiter, tab, shiftTab }).toEqual({
    newline: "1. item\n", delimiter: "*", tab: "1. item", shiftTab: "    1. item",
  });
});
