document.addEventListener('DOMContentLoaded', () => {
  const aboutEditToggle = document.querySelector('.wcmv-about-edit-toggle');
  const aboutForm = document.querySelector('.wcmv-vendor-about-form');
  const aboutCancel = document.querySelector('.wcmv-about-cancel');
  if (aboutEditToggle && aboutForm) {
    aboutEditToggle.addEventListener('click', () => {
      aboutForm.classList.remove('wcmv-hidden');
      aboutEditToggle.style.display = 'none';
    });
    aboutCancel?.addEventListener('click', () => {
      aboutForm.classList.add('wcmv-hidden');
      aboutEditToggle.style.display = '';
    });
  }

  const shareBtn = document.querySelector('[data-wcmv-share]');
  if (shareBtn) {
    shareBtn.addEventListener('click', async () => {
      const payload = { title: document.title, url: window.location.href };
      if (navigator.share) {
        try {
          await navigator.share(payload);
          return;
        } catch (error) {
          // fall through to clipboard fallback
        }
      }
      if (navigator.clipboard && navigator.clipboard.writeText) {
        try {
          await navigator.clipboard.writeText(window.location.href);
          shareBtn.textContent = 'Link copied';
          window.setTimeout(() => { shareBtn.textContent = 'Share'; }, 1400);
          return;
        } catch (error) {
          // ignore and continue
        }
      }
      window.prompt('Copy this link', window.location.href);
    });
  }

  const slider = document.querySelector('.wcmv-vendor-banner-slider');
  if (!slider) return;

  const slides = Array.from(slider.querySelectorAll('.wcmv-vendor-banner-slide'));
  const prev = slider.querySelector('.wcmv-vendor-banner-nav.prev');
  const next = slider.querySelector('.wcmv-vendor-banner-nav.next');

  if (slides.length < 2) return;

  let index = 0;
  let timer = null;

  const render = () => {
    slides.forEach((slide, i) => slide.classList.toggle('is-active', i === index));
  };

  const go = (newIndex) => {
    index = (newIndex + slides.length) % slides.length;
    render();
  };

  const startAutoplay = () => {
    if (slider.dataset.autoplay !== '1') return;
    stopAutoplay();
    timer = window.setInterval(() => go(index + 1), 5000);
  };

  const stopAutoplay = () => {
    if (timer) {
      window.clearInterval(timer);
      timer = null;
    }
  };

  prev?.addEventListener('click', () => {
    go(index - 1);
    startAutoplay();
  });

  next?.addEventListener('click', () => {
    go(index + 1);
    startAutoplay();
  });

  slider.addEventListener('mouseenter', stopAutoplay);
  slider.addEventListener('mouseleave', startAutoplay);

  render();
  startAutoplay();
});
