(function () {
  const { useEffect, useRef } = React;

  function Cursor() {
    const blobRef = useRef(null);
    const rafRef  = useRef(null);
    const mouse   = useRef({ x: -400, y: -400 });
    const pos     = useRef({ x: -400, y: -400 });
    const size    = useRef(18); // lerped display size

    useEffect(() => {
      if (window.matchMedia('(pointer: coarse)').matches) return;

      const onMove = (e) => {
        mouse.current.x = e.clientX;
        mouse.current.y = e.clientY;
      };

      const onOver = (e) => {
        const overImg = !!e.target.closest('img, .hero-frame, .hero-frame__img');
        blobRef.current?.classList.toggle('over-image', overImg);
      };

      window.addEventListener('mousemove', onMove, { passive: true });
      window.addEventListener('mouseover', onOver);

      const LERP      = 0.14;
      const SIZE_LERP = 0.10;
      const BASE      = 68;   // resting diameter px
      const MAX_ADD   = 120;  // extra px at peak velocity

      const tick = () => {
        const dx = mouse.current.x - pos.current.x;
        const dy = mouse.current.y - pos.current.y;
        pos.current.x += dx * LERP;
        pos.current.y += dy * LERP;

        // Velocity = distance the circle still needs to travel
        const dist = Math.sqrt(dx * dx + dy * dy);
        const targetSize = BASE + Math.min(dist * 1.1, MAX_ADD);
        size.current += (targetSize - size.current) * SIZE_LERP;

        const s = size.current;
        const el = blobRef.current;
        if (el) {
          el.style.width  = `${s}px`;
          el.style.height = `${s}px`;
          el.style.transform =
            `translate3d(${pos.current.x}px,${pos.current.y}px,0) translate(-50%,-50%)`;
        }

        rafRef.current = requestAnimationFrame(tick);
      };
      rafRef.current = requestAnimationFrame(tick);

      return () => {
        window.removeEventListener('mousemove', onMove);
        window.removeEventListener('mouseover', onOver);
        cancelAnimationFrame(rafRef.current);
      };
    }, []);

    return <div className="cursor-blob" ref={blobRef} aria-hidden="true" />;
  }

  window.Cursor = Cursor;
})();
