document.addEventListener('DOMContentLoaded',()=>{
  // Hero slider
  const slider = document.querySelector('.hero.hero-slider');
  const slides = Array.from(document.querySelectorAll('.hero.hero-slider .slide'));
  const dotsContainer = document.querySelector('.hero.hero-slider .dots');
  const prevBtn = document.querySelector('.hero.hero-slider .arrow.prev');
  const nextBtn = document.querySelector('.hero.hero-slider .arrow.next');
  let index = 0; let timer = null; const DURATION = 3000;

  if (slider && slides.length) {
    // init dots
    slides.forEach((_, i) => {
      const b = document.createElement('button');
      b.setAttribute('aria-label', `切换到第${i+1}张`);
      if (i === 0) b.classList.add('active');
      b.addEventListener('click', ()=> go(i));
      dotsContainer.appendChild(b);
    });

    function show(i){
      slides.forEach((s, idx)=> s.classList.toggle('active', idx === i));
      dotsContainer.querySelectorAll('button').forEach((d, idx)=> d.classList.toggle('active', idx === i));
    }
    function next(){ index = (index + 1) % slides.length; show(index); }
    function prev(){ index = (index - 1 + slides.length) % slides.length; show(index); }
    function go(i){ index = i % slides.length; show(index); restart(); }

    function start(){ timer = setInterval(next, DURATION); }
    function stop(){ if (timer) clearInterval(timer); timer = null; }
    function restart(){ stop(); start(); }

    nextBtn.addEventListener('click', ()=>{ next(); restart(); });
    prevBtn.addEventListener('click', ()=>{ prev(); restart(); });

    slider.addEventListener('mouseenter', stop);
    slider.addEventListener('mouseleave', start);

    // touch swipe (basic)
    let startX = 0; let dx = 0;
    slider.addEventListener('touchstart', e=>{ startX = e.touches[0].clientX; dx = 0; stop(); }, {passive:true});
    slider.addEventListener('touchmove', e=>{ dx = e.touches[0].clientX - startX; }, {passive:true});
    slider.addEventListener('touchend', ()=>{ if (Math.abs(dx) > 40) { dx < 0 ? next() : prev(); } start(); });

    start();
  }
});