import { readFile } from "node:fs/promises";
import { PNG } from "pngjs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("RTF workspace and draft attachment previews preserve tabs and repeated spaces", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("proj", { "spacing.rtf": String.raw`{\rtf1\ansi A\tab B  C}` });
  const thread = await t3.thread({ project, title: "RTF spacing", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "spacing.rtf").tap();
  await expect(screen.getByText("1 page", { exact: false })).toBeVisible({ timeout: 120_000 });
  await expect(browser.frameLocator('iframe[title^="spacing.rtf"]').locator("body")).toContainText("A");
  const workspaceBounds = await browser.frameLocator('iframe[title^="spacing.rtf"]').locator("p").boundingBox();
  const workspace = await gaps(await app.screenshot("workspace-spacing"), workspaceBounds!);
  await browser.keyboard.press("Escape");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    if (!input) throw new Error("Attachment input missing");
    const files = new DataTransfer();
    files.items.add(new File([String.raw`{\rtf1\ansi A\tab B  C}`], "spacing.rtf", {type:"application/rtf"}));
    input.files = files.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  await screen.getByRole("button", "File attachment, spacing.rtf", { exact: false }).tap();
  await expect(screen.getByRole("dialog")).toBeVisible();
  await expect(browser.frameLocator('[role="dialog"] iframe').locator("body")).toContainText("A");
  const attachmentBounds = await browser.frameLocator('[role="dialog"] iframe').locator("p").boundingBox();
  const attachment = await gaps(await app.screenshot("attachment-spacing"), attachmentBounds!);
  for (const spacing of [workspace, attachment]) {
    expect(spacing.length).toBe(2);
    expect(spacing[0]).toBeGreaterThanOrEqual(20);
    expect(spacing[1]).toBeGreaterThanOrEqual(8);
  }
});

// Measure the two empty pixel runs between the three glyphs in the actual rendered paragraph.
async function gaps(path: string, rect: {x:number;y:number;width:number;height:number}) {
  const png = PNG.sync.read(await readFile(path));
  const runs: number[][] = [];
  for (let x = Math.ceil(rect.x); x < Math.floor(rect.x + rect.width); x++) {
    let ink = false;
    for (let y = Math.ceil(rect.y); y < Math.floor(rect.y + rect.height); y++) {
      const i = (y * png.width + x) * 4;
      if (png.data[i]! < 128 && png.data[i+1]! < 128 && png.data[i+2]! < 128) ink = true;
    }
    if (ink) {
      const last = runs.at(-1);
      if (last && last[1] === x-1) last[1] = x;
      else runs.push([x,x]);
    }
  }
  return runs.slice(1).map((run,i) => run[0]! - runs[i]![1]! - 1);
}
