/* main.js - Global JS for Karunya Sagar Dasa Website */
document.addEventListener('DOMContentLoaded',function(){
  // Navbar scroll
  const navbar=document.querySelector('.navbar');
  if(navbar){
    window.addEventListener('scroll',()=>{
      navbar.classList.toggle('scrolled',window.scrollY>60);
    });
  }
  // Hamburger
  const hamburger=document.querySelector('.hamburger');
  const navMenu=document.querySelector('.nav-menu');
  if(hamburger&&navMenu){
    hamburger.addEventListener('click',()=>{
      hamburger.classList.toggle('active');
      navMenu.classList.toggle('active');
    });
    navMenu.querySelectorAll('a').forEach(link=>{
      link.addEventListener('click',()=>{
        hamburger.classList.remove('active');
        navMenu.classList.remove('active');
      });
    });
  }
  // Scroll animations
  const observerOpts={threshold:0.15,rootMargin:'0px 0px -50px 0px'};
  const observer=new IntersectionObserver((entries)=>{
    entries.forEach(e=>{if(e.isIntersecting){e.target.classList.add('visible');observer.unobserve(e.target);}});
  },observerOpts);
  document.querySelectorAll('.fade-up,.fade-left,.fade-right').forEach(el=>observer.observe(el));
  // Animated counters
  const counters=document.querySelectorAll('[data-count]');
  const counterObs=new IntersectionObserver((entries)=>{
    entries.forEach(e=>{
      if(e.isIntersecting){
        const target=parseInt(e.target.getAttribute('data-count'));
        let current=0;const increment=Math.ceil(target/60);
        const timer=setInterval(()=>{
          current+=increment;
          if(current>=target){current=target;clearInterval(timer);}
          e.target.textContent=current.toLocaleString()+'+';
        },30);
        counterObs.unobserve(e.target);
      }
    });
  },{threshold:0.5});
  counters.forEach(c=>counterObs.observe(c));
  // Quote rotator
  const quotes=document.querySelectorAll('.quote-slide');
  if(quotes.length>1){
    let qi=0;
    quotes[0].style.display='block';
    setInterval(()=>{
      quotes[qi].style.opacity='0';
      setTimeout(()=>{
        quotes[qi].style.display='none';
        qi=(qi+1)%quotes.length;
        quotes[qi].style.display='block';
        setTimeout(()=>{quotes[qi].style.opacity='1';},50);
      },500);
    },6000);
  }
  // Back to top
  const btt=document.querySelector('.back-to-top');
  if(btt){
    window.addEventListener('scroll',()=>{btt.classList.toggle('show',window.scrollY>400);});
    btt.addEventListener('click',()=>{window.scrollTo({top:0,behavior:'smooth'});});
  }
  // Gallery lightbox
  const lightbox=document.querySelector('.lightbox');
  const lbImg=lightbox?lightbox.querySelector('img'):null;
  const lbClose=lightbox?lightbox.querySelector('.lightbox-close'):null;
  document.querySelectorAll('.gallery-item').forEach(item=>{
    item.addEventListener('click',()=>{
      if(lightbox&&lbImg){
        lbImg.src=item.querySelector('img').src;
        lightbox.classList.add('active');
        document.body.style.overflow='hidden';
      }
    });
  });
  if(lbClose){lbClose.addEventListener('click',()=>{lightbox.classList.remove('active');document.body.style.overflow='';});}
  if(lightbox){lightbox.addEventListener('click',(e)=>{if(e.target===lightbox){lightbox.classList.remove('active');document.body.style.overflow='';}});}
  // Accordion
  document.querySelectorAll('.accordion-header').forEach(header=>{
    header.addEventListener('click',()=>{
      const item=header.parentElement;
      const isActive=item.classList.contains('active');
      item.closest('.accordion-list').querySelectorAll('.accordion-item').forEach(i=>i.classList.remove('active'));
      if(!isActive)item.classList.add('active');
    });
  });
  // Contact form validation
  const form=document.querySelector('.contact-form form');
  if(form){
    form.addEventListener('submit',(e)=>{
      e.preventDefault();
      let valid=true;
      form.querySelectorAll('[required]').forEach(f=>{
        if(!f.value.trim()){f.style.borderColor='#ff6b6b';valid=false;}
        else{f.style.borderColor='#e0d9c8';}
      });
      const email=form.querySelector('[type="email"]');
      if(email&&email.value&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)){
        email.style.borderColor='#ff6b6b';valid=false;
      }
      if(valid){
        alert('Thank you for your message! We will get back to you soon. Hare Krishna!');
        form.reset();
      }
    });
  }
  // Scroll spy
  const sections=document.querySelectorAll('section[id]');
  const navLinks=document.querySelectorAll('.nav-menu a');
  if(sections.length&&navLinks.length){
    window.addEventListener('scroll',()=>{
      let current='';
      sections.forEach(s=>{
        const top=s.offsetTop-200;
        if(window.scrollY>=top)current=s.getAttribute('id');
      });
      navLinks.forEach(l=>{
        l.classList.remove('active');
        if(l.getAttribute('href')&&l.getAttribute('href').includes(current))l.classList.add('active');
      });
    });
  }
  // Parallax
  window.addEventListener('scroll',()=>{
    document.querySelectorAll('.parallax-bg').forEach(el=>{
      const speed=parseFloat(el.dataset.speed)||0.5;
      el.style.transform=`translateY(${window.scrollY*speed}px)`;
    });
  });
});

// Gate page logic
function checkAccessCode(){
  const input=document.getElementById('accessCode');
  const error=document.getElementById('gateError');
  if(!input)return;
  const code=input.value.trim();
  if(code.toLowerCase()==='digantsharma'){
    sessionStorage.setItem('sd_access','1');
    document.querySelector('.gate-content').style.opacity='0';
    document.querySelector('.gate-content').style.transform='scale(0.9)';
    setTimeout(()=>{window.location.href='home.html';},600);
  }else{
    error.classList.add('show');
    error.textContent='⚠ Invalid access code. Please try again with devotion.';
    input.style.borderColor='#ff6b6b';
    setTimeout(()=>{error.classList.remove('show');input.style.borderColor='rgba(230,168,23,.4)';},3000);
  }
}
