/**
 * @jest-environment jsdom
 */
// chrome.ts imports createDropdown from reading-mode.ts directly (for the
// collapsed dropdown groups) and renderLeaf (which itself pulls in
// reading-mode.ts too) — reading-mode.ts's Vite-only `import.meta.env` usage
// isn't something ts-jest can parse, so both are stubbed. The createDropdown
// stub reproduces its real <details><summary/><div class="dropdown-content">
// shape (see reading-mode.ts) since renderNav queries into it.
jest.mock("../../../src/reader-view/render-leaf", () => ({
  renderLeaf: jest.fn((leaf: { name?: string; content?: string; href?: string }, parent: HTMLElement) => {
    const el = document.createElement(leaf.name || "div");
    el.textContent = leaf.content || "";
    if (leaf.href != undefined) el.setAttribute("href", leaf.href);
    parent.append(el);
  }),
}));
jest.mock("../../../src/reading-mode", () => ({
  createDropdown: jest.fn((parent: HTMLElement) => {
    const details = document.createElement("details");
    details.className = "dropdown";
    details.append(document.createElement("summary"));
    const content = document.createElement("div");
    content.className = "dropdown-content";
    details.append(content);
    parent.append(details);
    return details;
  }),
}));

import { renderNav } from "../../../src/reader-view/renderers/chrome";
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: "nav",
    c: 1,
    r: [-1, -1],
    children: [],
    ...overrides,
  };
}

function makeContext(leaves: ReaderObject[]): RenderContext {
  return {
    calendarLang: "fr",
    leavesOf: () => leaves,
    renderInto: () => {
      throw new Error("renderNav should not need renderInto");
    },
  };
}

describe("renderNav", () => {
  it("groups links under a preceding non-link label into a collapsed dropdown (lisio.fr's 'Solutions'/'À propos' shape)", () => {
    const leaves: ReaderObject[] = [
      { position: 0, name: "a", content: "Accueil", href: "https://lisio.fr/" },
      { position: 1, name: "button", content: "Solutions" },
      { position: 2, name: "a", content: "Extension navigateur", href: "https://lisio.fr/extension" },
      { position: 3, name: "a", content: "Application mobile", href: "https://lisio.fr/app" },
      { position: 4, name: "span", content: "À propos" },
      { position: 5, name: "a", content: "Notre équipe", href: "https://lisio.fr/equipe" },
    ];
    const nav = block({ i: 0, l: [0, 1, 2, 3, 4, 5], n: "Menu principal" });
    const ctx = makeContext(leaves);

    const parent = document.createElement("div");
    renderNav(nav, ctx, parent);

    const list = parent.querySelector("nav.lisio-nav > ul");
    expect(list).not.toBeNull();

    // "Accueil" has no label before it — stays a flat top-level item.
    const topLevelLinks = Array.from(list?.children ?? [])
      .filter((li) => li.querySelector("details") == undefined)
      .map((li) => li.textContent?.trim());
    expect(topLevelLinks).toEqual(["Accueil"]);

    // "Solutions" and "À propos" each become their own collapsed group,
    // instead of being dropped and their links flattened in with "Accueil".
    const summaries = Array.from(list?.querySelectorAll("summary") ?? []).map((s) =>
      s.textContent?.trim(),
    );
    expect(summaries).toEqual(["Solutions", "À propos"]);

    const groups = Array.from(list?.querySelectorAll(".lisio-nav-group") ?? []);
    expect(groups).toHaveLength(2);

    const solutionsLinks = Array.from(
      groups[0].querySelectorAll(".dropdown-content li"),
    ).map((li) => li.textContent?.trim());
    expect(solutionsLinks).toEqual(["Extension navigateur", "Application mobile"]);

    const aProposLinks = Array.from(
      groups[1].querySelectorAll(".dropdown-content li"),
    ).map((li) => li.textContent?.trim());
    expect(aProposLinks).toEqual(["Notre équipe"]);
  });

  it("drops a label with no links actually following it instead of leaving an empty dropdown", () => {
    const leaves: ReaderObject[] = [
      { position: 0, name: "a", content: "Accueil", href: "https://lisio.fr/" },
      { position: 1, name: "button", content: "Solutions" },
    ];
    const nav = block({ i: 0, l: [0, 1] });
    const ctx = makeContext(leaves);

    const parent = document.createElement("div");
    renderNav(nav, ctx, parent);

    expect(parent.querySelector(".lisio-nav-group")).toBeNull();
    expect(parent.querySelectorAll("li")).toHaveLength(1);
  });

  it("falls back to a flat list when the nav has no links at all", () => {
    const leaves: ReaderObject[] = [
      { position: 0, name: "button", content: "Rechercher" },
      { position: 1, name: "button", content: "Fermer" },
    ];
    const nav = block({ i: 0, l: [0, 1] });
    const ctx = makeContext(leaves);

    const parent = document.createElement("div");
    renderNav(nav, ctx, parent);

    expect(parent.querySelector(".lisio-nav-group")).toBeNull();
    expect(parent.querySelector("details")).toBeNull();
    const items = Array.from(parent.querySelectorAll("nav.lisio-nav > ul > li")).map((li) =>
      li.textContent?.trim(),
    );
    expect(items).toEqual(["Rechercher", "Fermer"]);
  });
});
