/* =========================
   Run AFTER LCP (window load)
========================= */
window.addEventListener('load', () => {

  /* =========================
     Fade Section Observer
  ========================= */
  const fadeObserver = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('show');
        fadeObserver.unobserve(entry.target);
      }
    });
  }, { threshold: 0.2 });

  document.querySelectorAll('.fade-section').forEach(el => {
    fadeObserver.observe(el);
  });


  /* =========================
     Counter Animation
  ========================= */
  const counters = document.querySelectorAll('.counter');

  const animateCounter = (el) => {
    const target  = parseInt(el.dataset.target, 10);
    const suffix  = el.dataset.suffix || '';
    const useDot  = el.dataset.format === 'dot';

    let current = 0;
    const duration = 2000; // lebih cepat = lebih ringan
    const step = Math.ceil(target / (duration / 16));

    const format = (n) =>
      useDot ? n.toLocaleString('id-ID') : n;

    const update = () => {
      current += step;
      if (current >= target) {
        el.textContent = format(target) + suffix;
      } else {
        el.textContent = format(current) + suffix;
        requestAnimationFrame(update);
      }
    };

    update();
  };

  const counterObserver = new IntersectionObserver((entries, obs) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        animateCounter(entry.target);
        obs.unobserve(entry.target);
      }
    });
  }, { threshold: 0.6 });

  counters.forEach(el => counterObserver.observe(el));


  /* =========================
     Smooth Anchor Scroll
  ========================= */
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', e => {
      e.preventDefault();
      const target = document.querySelector(anchor.getAttribute('href'));
      if (target) {
        window.scrollTo({
          top: target.offsetTop - 80,
          behavior: 'smooth'
        });
      }
    });
  });

});

function openResellerModal() {

    const modal = document.getElementById('resellerModal');

    modal.classList.remove('hidden');
    modal.classList.add('flex');

}

function closeResellerModal() {

    const modal = document.getElementById('resellerModal');

    modal.classList.add('hidden');
    modal.classList.remove('flex');

}

document.getElementById('resellerModal').addEventListener('click', function(e){

    if(e.target === this){

        closeResellerModal();

    }

});