(function(){
  const shell = document.getElementById('moovlp-shell') || document.documentElement;
  const panels = Array.from(document.querySelectorAll('.panel[data-panel-title], .hero.panel'));
  const nav = document.querySelector('.panel-nav');
  const nextButtons = document.querySelectorAll('.scroll-next');
  let activeIndex = 0;

  const revealObserver = new IntersectionObserver((entries)=>{
    entries.forEach(entry=>{
      if(entry.isIntersecting){ entry.target.classList.add('is-visible'); }
    });
  }, { root: shell === document.documentElement ? null : shell, threshold: 0.22 });
  document.querySelectorAll('[data-animate]').forEach(el=>revealObserver.observe(el));

  function scrollToPanel(index){
    const target = panels[index];
    if(!target) return;
    target.scrollIntoView({behavior:'smooth', block:'start'});
  }

  function renderNav(){
    if(!nav) return;
    nav.innerHTML='';
    panels.forEach((panel, index)=>{
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.setAttribute('aria-label', panel.getAttribute('data-panel-title') || ('Section ' + (index + 1)));
      btn.addEventListener('click', ()=> scrollToPanel(index));
      nav.appendChild(btn);
    });
  }

  function syncActive(index){
    activeIndex = index;
    panels.forEach((panel, i)=> panel.classList.toggle('is-active', i === index));
    if(nav){
      Array.from(nav.children).forEach((dot, i)=> dot.classList.toggle('is-active', i === index));
    }
  }

  const activeObserver = new IntersectionObserver((entries)=>{
    const visible = entries.filter(e=>e.isIntersecting).sort((a,b)=> b.intersectionRatio - a.intersectionRatio)[0];
    if(!visible) return;
    const index = panels.indexOf(visible.target);
    if(index >= 0) syncActive(index);
  }, { root: shell === document.documentElement ? null : shell, threshold: [0.35,0.55,0.75] });
  panels.forEach(panel => activeObserver.observe(panel));

  nextButtons.forEach(btn=> btn.addEventListener('click', ()=> scrollToPanel(Math.min(activeIndex + 1, panels.length - 1))));

  document.addEventListener('keydown', (event)=>{
    const tag = (event.target && event.target.tagName) ? event.target.tagName.toLowerCase() : '';
    if(tag === 'input' || tag === 'textarea' || tag === 'select' || event.metaKey || event.ctrlKey || event.altKey) return;
    if(event.code === 'Space'){
      event.preventDefault();
      scrollToPanel(Math.min(activeIndex + 1, panels.length - 1));
    } else if(event.code === 'ArrowUp'){
      event.preventDefault();
      scrollToPanel(Math.max(activeIndex - 1, 0));
    } else if(event.code === 'ArrowDown'){
      event.preventDefault();
      scrollToPanel(Math.min(activeIndex + 1, panels.length - 1));
    }
  }, {passive:false});

  renderNav();
  syncActive(0);
})();