// ============================================
// Custom gold cursor (desktop only)
// ============================================

function Cursor() {
  const dotRef = React.useRef(null);
  const ringRef = React.useRef(null);
  const stateRef = React.useRef({ x: 0, y: 0, rx: 0, ry: 0, active: false });

  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const mq = window.matchMedia('(hover: hover) and (pointer: fine)');
    if (!mq.matches) return;

    const state = stateRef.current;

    const move = (e) => {
      state.x = e.clientX;
      state.y = e.clientY;
      if (!state.active) {
        state.active = true;
        state.rx = state.x;
        state.ry = state.y;
      }
      if (dotRef.current) {
        dotRef.current.style.transform = `translate(${state.x}px, ${state.y}px) translate(-50%, -50%)`;
      }
    };

    const tick = () => {
      state.rx += (state.x - state.rx) * 0.18;
      state.ry += (state.y - state.ry) * 0.18;
      if (ringRef.current) {
        ringRef.current.style.transform = `translate(${state.rx}px, ${state.ry}px) translate(-50%, -50%)`;
      }
      raf = requestAnimationFrame(tick);
    };
    let raf = requestAnimationFrame(tick);

    const hoverSel = 'a, button, input, textarea, select, [data-cursor="hover"]';
    const over = (e) => {
      if (e.target.closest && e.target.closest(hoverSel)) {
        dotRef.current && dotRef.current.classList.add('is-hover');
        ringRef.current && ringRef.current.classList.add('is-hover');
      }
    };
    const out = (e) => {
      if (e.target.closest && e.target.closest(hoverSel)) {
        dotRef.current && dotRef.current.classList.remove('is-hover');
        ringRef.current && ringRef.current.classList.remove('is-hover');
      }
    };

    window.addEventListener('mousemove', move, { passive: true });
    document.addEventListener('mouseover', over);
    document.addEventListener('mouseout', out);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', move);
      document.removeEventListener('mouseover', over);
      document.removeEventListener('mouseout', out);
    };
  }, []);

  return (
    <>
      <div ref={dotRef} className="cursor" aria-hidden="true"></div>
      <div ref={ringRef} className="cursor-ring" aria-hidden="true"></div>
    </>
  );
}

window.Cursor = Cursor;
