/* global React, gsap, ScrollTrigger */

// Counter that animates 0 → target when in viewport
window.useCounter = function useCounter(target, options = {}) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el || !window.gsap) return;
    const obj = { v: 0 };
    let started = false;
    const start = () => {
      if (started) return;
      started = true;
      gsap.to(obj, {
        v: target,
        duration: options.duration || 2.2,
        ease: options.ease || 'power2.out',
        onUpdate: () => {
          const prefix = options.prefix || '';
          const suffix = options.suffix || '';
          el.textContent = prefix + Math.round(obj.v).toLocaleString('es-ES') + suffix;
        },
      });
    };
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) start(); });
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [target]);
  return ref;
};
