// Custom cursor with magnetic hover
const Cursor = () => {
  const cursorRef = React.useRef(null);
  const dotRef = React.useRef(null);
  const [hovering, setHovering] = React.useState(false);

  React.useEffect(() => {
    let rafId;
    let targetX = 0, targetY = 0;
    let curX = 0, curY = 0;

    const onMove = (e) => {
      targetX = e.clientX;
      targetY = e.clientY;
      if (dotRef.current) {
        dotRef.current.style.transform = `translate(${targetX}px, ${targetY}px) translate(-50%, -50%)`;
      }
    };

    const animate = () => {
      curX += (targetX - curX) * 0.18;
      curY += (targetY - curY) * 0.18;
      if (cursorRef.current) {
        cursorRef.current.style.transform = `translate(${curX}px, ${curY}px) translate(-50%, -50%)`;
      }
      rafId = requestAnimationFrame(animate);
    };

    const checkHover = (e) => {
      const el = e.target;
      const interactive = el.closest("a, button, .post-card, .stack-category, .stat-card, .timeline-item, [data-cursor='hover']");
      setHovering(!!interactive);
    };

    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseover", checkHover);
    rafId = requestAnimationFrame(animate);

    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseover", checkHover);
      cancelAnimationFrame(rafId);
    };
  }, []);

  return (
    <React.Fragment>
      <div ref={cursorRef} className={`custom-cursor ${hovering ? "hover" : ""}`}></div>
      <div ref={dotRef} className="custom-cursor-dot"></div>
    </React.Fragment>
  );
};

window.Cursor = Cursor;
