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

export function renderMain(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  const article = document.createElement("article");
  article.className = "lisio-main";
  ctx.renderInto(block, article);
  if (article.childNodes.length > 0) parent.append(article);
}

function headingTextOf(html: string): string {
  const scratch = document.createElement("div");
  scratch.innerHTML = html;
  return (scratch.textContent || "").replace(/\s+/g, " ").trim();
}

/**
 * A block's label (`block.n`) comes from `extractLabel()`, which grabs the
 * first heading *anywhere in the source element's subtree* — it has no way
 * to know whether that same heading will also be rendered verbatim as one
 * of this block's own leaves (directly, or via a nested child block), since
 * label extraction runs before leaf assignment. When it will, synthesizing
 * an extra `<h2>` from the label just repeats that heading right above
 * itself. Checked recursively (not just this block's own leaves/first leaf)
 * because DOM levels collapsed during segmentation (see segment-page.ts's
 * `splitPoints` collapse) can leave the matching heading several leaves in,
 * or owned by a nested child block, rather than being `leavesOf(block)[0]`.
 */
function rendersOwnHeading(block: BlockTreeNode, ctx: RenderContext, label: string): boolean {
  const ownMatch = ctx
    .leavesOf(block)
    .some((leaf) => /^h[1-6]$/.test(leaf.name || "") && headingTextOf(leaf.content || "") === label);
  if (ownMatch) return true;
  return block.children.some((child) => rendersOwnHeading(child, ctx, label));
}

export function renderSection(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  const section = document.createElement("section");
  const label = block.n?.trim();
  if (label != undefined && label !== "" && !rendersOwnHeading(block, ctx, label)) {
    const heading = document.createElement("h2");
    heading.textContent = label;
    section.append(heading);
  }
  ctx.renderInto(block, section);
  if (section.childNodes.length > 0) parent.append(section);
}

export function renderList(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  const ul = document.createElement("ul");
  ul.className = "lisio-list";
  for (const leaf of ctx.leavesOf(block)) {
    const li = document.createElement("li");
    renderLeaf(leaf, li, ctx.calendarLang);
    if (li.childNodes.length > 0) ul.append(li);
  }
  if (ul.children.length > 0) parent.append(ul);
}

/** Transparent: no wrapper, leaves/children spliced straight into the parent. */
export function renderContentGroup(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  ctx.renderInto(block, parent);
}
