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

test("Blank and chip-adjacent caret lines remain visible when the sidebar expands", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("caret-demo", { "README.md": "# Demo\n" });
  const thread = await t3.thread({ project, title: "Composer resize", messages: ["Start"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  await browser.keyboard.press("Control+b");
  const editor = screen.getByTestId("composer-editor");
  await editor.tap();
  await browser.evaluate(() => {
    const data = new DataTransfer();
    data.setData("text/plain", Array.from({ length: 9 }, (_, i) => `Paragraph ${i + 1}: This is a long paragraph describing the composer caret resize demonstration. It contains enough words to wrap into several lines when the sidebar expands and the editor becomes narrower.`).join("\n\n") + "\n\n");
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    return null;
  });
  await browser.keyboard.press("Control+End");
  const position = () => browser.evaluate(() => {
    const e = document.querySelector('[data-testid="composer-editor"]')!;
    const p = e.lastElementChild!;
    const r = p.getBoundingClientRect(); const er = e.getBoundingClientRect();
    return { top: r.top - er.top, bottom: r.bottom - er.top, height: e.clientHeight, width: e.clientWidth, scrollHeight: e.scrollHeight, scrollTop: e.scrollTop, html: p.outerHTML };
  });
  await app.screenshot("blank-before-resize");
  const blankBefore = await position();
  await browser.keyboard.press("Control+b");
  await app.screenshot("blank-after-resize");
  const blankAfter = await position();
  await browser.keyboard.press("Control+b");
  await browser.keyboard.type("Check @README");
  await screen.getByText("README.md", { exact: true }).last().tap();
  await browser.keyboard.press("Backspace");
  await app.screenshot("chip-before-resize");
  const chipBefore = await position();
  await browser.keyboard.press("Control+b");
  await app.screenshot("chip-after-resize");
  const chipAfter = await position();
  console.log(JSON.stringify({ blankBefore, blankAfter, chipBefore, chipAfter }));
  expect(blankAfter.bottom).toBeLessThanOrEqual(blankAfter.height + 2);
  expect(Math.abs(blankAfter.top - blankBefore.top)).toBeLessThanOrEqual(3);
  expect(chipAfter.bottom).toBeLessThanOrEqual(chipAfter.height + 2);
  expect(Math.abs(chipAfter.top - chipBefore.top)).toBeLessThanOrEqual(3);
});
