/**
 * PageSpark WP Theme — Main JS
 * Minimal. Let Bootstrap handle the heavy lifting.
 */
(function() {
    'use strict';

    // Close offcanvas when clicking a nav link (smooth UX)
    const offcanvasEl = document.getElementById('wpbs-offcanvas');
    if (offcanvasEl) {
        const offcanvas = bootstrap.Offcanvas.getOrCreateInstance(offcanvasEl);
        offcanvasEl.querySelectorAll('.nav-link:not(.dropdown-toggle)').forEach(link => {
            link.addEventListener('click', () => {
                offcanvas.hide();
            });
        });
    }

    // Navbar style change on scroll (for transparent navbar)
    const navbar = document.querySelector('.wpbs-navbar.bg-transparent');
    if (navbar) {
        const scrollThreshold = 100;
        
        function updateNavbar() {
            if (window.scrollY > scrollThreshold) {
                navbar.classList.remove('bg-transparent');
                navbar.classList.add('bg-white', 'shadow-sm');
                navbar.style.backgroundColor = 'var(--wpbs-navbar-bg)';
            } else {
                navbar.classList.add('bg-transparent');
                navbar.classList.remove('bg-white', 'shadow-sm');
                navbar.style.backgroundColor = 'transparent';
            }
        }

        window.addEventListener('scroll', updateNavbar, { passive: true });
        updateNavbar();
    }

    // Smooth scroll for anchor links (skip bare "#" and dropdown toggles)
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (!href || href === '#' || this.classList.contains('dropdown-toggle')) return;
            try {
                const target = document.querySelector(href);
                if (target) {
                    e.preventDefault();
                    const offset = document.querySelector('.wpbs-navbar.sticky-top')?.offsetHeight || 0;
                    const top = target.getBoundingClientRect().top + window.pageYOffset - offset;
                    window.scrollTo({ top, behavior: 'smooth' });
                }
            } catch (err) {}
        });
    });

})();
