/* Custom cursor with dot + ring + ambient glow.
   Also updates --mx/--my on documentElement for background parallax. */
function CursorFX() {
  const dotRef = React.useRef(null);
  const ringRef = React.useRef(null);
  const glowRef = React.useRef(null);
  // Skip entirely on low-perf devices — body gets native cursor via .native-cursor class
  // (set by the perf-tier IIFE in app.jsx).
  const lowPerf = (typeof document !== 'undefined') && document.body.dataset.perf === 'low';
  // We deliberately avoid React state for hover-link detection — every mousemove
  // triggered a re-render at ~60Hz and stole frames from the rAF loop.
  // Toggling a CSS class directly on the ring element is orders of magnitude cheaper.

  React.useEffect(() => {
    if (lowPerf) return undefined;
    let mx = window.innerWidth / 2, my = window.innerHeight / 2;
    let rx = mx, ry = my;
    let gx = mx, gy = my;
    let raf;
    let lastLinky = false;
    const LINK_SELECTOR = 'a, button, .chip, .case, .svc, .li, .b-chip, .sw, .price-card, .team-card, .blog-card, input, textarea, select';

    const onMove = (e) => {
      mx = e.clientX; my = e.clientY;
      // The dot tracks the real cursor 1:1 with no easing — set transform inline,
      // no CSS transition (we removed it in styles.css to kill ghost trails).
      if (dotRef.current) {
        dotRef.current.style.transform = `translate3d(${mx}px, ${my}px, 0) translate(-50%, -50%)`;
      }
      document.documentElement.style.setProperty('--mx', mx + 'px');
      document.documentElement.style.setProperty('--my', my + 'px');

      const t = e.target;
      const linky = !!(t && t.closest && t.closest(LINK_SELECTOR));
      if (linky !== lastLinky) {
        lastLinky = linky;
        if (ringRef.current) ringRef.current.classList.toggle('is-link', linky);
      }
    };

    const loop = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      gx += (mx - gx) * 0.06;
      gy += (my - gy) * 0.06;
      if (ringRef.current) ringRef.current.style.transform = `translate3d(${rx}px, ${ry}px, 0) translate(-50%, -50%)`;
      if (glowRef.current) glowRef.current.style.transform = `translate3d(${gx}px, ${gy}px, 0) translate(-50%, -50%)`;
      raf = requestAnimationFrame(loop);
    };
    loop();

    // passive: we never call preventDefault, lets the browser schedule
    // the handler off the main rendering path.
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, []);

  if (lowPerf) return null;
  return (
    <React.Fragment>
      <div ref={glowRef} className="cursor-glow" />
      <div ref={ringRef} className="cursor-ring" />
      <div ref={dotRef} className="cursor-dot" />
    </React.Fragment>
  );
}

window.CursorFX = CursorFX;
