/* ============================================
   POLANGER DOCUMENTATION - MAIN JAVASCRIPT
   ============================================ */

document.addEventListener('DOMContentLoaded', function() {
    // Initialize all components
    initSidebar();
    initSearch();
    initTabs();
    initAccordion();
    initBackToTop();
    initSmoothScroll();
    initActiveNavigation();
    initCodeCopy();
});

/* ============================================
   SIDEBAR
   ============================================ */

function initSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const toggle = document.querySelector('.mobile-menu-toggle');
    const navItems = document.querySelectorAll('.sidebar-nav-item');

    // Mobile menu toggle
    if (toggle) {
        toggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
            overlay.classList.toggle('active');
            document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
        });
    }

    // Close sidebar on overlay click
    if (overlay) {
        overlay.addEventListener('click', function() {
            sidebar.classList.remove('active');
            overlay.classList.remove('active');
            document.body.style.overflow = '';
        });
    }

    // Expandable nav items
    navItems.forEach(item => {
        const toggleBtn = item.querySelector('.sidebar-toggle');
        const subnav = item.querySelector('.sidebar-subnav');

        if (toggleBtn && subnav) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                item.classList.toggle('expanded');
            });

            // Also toggle on main link click if has subnav
            const mainLink = item.querySelector('.sidebar-nav-link');
            if (mainLink) {
                mainLink.addEventListener('click', function(e) {
                    if (subnav) {
                        e.preventDefault();
                        item.classList.toggle('expanded');
                    }
                });
            }
        }
    });

    // Close sidebar on link click (mobile)
    const sidebarLinks = document.querySelectorAll('.sidebar-subnav-link');
    sidebarLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth <= 1024) {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    });
}

/* ============================================
   SEARCH
   ============================================ */

function initSearch() {
    const searchInput = document.querySelector('.header-search input');
    const searchResults = document.querySelector('.search-results');

    if (!searchInput || !searchResults) return;

    // Search data - will be populated from page content
    const searchData = [];
    
    // Collect searchable content
    document.querySelectorAll('section[id]').forEach(section => {
        const title = section.querySelector('h2, h3');
        const content = section.textContent;
        
        if (title) {
            searchData.push({
                id: section.id,
                title: title.textContent.trim(),
                content: content.substring(0, 500).trim()
            });
        }
    });

    // Also collect from feature cards and other elements
    document.querySelectorAll('.feature-card').forEach((card, index) => {
        const title = card.querySelector('h4');
        const content = card.querySelector('p');
        
        if (title) {
            searchData.push({
                id: card.closest('section')?.id || `feature-${index}`,
                title: title.textContent.trim(),
                content: content ? content.textContent.trim() : ''
            });
        }
    });

    let debounceTimer;

    searchInput.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            const query = this.value.trim().toLowerCase();
            
            if (query.length < 2) {
                searchResults.classList.remove('active');
                return;
            }

            const results = searchData.filter(item => 
                item.title.toLowerCase().includes(query) ||
                item.content.toLowerCase().includes(query)
            ).slice(0, 8);

            if (results.length > 0) {
                searchResults.innerHTML = results.map(item => `
                    <div class="search-result-item" data-target="${item.id}">
                        <div class="search-result-title">${highlightMatch(item.title, query)}</div>
                        <div class="search-result-excerpt">${highlightMatch(truncate(item.content, 100), query)}</div>
                    </div>
                `).join('');
                searchResults.classList.add('active');
            } else {
                searchResults.innerHTML = '<div class="search-no-results">No results found</div>';
                searchResults.classList.add('active');
            }
        }, 200);
    });

    // Click on search result
    searchResults.addEventListener('click', function(e) {
        const item = e.target.closest('.search-result-item');
        if (item) {
            const targetId = item.dataset.target;
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
                searchResults.classList.remove('active');
                searchInput.value = '';
            }
        }
    });

    // Close search results on outside click
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.header-search')) {
            searchResults.classList.remove('active');
        }
    });

    // Keyboard navigation
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            searchResults.classList.remove('active');
            this.blur();
        }
    });
}

function highlightMatch(text, query) {
    if (!query) return text;
    const regex = new RegExp(`(${escapeRegex(query)})`, 'gi');
    return text.replace(regex, '<mark>$1</mark>');
}

function escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function truncate(text, length) {
    if (text.length <= length) return text;
    return text.substring(0, length) + '...';
}

/* ============================================
   TABS
   ============================================ */

function initTabs() {
    const tabContainers = document.querySelectorAll('.tabs');

    tabContainers.forEach(container => {
        const buttons = container.querySelectorAll('.tab-btn');
        const contents = container.querySelectorAll('.tab-content');

        buttons.forEach(btn => {
            btn.addEventListener('click', function() {
                const target = this.dataset.tab;

                // Remove active from all
                buttons.forEach(b => b.classList.remove('active'));
                contents.forEach(c => c.classList.remove('active'));

                // Add active to clicked
                this.classList.add('active');
                const targetContent = container.querySelector(`[data-tab-content="${target}"]`);
                if (targetContent) {
                    targetContent.classList.add('active');
                }
            });
        });
    });
}

/* ============================================
   ACCORDION
   ============================================ */

function initAccordion() {
    const accordions = document.querySelectorAll('.accordion');

    accordions.forEach(accordion => {
        const items = accordion.querySelectorAll('.accordion-item');

        items.forEach(item => {
            const header = item.querySelector('.accordion-header');

            header.addEventListener('click', function() {
                const isActive = item.classList.contains('active');

                // Close all items in this accordion
                items.forEach(i => i.classList.remove('active'));

                // Open clicked if it wasn't active
                if (!isActive) {
                    item.classList.add('active');
                }
            });
        });
    });
}

/* ============================================
   BACK TO TOP
   ============================================ */

function initBackToTop() {
    const btn = document.querySelector('.back-to-top');
    if (!btn) return;

    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            btn.classList.add('visible');
        } else {
            btn.classList.remove('visible');
        }
    });

    btn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

/* ============================================
   SMOOTH SCROLL
   ============================================ */

function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                e.preventDefault();
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });

                // Update URL without jumping
                history.pushState(null, null, targetId);
            }
        });
    });
}

/* ============================================
   ACTIVE NAVIGATION
   ============================================ */

function initActiveNavigation() {
    const sections = document.querySelectorAll('section[id]');
    const navLinks = document.querySelectorAll('.sidebar-subnav-link, .sidebar-nav-link');

    if (sections.length === 0) return;

    const observerOptions = {
        root: null,
        rootMargin: '-20% 0px -70% 0px',
        threshold: 0
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const id = entry.target.id;
                
                // Remove active from all links
                navLinks.forEach(link => link.classList.remove('active'));

                // Add active to matching link
                const activeLink = document.querySelector(`.sidebar-subnav-link[href="#${id}"], .sidebar-nav-link[href="#${id}"]`);
                if (activeLink) {
                    activeLink.classList.add('active');

                    // Expand parent if needed
                    const parentItem = activeLink.closest('.sidebar-nav-item');
                    if (parentItem) {
                        parentItem.classList.add('expanded');
                    }
                }
            }
        });
    }, observerOptions);

    sections.forEach(section => {
        observer.observe(section);
    });
}

/* ============================================
   CODE COPY
   ============================================ */

function initCodeCopy() {
    document.querySelectorAll('.code-copy').forEach(btn => {
        btn.addEventListener('click', async function() {
            const codeBlock = this.closest('.code-block').querySelector('code');
            if (!codeBlock) return;

            try {
                await navigator.clipboard.writeText(codeBlock.textContent);
                
                const originalText = this.textContent;
                this.textContent = 'Copied!';
                this.style.color = 'var(--success)';

                setTimeout(() => {
                    this.textContent = originalText;
                    this.style.color = '';
                }, 2000);
            } catch (err) {
                console.error('Failed to copy:', err);
            }
        });
    });
}

/* ============================================
   UTILITY: Scroll Progress
   ============================================ */

function initScrollProgress() {
    const progressBar = document.querySelector('.scroll-progress');
    if (!progressBar) return;

    window.addEventListener('scroll', function() {
        const scrollTop = window.scrollY;
        const docHeight = document.documentElement.scrollHeight - window.innerHeight;
        const progress = (scrollTop / docHeight) * 100;
        progressBar.style.width = progress + '%';
    });
}

/* ============================================
   UTILITY: Print
   ============================================ */

function printDocumentation() {
    window.print();
}
