/**
 * @jest-environment jsdom
 */
import { LightBlock } from "../../../src/adapters/reader/light-reader-types";
import {
  renderLightContent,
  updateLightContent,
} from "../../../src/reader-view/render-light";

function render(blocks: LightBlock[], onLinkClick = jest.fn()) {
  const container = document.createElement("main");
  renderLightContent(blocks, container, onLinkClick);
  return container;
}

describe("renderLightContent", () => {
  it("renders every block type", () => {
    const container = render([
      { type: "heading", level: 2, c: ["Titre"] },
      { type: "paragraph", c: ["a ", { t: "strong", c: ["b"] }, { t: "br" }, { t: "em", c: ["c"] }] },
      { type: "quote", c: ["cit"] },
      { type: "pre", text: "x\n  y" },
      {
        type: "list",
        ordered: false,
        items: [
          {
            c: ["item"],
            children: [{ type: "list", ordered: true, items: [{ c: ["sub"], children: [] }] }],
          },
        ],
      },
      { type: "image", src: "https://example.com/i.png", alt: "Image" },
    ]);
    expect(container.innerHTML).toBe(
      "<h2>Titre</h2>" +
        "<p>a <strong>b</strong><br><em>c</em></p>" +
        "<blockquote>cit</blockquote>" +
        "<pre>x\n  y</pre>" +
        "<ul><li><p>item</p><ol><li>sub</li></ol></li></ul>" +
        '<img src="https://example.com/i.png" alt="Image" loading="lazy">',
    );
  });

  it("marks blocks and list items with their scroll anchor", () => {
    const container = render([
      { type: "heading", level: 1, c: ["T"], a: 0 },
      {
        type: "list",
        ordered: false,
        a: 1,
        items: [{ c: ["x"], children: [], a: 2 }],
      },
      { type: "paragraph", c: ["sans ancre"] },
    ]);
    expect(
      Array.from(container.querySelectorAll<HTMLElement>("[data-anchor]")).map(
        (el) => `${el.localName}:${el.dataset.anchor}`,
      ),
    ).toEqual(["h1:0", "ul:1", "li:2"]);
  });

  it("sets the language of blocks in another language", () => {
    const container = render([
      { type: "paragraph", c: ["Bonjour"] },
      { type: "quote", c: ["Hello"], lang: "en" },
    ]);
    expect(container.innerHTML).toBe(
      '<p>Bonjour</p><blockquote lang="en">Hello</blockquote>',
    );
  });

  it("renders nothing for an unresolved pdf placeholder", () => {
    const container = render([
      { type: "pdf", src: "https://example.com/doc.pdf", title: "doc.pdf", a: 0 },
      { type: "paragraph", c: ["après"] },
    ]);
    expect(container.innerHTML).toBe("<p>après</p>");
  });

  it("never parses text as HTML", () => {
    const container = render([
      { type: "paragraph", c: ['<script>alert(1)</script><img src=x onerror="alert(1)">'] },
    ]);
    expect(container.querySelector("script, img")).toBeNull();
    expect(container.textContent).toContain("<script>");
  });

  it("wires links to the click handler", () => {
    const onLinkClick = jest.fn();
    const container = render(
      [
        {
          type: "paragraph",
          c: [{ t: "a", href: "https://example.com/x", blank: true, c: ["Lien"] }],
        },
      ],
      onLinkClick,
    );
    const a = container.querySelector("a");
    expect(a?.getAttribute("href")).toBe("https://example.com/x");
    expect(a?.dataset.blank).toBe("true");
    a?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
    expect(onLinkClick).toHaveBeenCalledWith(
      expect.any(MouseEvent),
      "https://example.com/x",
      true,
    );
  });
});

describe("updateLightContent", () => {
  const anchors = (container: HTMLElement) =>
    Array.from(container.querySelectorAll<HTMLElement>("[data-anchor]")).map(
      (el) => `${el.localName}:${el.dataset.anchor}`,
    );

  it("keeps the elements of unchanged blocks (carousel slide swapped)", () => {
    const container = render([
      { type: "heading", level: 2, c: ["Galerie"], a: 0 },
      { type: "image", src: "https://example.com/a.jpg", alt: "a", a: 1 },
      { type: "paragraph", c: ["Après"], a: 2 },
    ]);
    const [heading, image, paragraph] = Array.from(container.children);
    // Adaptation posée par le Lisio de la fenêtre de lecture : doit survivre.
    heading.setAttribute("data-adapted", "1");

    updateLightContent(
      [
        { type: "heading", level: 2, c: ["Galerie"], a: 0 },
        { type: "image", src: "https://example.com/b.jpg", alt: "b", a: 1 },
        { type: "paragraph", c: ["Après"], a: 2 },
      ],
      container,
      jest.fn(),
    );

    const children = Array.from(container.children);
    expect(children[0]).toBe(heading);
    expect(children[0].getAttribute("data-adapted")).toBe("1");
    expect(children[1]).not.toBe(image);
    expect(children[1].getAttribute("src")).toBe("https://example.com/b.jpg");
    expect(children[2]).toBe(paragraph);
    expect(anchors(container)).toEqual(["h2:0", "img:1", "p:2"]);
  });

  it("re-numbers the anchors of kept blocks, list items included", () => {
    const list: LightBlock = {
      type: "list",
      ordered: false,
      a: 1,
      items: [
        {
          c: ["x"],
          a: 2,
          children: [{ type: "list", ordered: true, a: 3, items: [{ c: ["y"], children: [], a: 4 }] }],
        },
      ],
    };
    const container = render([{ type: "paragraph", c: ["Avant"], a: 0 }, list]);
    const ul = container.querySelector("ul");

    updateLightContent(
      [
        { type: "paragraph", c: ["Avant"], a: 0 },
        { type: "image", src: "https://example.com/new.jpg", alt: "", a: 1 },
        {
          ...list,
          a: 2,
          items: [
            {
              c: ["x"],
              a: 3,
              children: [{ type: "list", ordered: true, a: 4, items: [{ c: ["y"], children: [], a: 5 }] }],
            },
          ],
        },
      ],
      container,
      jest.fn(),
    );

    expect(container.querySelector("ul")).toBe(ul);
    expect(anchors(container)).toEqual(["p:0", "img:1", "ul:2", "li:3", "ol:4", "li:5"]);
  });

  it("follows reordered and removed blocks", () => {
    const container = render([
      { type: "paragraph", c: ["A"] },
      { type: "paragraph", c: ["B"] },
      { type: "paragraph", c: ["C"] },
    ]);
    const [a, , c] = Array.from(container.children);

    updateLightContent(
      [
        { type: "paragraph", c: ["C"] },
        { type: "paragraph", c: ["A"] },
      ],
      container,
      jest.fn(),
    );

    expect(container.innerHTML).toBe("<p>C</p><p>A</p>");
    expect(container.children[0]).toBe(c);
    expect(container.children[1]).toBe(a);
  });

  it("renders from scratch when the container was emptied in between", () => {
    const container = render([{ type: "paragraph", c: ["A"] }]);
    container.textContent = "";
    container.append("Extraction impossible");

    updateLightContent([{ type: "paragraph", c: ["A"] }], container, jest.fn());

    expect(container.innerHTML).toBe("<p>A</p>");
  });
});
