/* ═══════════════════════════════════════════════
   navbar.js — Navbar Scroll & Mobile Behavior
   ═══════════════════════════════════════════════ */

'use strict';

(function initNavbar() {
  const nav = document.getElementById('mainNav');
  if (!nav) return;

  // Scroll class
  function onScroll() {
    nav.classList.toggle('scrolled', window.scrollY > 40);
  }
  window.addEventListener('scroll', onScroll, { passive: true });
  onScroll(); // run on load

  // Close mobile menu on link click
  const collapse = nav.querySelector('.navbar-collapse');
  const toggler  = nav.querySelector('.navbar-toggler');

  nav.querySelectorAll('.nav-link, .btn').forEach(link => {
    link.addEventListener('click', () => {
      if (collapse && collapse.classList.contains('show')) {
        // Trigger Bootstrap collapse close
        const bsCollapse = bootstrap.Collapse.getOrCreateInstance(collapse);
        bsCollapse.hide();
      }
    });
  });

  // Highlight active nav on scroll
  const sections = document.querySelectorAll('section[id]');
  const navLinks = nav.querySelectorAll('.nav-link[href^="#"]');

  const sectionObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const id = entry.target.id;
        navLinks.forEach(link => {
          link.classList.toggle('active', link.getAttribute('href') === `#${id}`);
        });
      }
    });
  }, { rootMargin: '-30% 0px -60% 0px' });

  sections.forEach(s => sectionObserver.observe(s));
})();
