"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tree_builder_exports = {};
__export(tree_builder_exports, {
  buildAlphabeticalGroups: () => buildAlphabeticalGroups,
  buildTree: () => buildTree
});
module.exports = __toCommonJS(tree_builder_exports);
const buildTree = (headings) => {
  const roots = [];
  const stack = [];
  headings.forEach((heading) => {
    const item = {
      ...heading,
      children: []
    };
    while (stack.length > 0 && stack[stack.length - 1].level >= heading.level) {
      stack.pop();
    }
    const parent = stack[stack.length - 1];
    if (parent) {
      parent.children.push(item);
    } else {
      roots.push(item);
    }
    stack.push(item);
  });
  return roots;
};
const alphabeticalIndexCollator = (() => {
  try {
    return new Intl.Collator(void 0, { sensitivity: "base", numeric: true });
  } catch {
    return { compare: (a, b) => a.localeCompare(b) };
  }
})();
const getAlphabeticalIndexLetter = (text) => {
  const firstCharacter = text.trim().charAt(0).toUpperCase();
  return /^[A-Z]$/.test(firstCharacter) ? firstCharacter : "#";
};
const buildAlphabeticalGroups = (headings) => {
  const sortedHeadings = [...headings].sort((left, right) => {
    const textComparison = alphabeticalIndexCollator.compare(left.text, right.text);
    if (textComparison !== 0) {
      return textComparison;
    }
    return alphabeticalIndexCollator.compare(left.nodeId, right.nodeId);
  });
  return sortedHeadings.reduce((groups, heading) => {
    const letter = getAlphabeticalIndexLetter(heading.text);
    const existingGroup = groups[groups.length - 1];
    if (!existingGroup || existingGroup.letter !== letter) {
      groups.push({
        letter,
        items: [heading]
      });
      return groups;
    }
    existingGroup.items.push(heading);
    return groups;
  }, []);
};
//# sourceMappingURL=tree-builder.js.map
