import { ReaderObject } from "../adapters/reader/lisio-reader-adapter";
import { BlockKind, SerializedBlockTree } from "../adapters/reader/structure/block-types";
import { renderLeaf } from "./render-leaf";
import { BlockTreeNode, buildBlockTree } from "./block-tree";
import { RenderContext } from "./render-context";
import { renderCollapsedChrome, renderNav } from "./renderers/chrome";
import { renderCard, renderCardList } from "./renderers/cards";
import { renderContentGroup, renderList, renderMain, renderSection } from "./renderers/content";
import { renderGallery } from "./renderers/gallery";
import { renderPassthrough } from "./renderers/passthrough";

type BlockRenderer = (block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement) => void;

const BLOCK_RENDERERS: Partial<Record<BlockKind, BlockRenderer>> = {
  main: renderMain,
  article: renderMain,
  section: renderSection,
  cardList: renderCardList,
  card: (block, ctx, parent) => renderCard(block, ctx, parent),
  gallery: renderGallery,
  list: renderList,
  contentGroup: renderContentGroup,
  nav: renderNav,
  header: (block, ctx, parent) => renderCollapsedChrome(block, ctx, parent, "En-tête du site"),
  footer: (block, ctx, parent) => renderCollapsedChrome(block, ctx, parent, "Pied de page"),
  aside: (block, ctx, parent) => renderCollapsedChrome(block, ctx, parent, "Informations complémentaires"),
  table: renderPassthrough,
  form: renderPassthrough,
  calendar: renderPassthrough,
  embed: renderPassthrough,
};

/**
 * Rendering rank for a block's DIRECT CHILDREN under `<main>` (or, when
 * this document has no detected `main`, at the top level). Content-shaped
 * kinds come first so the article is always what the user sees first;
 * navigational chrome comes last (collapsed).
 */
const RENDER_ORDER: BlockKind[] = [
  "breadcrumb",
  "search",
  "main",
  "article",
  "section",
  "cardList",
  "gallery",
  "table",
  "form",
  "calendar",
  "list",
  "contentGroup",
  "embed",
  "pagination",
  "aside",
  "nav",
  "header",
  "toolbar",
  "footer",
];

function rankOf(kind: BlockKind): number {
  const i = RENDER_ORDER.indexOf(kind);
  return i === -1 ? RENDER_ORDER.length : i;
}

/** consent/promo (dropped leaves) and unhandled milestone-2 kinds are ignored gracefully. */
function isRenderable(kind: BlockKind): boolean {
  return BLOCK_RENDERERS[kind] != undefined;
}

/**
 * Entry point called from reading-mode.ts's BCMR_INIT_HTML handler when
 * `value.structure` is present AND non-empty (an empty/bailed structure
 * means the caller should use the flat v1 path instead — this function
 * assumes it will actually find a root block to render).
 *
 * `container` is the top-level element (`main`). `texts` is the SAME flat
 * ReaderObject[] the v1 path renders — the block tree only says which
 * positions belong together, it never duplicates leaf content.
 */
export function renderBlockTree(
  structure: SerializedBlockTree,
  texts: ReaderObject[],
  container: HTMLElement,
  calendarLang: "fr" | "en",
): void {
  const leavesByPosition = new Map<number, ReaderObject>();
  for (const t of texts) leavesByPosition.set(t.position, t);

  const treeRoots = buildBlockTree(structure);

  const ctx: RenderContext = {
    calendarLang,
    leavesOf(block) {
      return block.l
        .map((pos) => leavesByPosition.get(pos))
        .filter((l): l is ReaderObject => l != undefined);
    },
    renderInto(block, parent) {
      interface Item {
        pos: number;
        render: () => void;
      }
      const items: Item[] = [];
      for (const pos of block.l) {
        const leaf = leavesByPosition.get(pos);
        if (leaf == undefined) continue;
        items.push({ pos, render: () => renderLeaf(leaf, parent, calendarLang) });
      }
      for (const child of block.children) {
        const pos = child.r[0] >= 0 ? child.r[0] : Number.MAX_SAFE_INTEGER;
        items.push({ pos, render: () => renderBlockNode(child, ctx, parent) });
      }
      items.sort((a, b) => a.pos - b.pos);
      for (const item of items) item.render();
    },
  };

  function renderBlockNode(block: BlockTreeNode, context: RenderContext, parent: HTMLElement): void {
    if (!isRenderable(block.k)) return; // consent/promo and not-yet-implemented milestone-2 kinds: silently skipped
    const renderer = BLOCK_RENDERERS[block.k];
    renderer?.(block, context, parent);
  }

  /**
   * The synthetic root's DIRECT children get the RENDER_ORDER treatment
   * (main first, chrome last) — that reordering is intentionally a
   * top-level-only behaviour; every other container renders its own
   * children in natural document order via `ctx.renderInto`. Root's own
   * unassigned leaves (whatever the classifier couldn't confidently place)
   * are treated as if they were a "contentGroup"-ranked item, so they
   * surface near the real content instead of being dumped after the
   * collapsed chrome.
   */
  function renderRoot(rootNode: BlockTreeNode, parent: HTMLElement): void {
    interface Item {
      rank: number;
      pos: number;
      render: () => void;
    }
    const items: Item[] = [];
    for (const pos of rootNode.l) {
      const leaf = leavesByPosition.get(pos);
      if (leaf == undefined) continue;
      items.push({
        rank: rankOf("contentGroup"),
        pos,
        render: () => renderLeaf(leaf, parent, calendarLang),
      });
    }
    for (const child of rootNode.children) {
      const pos = child.r[0] >= 0 ? child.r[0] : Number.MAX_SAFE_INTEGER;
      items.push({ rank: rankOf(child.k), pos, render: () => renderBlockNode(child, ctx, parent) });
    }
    items.sort((a, b) => a.rank - b.rank || a.pos - b.pos);
    for (const item of items) item.render();
  }

  for (const node of treeRoots) {
    if (node.k === "root") {
      renderRoot(node, container);
    } else {
      // Defensive: shouldn't happen given segment-page.ts always emits a
      // "root" wrapper when `blocks` is non-empty, but stay robust.
      renderBlockNode(node, ctx, container);
    }
  }
}
