export class ScrollSpyManager {
    constructor(sections, navLinksSelector, containerId, thresholdOffset = 0.5) {
        var _a;
        this.ticking = false;
        this.sections = sections;
        this.navLinks = document.querySelectorAll(navLinksSelector);
        this.scrollContainer = containerId
            ? ((_a = document.getElementById(containerId)) !== null && _a !== void 0 ? _a : window)
            : window;
        this.thresholdOffset = thresholdOffset;
        this.bindScrollListener();
        this.updateActiveLink();
    }
    bindScrollListener() {
        const container = this.scrollContainer === window ? window : this.scrollContainer;
        container.addEventListener("scroll", () => this.onScroll(), {
            passive: true,
        });
    }
    onScroll() {
        if (!this.ticking) {
            window.requestAnimationFrame(() => {
                this.updateActiveLink();
                this.ticking = false;
            });
            this.ticking = true;
        }
    }
    updateActiveLink() {
        if (!this.sections || this.sections.length === 0 || !this.navLinks)
            return;
        const scrollY = this.scrollContainer instanceof Window
            ? window.scrollY
            : this.scrollContainer.scrollTop;
        let activeId = null;
        for (const section of this.sections) {
            const id = section.getAttribute("id");
            if (!id)
                continue;
            const top = section.offsetTop;
            const height = section.offsetHeight;
            const threshold = top - height * this.thresholdOffset;
            if (scrollY >= threshold) {
                activeId = id;
            }
        }
        this.navLinks.forEach((link) => {
            var _a;
            const targetId = (_a = link.getAttribute("href")) === null || _a === void 0 ? void 0 : _a.replace("#", "");
            const isActive = targetId === activeId;
            link.classList.toggle("active", isActive);
            let parent = link.parentElement;
            while (parent && parent !== document.body) {
                if (parent.tagName === "LI") {
                    parent.classList.remove("active");
                }
                parent = parent.parentElement;
            }
            if (isActive) {
                let parent = link.parentElement;
                while (parent && parent !== document.body) {
                    if (parent.tagName === "LI") {
                        parent.classList.add("active");
                    }
                    parent = parent.parentElement;
                }
            }
        });
    }
}
//# sourceMappingURL=ScrollSpyManager.js.map