import { createDropdown } from "../../reading-mode";
import { renderLeaf } from "../render-leaf";
import { BlockTreeNode } from "../block-tree";
import { RenderContext } from "../render-context";

/**
 * header / footer / aside: collapsed into a labelled `<details>`, reusing
 * `createDropdown()` verbatim — that keeps `BCMR_OPEN_DROPDOWN`'s
 * `closest("details")` working unchanged for these blocks too.
 */
export function renderCollapsedChrome(
  block: BlockTreeNode,
  ctx: RenderContext,
  parent: HTMLElement,
  defaultLabel: string,
): void {
  const details = createDropdown(parent);
  const summary = details.querySelector<HTMLElement>("summary");
  if (summary != undefined) summary.textContent = block.n ?? defaultLabel;
  const content = details.querySelector<HTMLElement>(".dropdown-content");
  if (content == undefined) return;
  ctx.renderInto(block, content);
}

/**
 * nav: an always-visible link list, one level deep. `block`'s own leaves are
 * flat and position-ordered (segment-page.ts deliberately merges any
 * nav-shaped descendant into this SAME block — see its `descend()` — rather
 * than nesting a child block renderNav would never visit), so there is no
 * explicit parent/child pointer between a dropdown's label and the links it
 * groups. Reconstruct it from DOM order instead: a leaf with no `href` of
 * its own (lisio.fr's "Solutions"/"À propos" — a `<button>`/`<span>`
 * dropdown TOGGLE, not a link) is treated as the start of a new group, and
 * every link leaf that follows it belongs to that group, up to the next
 * such label. Links before the first label (or when the nav has no labels
 * at all) stay flat top-level items, exactly as before.
 *
 * Each group renders as a collapsed `<details>` via `createDropdown()` —
 * the same building block header/footer/aside already collapse into (see
 * `renderCollapsedChrome`) — so it picks up that existing styling for free
 * instead of the label being silently dropped and its items flattened in
 * with everything else.
 */
export function renderNav(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  const nav = document.createElement("nav");
  nav.className = "lisio-nav";
  const heading = document.createElement("h2");
  heading.textContent = block.n ?? "Menu";
  nav.append(heading);
  const list = document.createElement("ul");
  nav.append(list);

  const leaves = ctx.leavesOf(block);
  const hasLinks = leaves.some((leaf) => leaf.name === "a");
  let currentGroup: HTMLUListElement | undefined;

  for (const leaf of leaves) {
    if (hasLinks && leaf.name !== "a") {
      const groupItem = document.createElement("li");
      groupItem.className = "lisio-nav-group";
      const details = createDropdown(groupItem);
      const summary = details.querySelector<HTMLElement>("summary");
      if (summary != undefined) summary.textContent = leaf.content || "";
      currentGroup = document.createElement("ul");
      details.querySelector<HTMLElement>(".dropdown-content")?.append(currentGroup);
      list.append(groupItem);
      continue;
    }

    const li = document.createElement("li");
    renderLeaf(leaf, li, ctx.calendarLang);
    if (li.childNodes.length === 0) continue;
    (currentGroup ?? list).append(li);
  }

  // A label with no links actually following it (trailing toggle, or two
  // labels back to back) would otherwise leave an empty, pointless dropdown.
  for (const groupItem of Array.from(list.querySelectorAll<HTMLLIElement>(".lisio-nav-group"))) {
    if (groupItem.querySelector("li") == undefined) groupItem.remove();
  }

  if (list.children.length > 0) parent.append(nav);
}
