import { layoutPdfPages, PdfTextItem } from "../../../src/adapters/reader/pdf-text-layout";

/** Une ligne d'un seul morceau, terminée par un saut de ligne. */
function line(str: string, y: number, height = 10, x = 50): PdfTextItem {
  return { str, x, y, width: str.length * height * 0.5, height, hasEOL: true };
}

describe("layoutPdfPages", () => {
  it("joins the items of a line, with a space only where there is a gap", () => {
    const blocks = layoutPdfPages([
      [
        { str: "Bon", x: 0, y: 700, width: 15, height: 10, hasEOL: false },
        { str: "jour", x: 15, y: 700, width: 20, height: 10, hasEOL: false },
        { str: "monde", x: 40, y: 700.5, width: 25, height: 10, hasEOL: true },
      ],
    ]);
    expect(blocks).toEqual([{ type: "paragraph", c: ["Bonjour monde"] }]);
  });

  it("merges close lines into one paragraph and splits on a vertical gap", () => {
    const blocks = layoutPdfPages([
      [
        line("Première ligne", 700),
        line("deuxième ligne.", 688),
        line("Autre paragraphe.", 650),
      ],
    ]);
    expect(blocks).toEqual([
      { type: "paragraph", c: ["Première ligne deuxième ligne."] },
      { type: "paragraph", c: ["Autre paragraphe."] },
    ]);
  });

  it("merges a word hyphenated at the end of a line", () => {
    const blocks = layoutPdfPages([[line("le mode lec-", 700), line("ture", 688)]]);
    expect(blocks).toEqual([{ type: "paragraph", c: ["le mode lecture"] }]);
  });

  it("detects headings from the font size", () => {
    const body = Array.from({ length: 5 }, (_, i) =>
      line(`Texte courant numéro ${i}`, 600 - i * 12),
    );
    const blocks = layoutPdfPages([
      [line("Grand titre", 760, 20), line("Sous-titre", 720, 15), line("Petit titre", 680, 13), ...body],
    ]);
    expect(blocks.slice(0, 3)).toEqual([
      { type: "heading", level: 1, c: ["Grand titre"] },
      { type: "heading", level: 2, c: ["Sous-titre"] },
      { type: "heading", level: 3, c: ["Petit titre"] },
    ]);
    expect(blocks[3].type).toBe("paragraph");
  });

  it("merges a heading written on two lines", () => {
    const blocks = layoutPdfPages([
      [
        line("Un titre sur", 760, 20),
        line("deux lignes", 738, 20),
        ...Array.from({ length: 5 }, (_, i) => line(`Texte courant ${i}`, 600 - i * 12)),
      ],
    ]);
    expect(blocks[0]).toEqual({ type: "heading", level: 1, c: ["Un titre sur deux lignes"] });
  });

  it("does not treat a large sentence as a heading", () => {
    const blocks = layoutPdfPages([
      [line("Une phrase en gros.", 760, 20), line("Texte courant assez long pour dominer", 700)],
    ]);
    expect(blocks[0].type).toBe("paragraph");
  });

  it("adds a page marker before each non-empty page after the first", () => {
    const blocks = layoutPdfPages([
      [line("Page un", 700)],
      [line("  ", 700)],
      [line("Page trois", 700)],
    ]);
    expect(blocks).toEqual([
      { type: "paragraph", c: ["Page un"] },
      { type: "paragraph", c: ["Page 3"] },
      { type: "paragraph", c: ["Page trois"] },
    ]);
  });

  it("returns no block for a PDF without text", () => {
    expect(layoutPdfPages([[], [line("", 700)]])).toEqual([]);
  });

  it("starts a new paragraph when text goes back up (new column)", () => {
    const blocks = layoutPdfPages([[line("Colonne une", 700), line("Colonne deux", 750, 10, 300)]]);
    expect(blocks).toHaveLength(2);
  });

  it("does not merge lines of very different sizes that are close vertically", () => {
    const blocks = layoutPdfPages([
      [
        { str: "Recrute", x: 275, y: 786.6, width: 133, height: 42, hasEOL: false },
        { str: "Ouvrier(e)", x: 191, y: 766.8, width: 80, height: 18, hasEOL: false },
        ...Array.from({ length: 5 }, (_, i) => line(`Texte courant ${i}`, 600 - i * 12)),
      ],
    ]);
    expect(blocks.slice(0, 2)).toEqual([
      { type: "heading", level: 1, c: ["Recrute"] },
      { type: "heading", level: 1, c: ["Ouvrier(e)"] },
    ]);
  });

  it("puts blocks back in reading order (top → bottom, left → right)", () => {
    const blocks = layoutPdfPages([
      [
        line("Pied de page", 50),
        line("Corps", 500),
        line("Droite", 700, 10, 400),
        line("Gauche", 700, 10, 50),
      ],
    ]);
    expect(blocks.map((b) => ("c" in b ? b.c[0] : ""))).toEqual([
      "Gauche",
      "Droite",
      "Corps",
      "Pied de page",
    ]);
  });

  it("turns bulleted lines into a list, with indented continuation lines", () => {
    const blocks = layoutPdfPages([
      [
        line("Missions :", 700),
        line("• Premier élément qui continue", 688, 10, 60),
        line("sur la ligne suivante.", 676, 10, 80),
        line("- Second élément.", 664, 10, 60),
        line("Paragraphe après.", 630),
      ],
    ]);
    expect(blocks).toEqual([
      { type: "paragraph", c: ["Missions :"] },
      {
        type: "list",
        ordered: false,
        items: [
          { c: ["Premier élément qui continue sur la ligne suivante."], children: [] },
          { c: ["Second élément."], children: [] },
        ],
      },
      { type: "paragraph", c: ["Paragraphe après."] },
    ]);
  });

  it("ends a paragraph after a short line ending a sentence", () => {
    const long = (str: string, y: number): PdfTextItem => ({
      str, x: 50, y, width: 500, height: 10, hasEOL: true,
    });
    const blocks = layoutPdfPages([
      [
        long("Une longue ligne qui occupe toute la largeur de la page", 700),
        { str: "fin du paragraphe.", x: 50, y: 688, width: 200, height: 10, hasEOL: true },
        long("Nouveau paragraphe sans espace vertical supplémentaire", 676),
      ],
    ]);
    expect(blocks).toHaveLength(2);
  });
});
