/**
 * Enhanced Table of Contents with Hierarchy
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // Generate hierarchical table of contents
    const tocContainer = document.getElementById('table-of-contents');
    if (tocContainer) {
        const headings = document.querySelectorAll('.post-body h2, .post-body h3, .post-body h4, .post-body h5, .post-body h6');
        
        if (headings.length === 0) {
            tocContainer.parentElement.style.display = 'none';
        } else {
            const tocList = createHierarchicalTOC(headings);
            tocContainer.appendChild(tocList);
            
            // Add scroll spy functionality
            addScrollSpy(headings);
        }
    }
    
    // Create hierarchical TOC structure
    function createHierarchicalTOC(headings) {
        const tocList = document.createElement('ul');
        tocList.className = 'toc-list';
        
        let currentLevel = 2;
        let currentList = tocList;
        let listStack = [tocList];
        let counters = [0, 0, 0, 0, 0]; // h2, h3, h4, h5, h6
        
        headings.forEach((heading, index) => {
            const level = parseInt(heading.tagName.substring(1));
            const id = 'heading-' + index;
            heading.id = id;
            
            // Update counters
            const levelIndex = level - 2;
            counters[levelIndex]++;
            
            // Reset deeper level counters
            for (let i = levelIndex + 1; i < counters.length; i++) {
                counters[i] = 0;
            }
            
            // Generate number for TOC
            let number = '';
            for (let i = 0; i <= levelIndex; i++) {
                if (counters[i] > 0) {
                    number += (number ? '.' : '') + counters[i];
                }
            }
            
            // Handle hierarchy
            if (level > currentLevel) {
                // Going deeper - create nested list
                const nestedList = document.createElement('ul');
                const lastItem = currentList.lastElementChild;
                if (lastItem) {
                    lastItem.appendChild(nestedList);
                }
                currentList = nestedList;
                listStack.push(nestedList);
            } else if (level < currentLevel) {
                // Going back up - pop from stack
                const levelDiff = currentLevel - level;
                for (let i = 0; i < levelDiff; i++) {
                    listStack.pop();
                }
                currentList = listStack[listStack.length - 1];
            }
            
            currentLevel = level;
            
            // Create TOC item
            const listItem = document.createElement('li');
            listItem.className = 'toc-level-h' + level;
            
            const link = document.createElement('a');
            link.href = '#' + id;
            link.innerHTML = '<span class="toc-number">' + number + '</span>' + heading.textContent;
            link.setAttribute('data-heading-id', id);
            
            listItem.appendChild(link);
            currentList.appendChild(listItem);
        });
        
        return tocList;
    }
    
    // Add scroll spy functionality
    function addScrollSpy(headings) {
        const tocLinks = document.querySelectorAll('#table-of-contents a');
        
        function updateActiveTOC() {
            const scrollPosition = window.scrollY + 100;
            let activeHeading = null;
            
            headings.forEach(heading => {
                if (heading.offsetTop <= scrollPosition) {
                    activeHeading = heading;
                }
            });
            
            // Remove all active classes
            tocLinks.forEach(link => link.classList.remove('toc-active'));
            
            // Add active class to current section
            if (activeHeading) {
                const activeLink = document.querySelector(`a[data-heading-id="${activeHeading.id}"]`);
                if (activeLink) {
                    activeLink.classList.add('toc-active');
                }
            }
        }
        
        // Update on scroll
        window.addEventListener('scroll', updateActiveTOC);
        
        // Update on load
        updateActiveTOC();
    }
    
    // Smooth scrolling for TOC links
    document.querySelectorAll('#table-of-contents a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const target = document.getElementById(targetId);
            
            if (target) {
                const offsetTop = target.offsetTop - 100; // Account for any fixed headers
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
                
                // Update URL without scrolling
                history.pushState(null, null, '#' + targetId);
            }
        });
    });
    
    // Collapse/Expand TOC functionality (optional)
    const tocWidget = document.querySelector('.toc-widget');
    if (tocWidget) {
        const tocTitle = tocWidget.querySelector('.widget-title');
        if (tocTitle) {
            tocTitle.style.cursor = 'pointer';
            tocTitle.addEventListener('click', function() {
                const tocContent = tocWidget.querySelector('#table-of-contents');
                if (tocContent) {
                    tocContent.style.display = tocContent.style.display === 'none' ? 'block' : 'none';
                    this.classList.toggle('collapsed');
                }
            });
        }
    }
    
    // Add reading progress indicator
    function addReadingProgress() {
        const article = document.querySelector('.post-body');
        if (!article) return;
        
        const progressBar = document.createElement('div');
        progressBar.className = 'reading-progress';
        progressBar.innerHTML = '<div class="reading-progress-bar"></div>';
        
        // Add CSS for progress bar
        const style = document.createElement('style');
        style.textContent = `
            .reading-progress {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 4px;
                background: #f0f0f0;
                z-index: 1000;
                border-bottom: 2px solid #000;
            }
            .reading-progress-bar {
                height: 100%;
                background: #000;
                width: 0%;
                transition: width 0.2s ease;
            }
        `;
        document.head.appendChild(style);
        document.body.appendChild(progressBar);
        
        const progressBarFill = progressBar.querySelector('.reading-progress-bar');
        
        window.addEventListener('scroll', function() {
            const articleTop = article.offsetTop;
            const articleHeight = article.offsetHeight;
            const windowHeight = window.innerHeight;
            const scrollTop = window.scrollY;
            
            const articleBottom = articleTop + articleHeight;
            const windowBottom = scrollTop + windowHeight;
            
            if (scrollTop >= articleTop && scrollTop <= articleBottom) {
                const progress = ((scrollTop - articleTop) / (articleHeight - windowHeight)) * 100;
                progressBarFill.style.width = Math.min(Math.max(progress, 0), 100) + '%';
            }
        });
    }
    
    // Initialize reading progress
    if (document.querySelector('.single')) {
        addReadingProgress();
    }
});