"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 sectionGrouper_exports = {};
__export(sectionGrouper_exports, {
  JUNK_SECTION_NAME_PATTERN: () => JUNK_SECTION_NAME_PATTERN,
  resolveSections: () => resolveSections
});
module.exports = __toCommonJS(sectionGrouper_exports);
var import_slug = require("./slug");
const JUNK_SECTION_NAME_PATTERN = /^(content|section|untitled|main|overview|details)$/i;
function isJunk(candidateSlug) {
  return !candidateSlug || JUNK_SECTION_NAME_PATTERN.test(candidateSlug);
}
function resolveSections(inputs) {
  const assignments = {};
  const candidatesByAnchorKey = /* @__PURE__ */ new Map();
  const elementsByAnchorKey = /* @__PURE__ */ new Map();
  const headingAnchorChainByElement = /* @__PURE__ */ new Map();
  for (const inp of inputs) {
    const { landmarkAncestor, sectioningAncestor, headingAncestry } = inp.ancestry;
    if (landmarkAncestor) {
      const name = landmarkAncestor.nameHint;
      assignments[inp.id] = name;
      candidatesByAnchorKey.set(landmarkAncestor.anchorKey, {
        name,
        landmark: landmarkAncestor.landmark,
        anchorKey: landmarkAncestor.anchorKey
      });
      const arr2 = elementsByAnchorKey.get(landmarkAncestor.anchorKey) ?? [];
      arr2.push(inp.id);
      elementsByAnchorKey.set(landmarkAncestor.anchorKey, arr2);
      continue;
    }
    if (sectioningAncestor) {
      const rawName = sectioningAncestor.accessibleName;
      if (rawName) {
        const candidateSlug = (0, import_slug.slug)(rawName);
        if (!isJunk(candidateSlug)) {
          assignments[inp.id] = candidateSlug;
          candidatesByAnchorKey.set(sectioningAncestor.anchorKey, {
            name: candidateSlug,
            landmark: "other",
            landmarkOther: sectioningAncestor.tagName,
            anchorKey: sectioningAncestor.anchorKey
          });
          const arr2 = elementsByAnchorKey.get(sectioningAncestor.anchorKey) ?? [];
          arr2.push(inp.id);
          elementsByAnchorKey.set(sectioningAncestor.anchorKey, arr2);
          continue;
        }
      }
    }
    let assignedFromHeading = false;
    for (let i = headingAncestry.length - 1; i >= 0; i--) {
      const h = headingAncestry[i];
      const candidateSlug = (0, import_slug.slug)(h.text);
      if (!isJunk(candidateSlug)) {
        let finalName = candidateSlug;
        let suffix = 2;
        while ([...candidatesByAnchorKey.values()].some((c) => c.name === finalName && c.anchorKey !== h.anchorKey)) {
          finalName = `${candidateSlug}_${suffix++}`;
        }
        assignments[inp.id] = finalName;
        candidatesByAnchorKey.set(h.anchorKey, {
          name: finalName,
          landmark: "other",
          landmarkOther: "heading",
          anchorKey: h.anchorKey
        });
        const arr2 = elementsByAnchorKey.get(h.anchorKey) ?? [];
        arr2.push(inp.id);
        elementsByAnchorKey.set(h.anchorKey, arr2);
        headingAnchorChainByElement.set(
          inp.id,
          headingAncestry.map((hh) => hh.anchorKey)
        );
        assignedFromHeading = true;
        break;
      }
    }
    if (assignedFromHeading) continue;
    assignments[inp.id] = "page";
    const pageAnchorKey = "page-fallback";
    candidatesByAnchorKey.set(pageAnchorKey, { name: "page", landmark: "region", anchorKey: pageAnchorKey });
    const arr = elementsByAnchorKey.get(pageAnchorKey) ?? [];
    arr.push(inp.id);
    elementsByAnchorKey.set(pageAnchorKey, arr);
  }
  const candidateAnchorKeysWithElements = new Set(
    [...elementsByAnchorKey.entries()].filter(([, ids]) => ids.length > 0).map(([k]) => k)
  );
  const toDrop = /* @__PURE__ */ new Set();
  for (const [anchorKey, info] of candidatesByAnchorKey.entries()) {
    if (info.landmarkOther !== "heading") continue;
    let isAncestor = false;
    for (const [, chain] of headingAnchorChainByElement.entries()) {
      const idx = chain.indexOf(anchorKey);
      if (idx === -1) continue;
      for (let j = idx + 1; j < chain.length; j++) {
        const deeperKey = chain[j];
        if (candidateAnchorKeysWithElements.has(deeperKey) && deeperKey !== anchorKey) {
          isAncestor = true;
          break;
        }
      }
      if (isAncestor) break;
    }
    if (isAncestor) toDrop.add(anchorKey);
  }
  for (const droppedKey of toDrop) {
    const affectedIds = elementsByAnchorKey.get(droppedKey) ?? [];
    for (const id of affectedIds) {
      const chain = headingAnchorChainByElement.get(id) ?? [];
      let reassigned = null;
      for (let i = chain.length - 1; i >= 0; i--) {
        const k = chain[i];
        if (k === droppedKey) continue;
        if (toDrop.has(k)) continue;
        const cand = candidatesByAnchorKey.get(k);
        if (cand && cand.landmarkOther === "heading") {
          reassigned = cand.name;
          break;
        }
      }
      assignments[id] = reassigned ?? "page";
    }
    candidatesByAnchorKey.delete(droppedKey);
    elementsByAnchorKey.delete(droppedKey);
  }
  const sections = [];
  const seenNames = /* @__PURE__ */ new Set();
  const assignmentOrder = [];
  for (const inp of inputs) {
    const name = assignments[inp.id];
    if (name && !assignmentOrder.includes(name)) assignmentOrder.push(name);
  }
  for (const name of assignmentOrder) {
    if (seenNames.has(name)) continue;
    seenNames.add(name);
    const info = [...candidatesByAnchorKey.values()].find((c) => c.name === name);
    if (info) {
      sections.push({ name: info.name, landmark: info.landmark, landmarkOther: info.landmarkOther });
    } else if (name === "page") {
      sections.push({ name: "page", landmark: "region" });
    }
  }
  return { assignments, sections };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  JUNK_SECTION_NAME_PATTERN,
  resolveSections
});
