import React, { useEffect, useRef } from "react";
import { createPortal } from "react-dom";

const MouseTracker = ({ children, offset = { x: 0, y: 0 } }) => {
  const element = useRef(null);

  useEffect(() => {
    const handler = (ev) => {
      if (element.current) {
        const e = ev.touches ? ev.touches[0] : ev;
        const x = e.clientX + offset.x;
        const y = e.clientY + offset.y;
        element.current.style.transform = `translate(${x}px, ${y}px)`;
        element.current.style.visibility = "visible";
      }
    };

    document.addEventListener("mousemove", handler);
    document.addEventListener("touchmove", handler);

    return () => {
      document.removeEventListener("mousemove", handler);
      document.removeEventListener("touchmove", handler);
    };
  }, [offset]);

  return createPortal(
    <div
      ref={element}
      className="absolute pointer-events-none z-1000"
      style={{ visibility: "hidden", position: "fixed" }}
    >
      {children}
    </div>,
    document.body
  );
};

export default MouseTracker;
