// Cursor-following image preview — fires on preview:show / preview:hide events
(function () {
  const { useState, useEffect, useRef } = React;

  function CursorPreview() {
    const [active, setActive] = useState(false);
    const [imgSrc, setImgSrc] = useState('');
    const [label, setLabel] = useState('');
    const elRef = useRef(null);
    const rafRef = useRef(null);
    const target = useRef({ x: -999, y: -999 });
    const current = useRef({ x: -999, y: -999 });

    useEffect(() => {
      const onMove = (e) => {
        target.current = { x: e.clientX, y: e.clientY };
      };
      window.addEventListener('mousemove', onMove, { passive: true });

      const lerp = (a, b, t) => a + (b - a) * t;
      const tick = () => {
        current.current.x = lerp(current.current.x, target.current.x, 0.1);
        current.current.y = lerp(current.current.y, target.current.y, 0.1);
        if (elRef.current) {
          elRef.current.style.transform =
            `translate3d(${current.current.x}px,${current.current.y}px,0) translate(20px,-55%)`;
        }
        rafRef.current = requestAnimationFrame(tick);
      };
      rafRef.current = requestAnimationFrame(tick);

      const onShow = (e) => {
        setImgSrc(e.detail.src || '');
        setLabel(e.detail.label || '');
        setActive(true);
      };
      const onHide = () => setActive(false);
      window.addEventListener('preview:show', onShow);
      window.addEventListener('preview:hide', onHide);

      return () => {
        window.removeEventListener('mousemove', onMove);
        window.removeEventListener('preview:show', onShow);
        window.removeEventListener('preview:hide', onHide);
        cancelAnimationFrame(rafRef.current);
      };
    }, []);

    return (
      <div
        ref={elRef}
        className={`cursor-preview${active ? ' is-active' : ''}`}
        aria-hidden="true"
      >
        <div className="cursor-preview__frame">
          {imgSrc
            ? <img src={imgSrc} alt="" className="cursor-preview__img" />
            : <div className="cursor-preview__placeholder" />
          }
          {label && <div className="cursor-preview__label">{label}</div>}
        </div>
      </div>
    );
  }

  window.CursorPreview = CursorPreview;
})();
