class ScrollTracker {
  constructor() {
    this.navAnchors = document.querySelectorAll('.nav-links a');
    this.sectionEls = document.querySelectorAll('section[id]');
    this.leftDots = document.querySelectorAll('.side-panel.left .side-dot');
    this.rightDots = document.querySelectorAll('.side-panel.right .side-dot');
    this.leftTrack = document.getElementById('leftTrack');
    this.rightTrack = document.getElementById('rightTrack');
    this.scrollPctEl = document.getElementById('scrollPct');
    if (!this.sectionEls.length && !this.leftTrack) return;
    window.addEventListener('scroll', () => this.update(), { passive: true });
    this.update();
  }

  update() {
    const y = scrollY + innerHeight * 0.4;
    const maxScroll = document.documentElement.scrollHeight - innerHeight;
    const pct = Math.min(scrollY / maxScroll, 1);
    let id = '', activeIndex = 0;
    this.sectionEls.forEach((s, i) => {
      if (y >= s.offsetTop) { id = s.id; activeIndex = i; }
    });
    this.navAnchors.forEach(a => a.classList.toggle('active', a.getAttribute('href') === '#' + id));
    const trackPct = (pct * 100).toFixed(0);
    if (this.leftTrack) this.leftTrack.style.height = trackPct + '%';
    if (this.rightTrack) this.rightTrack.style.height = trackPct + '%';
    if (this.scrollPctEl) this.scrollPctEl.textContent = String(trackPct).padStart(2, '0');
    const leftIdx = Math.min(activeIndex, this.leftDots.length - 1);
    const rightIdx = Math.min(activeIndex, this.rightDots.length - 1);
    this.leftDots.forEach((d, i) => d.classList.toggle('active', i === leftIdx));
    this.rightDots.forEach((d, i) => d.classList.toggle('active', i === rightIdx));
  }
}
