/**
 * journalPagination — deterministic line-cap pagination for the gardener's
 * journal (Bekky's model, 2026-08-12).
 *
 * Each page has a FIXED line budget. Content is a sequence of "blocks" (a
 * section heading, a sub-heading, or a task entry). Each block consumes a
 * known number of lines. We pack blocks greedily onto pages:
 *   - a page can be LESS than the cap, never MORE
 *   - if the next block would push a page over the cap, it starts the next page
 *
 * This is deterministic — no pixel measurement. The parent decides each block's
 * line count (e.g. a task with a short brief = 3 lines, a long brief = 4).
 */

export type JournalBlock = {
  /** Stable key for React. */
  key: string;
  /** How many lines this block occupies. */
  lines: number;
  /** The rendered node for this block. */
  node: React.ReactNode;
};

/**
 * Pack blocks into pages under a line cap. Returns an array of pages, each an
 * array of blocks. A block whose lines exceed the cap is still placed on its
 * own page (never dropped).
 */
export function packBlocksIntoPages(blocks: JournalBlock[], lineCap: number): JournalBlock[][] {
  const pages: JournalBlock[][] = [];
  let current: JournalBlock[] = [];
  let used = 0;

  for (const block of blocks) {
    // If this block alone exceeds the cap, it gets its own page.
    if (block.lines > lineCap) {
      if (current.length) {
        pages.push(current);
        current = [];
        used = 0;
      }
      pages.push([block]);
      continue;
    }
    // If adding this block would exceed the cap, start a new page.
    if (used + block.lines > lineCap && current.length) {
      pages.push(current);
      current = [];
      used = 0;
    }
    current.push(block);
    used += block.lines;
  }
  if (current.length) pages.push(current);
  return pages;
}
