/**
 * Split flat navigation rows into sections using optional `header` markers.
 *
 * @typedef {{ header?: boolean, label?: string, key?: string, items?: unknown[], to?: string, path?: string }} NavItem
 * @param {NavItem[]} entries
 * @returns {{ title: string|null, entries: NavItem[] }[]}
 */
export function splitNavByHeaders(entries) {
  /** @type {{ title: string|null, entries: NavItem[] }[]} */
  const sections = [];
  let current = {
    title: /** @type {string|null} */ (null),
    entries: /** @type {NavItem[]} */ ([]),
  };

  const flush = () => {
    if (current.entries.length === 0 && current.title === null) {
      return;
    }
    sections.push({
      title: current.title,
      entries: [...current.entries],
    });
  };

  for (const e of entries ?? []) {
    if (!e) {
      continue;
    }
    if (e.header) {
      flush();
      current = { title: e.label ?? null, entries: [] };
    } else {
      current.entries.push(e);
    }
  }
  flush();

  return sections;
}
