/**
 * @jest-environment jsdom
 */
// content.ts also imports renderLeaf for renderList's sake, which transitively
// pulls in reading-mode.ts and its Vite-only `import.meta.env` usage — not
// something ts-jest can parse. renderSection never calls it, so stub it out.
jest.mock("../../../src/reader-view/render-leaf", () => ({ renderLeaf: jest.fn() }));

import { renderSection } from "../../../src/reader-view/renderers/content";
import { BlockTreeNode } from "../../../src/reader-view/block-tree";
import { RenderContext } from "../../../src/reader-view/render-context";
import { ReaderObject } from "../../../src/adapters/reader/lisio-reader-adapter";

function block(overrides: Partial<BlockTreeNode> & Pick<BlockTreeNode, "i" | "l">): BlockTreeNode {
  return {
    p: null,
    k: "section",
    c: 1,
    r: [-1, -1],
    children: [],
    ...overrides,
  };
}

function makeContext(leavesByBlock: Map<number, ReaderObject[]>): RenderContext {
  return {
    calendarLang: "fr",
    leavesOf: (b) => leavesByBlock.get(b.i) ?? [],
    renderInto: (b, parent) => {
      for (const leaf of leavesByBlock.get(b.i) ?? []) {
        const el = document.createElement(leaf.name || "div");
        el.textContent = leaf.content || "";
        parent.append(el);
      }
      for (const child of b.children) renderSection(child, makeContext(leavesByBlock), parent);
    },
  };
}

describe("renderSection", () => {
  it("does not synthesize a duplicate heading when the label heading is one of the block's own leaves", () => {
    // Reproduces lisio.fr's hero: segmentation collapses the intermediate
    // wrapper divs, so the section's own leaves are [p, h1, p] (the h1 isn't
    // leaves[0]) while its label — extracted via querySelector — is that
    // same h1's text.
    const heroLeaves: ReaderObject[] = [
      { position: 0, name: "p", content: "Bienvenue dans vos espaces numériques" },
      { position: 1, name: "h1", content: "Améliorez l'expérience en ligne de vos internautes" },
      { position: 2, name: "p", content: "Redonnons le sourire à vos internautes." },
    ];
    const hero = block({
      i: 0,
      l: [0, 1, 2],
      n: "Améliorez l'expérience en ligne de vos internautes",
    });
    const ctx = makeContext(new Map([[0, heroLeaves]]));

    const parent = document.createElement("div");
    renderSection(hero, ctx, parent);

    const headings = Array.from(parent.querySelectorAll("h1, h2")).map((el) => el.textContent);
    expect(headings).toEqual(["Améliorez l'expérience en ligne de vos internautes"]);
  });

  it("still synthesizes a heading for a section whose own content never repeats the label", () => {
    const leaves: ReaderObject[] = [
      { position: 0, name: "p", content: "Un paragraphe sans titre propre." },
    ];
    const section = block({ i: 0, l: [0], n: "Nos actualités" });
    const ctx = makeContext(new Map([[0, leaves]]));

    const parent = document.createElement("div");
    renderSection(section, ctx, parent);

    const heading = parent.querySelector("h2");
    expect(heading?.textContent).toBe("Nos actualités");
  });

  it("does not synthesize a duplicate heading when the label heading belongs to a nested child block", () => {
    const childLeaves: ReaderObject[] = [
      { position: 0, name: "h1", content: "Améliorez l'expérience en ligne de vos internautes" },
      { position: 1, name: "p", content: "Bienvenue." },
    ];
    const child = block({ i: 1, l: [0, 1] });
    const wrapper = block({
      i: 0,
      l: [],
      n: "Améliorez l'expérience en ligne de vos internautes",
      children: [child],
    });
    const ctx = makeContext(
      new Map([
        [0, []],
        [1, childLeaves],
      ]),
    );

    const parent = document.createElement("div");
    renderSection(wrapper, ctx, parent);

    const headings = Array.from(parent.querySelectorAll("h1, h2")).map((el) => el.textContent);
    expect(headings).toEqual(["Améliorez l'expérience en ligne de vos internautes"]);
  });
});
