import { useCallback, useEffect, useRef, useState } from 'react';

export function Ellipse() {
  const ref = useRef<HTMLDivElement>(null);
  const requestRef = useRef<number>();
  const x = useRef(0);
  const y = useRef(0);
  const [mousePos, setMousePos] = useState([0, 0]);

  const handleMouseMove = useCallback((e: MouseEvent) => {
    x.current = e.clientX;
    y.current = e.clientY;
  }, []);

  const animate = useCallback(() => {
    if (ref.current) {
      setMousePos(([prevX, prevY]) => [
        prevX + (x.current - prevX) / 10,
        prevY + (y.current - prevY) / 10,
      ]);
    }
    requestRef.current = requestAnimationFrame(animate);
  }, []);

  useEffect(() => {
    document.body?.addEventListener('mousemove', handleMouseMove);
    animate();

    return () => {
      cancelAnimationFrame(requestRef.current!);
      document.body?.removeEventListener('mousemove', handleMouseMove);
    };
  }, [animate, handleMouseMove]);

  return (
    <div
      ref={ref}
      style={{ top: mousePos[1], left: mousePos[0] }}
      className="fixed -z-[9] bg-[url('/Ellipse.png')] bg-transparent bg-cover bg-no-repeat bg-center -translate-y-[50%] -translate-x-[50%] aspect-[348.75/262.77] w-[21.75vw]"
    />
  );
}
