import { ScrollSpyManager } from "../scroll/ScrollSpyManager.js";
export class TableOfContentsBuilder {
    constructor(rootId, tocContainerId) {
        this.idSet = new Set();
        this.linkSectionMap = new Map();
        this.rootId = rootId;
        this.tocContainerId = tocContainerId;
    }
    generateUniqueId(baseId) {
        let id = baseId
            .toLowerCase()
            .replace(/\s+/g, "-")
            .replace(/[^\w-]/g, "");
        let count = 1;
        while (this.idSet.has(id)) {
            id = `${baseId}-${count++}`;
        }
        this.idSet.add(id);
        return id;
    }
    createTOCEntry(element) {
        const text = element.getAttribute("data-label") || "Untitled";
        const id = this.generateUniqueId(text);
        element.id = id;
        const a = document.createElement("a");
        a.href = `#${id}`;
        a.textContent = text;
        const li = document.createElement("li");
        li.appendChild(a);
        this.linkSectionMap.set(a, element);
        return li;
    }
    buildTOCTree(element) {
        const ul = document.createElement("ul");
        Array.from(element.children).forEach((child) => {
            if (!(child instanceof HTMLElement))
                return;
            if (child.hasAttribute("data-label")) {
                const li = this.createTOCEntry(child);
                const nestedUL = this.buildTOCTree(child);
                if (nestedUL.children.length > 0) {
                    li.appendChild(nestedUL);
                }
                ul.appendChild(li);
            }
            else {
                const nested = this.buildTOCTree(child);
                if (nested.children.length > 0) {
                    ul.append(...Array.from(nested.children));
                }
            }
        });
        return ul;
    }
    buildAndAppendTOC() {
        const root = document.getElementById(this.rootId);
        const tocContainer = document.getElementById(this.tocContainerId);
        if (!root || !tocContainer)
            return;
        const tocTree = this.buildTOCTree(root);
        tocContainer.innerHTML = "";
        tocContainer.appendChild(tocTree);
        this.scrollSpyManager = new ScrollSpyManager(Array.from(this.linkSectionMap.values()), `#${this.tocContainerId} a`, this.rootId);
    }
    getLinkSectionMap() {
        return this.linkSectionMap;
    }
}
//# sourceMappingURL=TableOfContentsBuilder.js.map