
document.addEventListener('DOMContentLoaded', function () {
    const contentSelector = '.sifency-post-content-wrapper, .elementor-widget-theme-post-content, .entry-content';
    const tocRoot = document.getElementById('sifency-toc-root');
    const contentWrap = document.querySelector(contentSelector);

    if (!contentWrap || !tocRoot) return;

    const headings = contentWrap.querySelectorAll('h1, h2');
    if (headings.length === 0) {
        tocRoot.parentElement.style.display = 'none';
        return;
    }

    let tocHTML = '';
    let currentSubListId = null;
    let hasOpenTag = false;

    headings.forEach((h, index) => {
        if (!h.id) {
            h.id = h.textContent.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '') || `section-${index}`;
        }

        if (h.tagName === 'H1') {
            if (hasOpenTag) {
                tocHTML += '</ul></div>';
            }

            tocHTML += `
                    <div class="toc-item-h1" id="nav-item-${h.id}">
                        <div class="toc-header">
                            <span class="toc-toggle"></span>
                            <a href="#${h.id}" class="toc-link-h1" data-target="${h.id}">${h.textContent}</a>
                        </div>
                        <ul class="toc-sub-list">
                    `;
            hasOpenTag = true;
        }
        else if (h.tagName === 'H2') {
            if (!hasOpenTag) {
                tocHTML += '<div class="toc-item-h1 no-parent"><ul class="toc-sub-list" style="max-height:none">';
                hasOpenTag = true;
            }
            tocHTML += `<li><a href="#${h.id}" class="toc-link-h2" data-target="${h.id}">${h.textContent}</a></li>`;
        }
    });

    if (hasOpenTag) tocHTML += '</ul></div>';
    tocRoot.innerHTML = tocHTML;

    tocRoot.querySelectorAll('.toc-header').forEach(header => {
        header.addEventListener('click', function (e) {
            const parent = this.parentElement;

            if (!e.target.classList.contains('toc-link-h1')) {
                e.preventDefault();
            }

            parent.classList.toggle('open');
        });
    });

    const links = document.querySelectorAll('.toc-link-h1, .toc-link-h2');
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const id = entry.target.id;

                document.querySelectorAll('.is-active, .toc-item-h1.active').forEach(el => {
                    el.classList.remove('is-active', 'active');
                });

                const activeLink = document.querySelector(`[data-target="${id}"]`);
                if (activeLink) {
                    activeLink.classList.add('is-active');

                    const parentItem = activeLink.closest('.toc-item-h1');
                    if (parentItem) {
                        parentItem.classList.add('active');
                        if (!parentItem.classList.contains('open')) {
                            parentItem.classList.add('open');
                        }
                    }
                }
            }
        });
    }, { rootMargin: '-100px 0px -65% 0px' });

    headings.forEach(h => observer.observe(h));
});