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

test("Sent outline preserves three and eight leading spaces", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("outline-demo");
  const thread = await t3.thread({ project, title: "Outline indentation", messages: ["Ready for an outline"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Plan");
  await composer.press("Shift+Enter");
  await browser.keyboard.type("   Step one");
  await composer.press("Shift+Enter");
  await browser.keyboard.type("        Detail a");
  await app.screenshot("composed-outline");
  await composer.press("Enter");
  await screen.getByText("Detail a", { exact: false }).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await app.screenshot("sent-outline");
  const offsets = await browser.evaluate(() => {
    const body = [...document.querySelectorAll('[data-user-message-body]')].find(el => el.textContent?.includes("Detail a"))!;
    const x = (word: string) => {
      const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
      let node: Node | null;
      while ((node = walker.nextNode())) {
        const start = node.textContent!.indexOf(word);
        if (start < 0) continue;
        const range = document.createRange();
        range.setStart(node, start);
        range.setEnd(node, start + 1);
        return range.getBoundingClientRect().x;
      }
      throw new Error(`Missing ${word}`);
    };
    const start = x("Plan");
    return [x("Step one") - start, x("Detail a") - start];
  });
  expect(offsets[0]).toBeGreaterThan(8);
  expect(offsets[1]).toBeGreaterThan(offsets[0] + 10);
});
