'use client';
import { useEffect, useRef } from 'react';

const CursorDot = () => {
  const dotRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Skip entirely on touch / coarse-pointer devices (no cursor to follow)
    if (typeof window === 'undefined') return;
    if (window.matchMedia('(pointer: coarse)').matches) return;

    const dot = dotRef.current;
    if (!dot) return;

    let mouseX = 0, mouseY = 0;
    let dotX = 0, dotY = 0;
    let rafId = 0;
    let running = false;

    const loop = () => {
      // lerp = linear interpolation (0.15 = smoothness)
      dotX += (mouseX - dotX) * 0.15;
      dotY += (mouseY - dotY) * 0.15;
      dot.style.transform = `translate3d(${dotX - 6}px, ${dotY - 6}px, 0)`;

      // Stop the loop once the dot has essentially caught up (saves CPU when idle)
      if (Math.abs(mouseX - dotX) < 0.1 && Math.abs(mouseY - dotY) < 0.1) {
        running = false;
        return;
      }
      rafId = requestAnimationFrame(loop);
    };

    const moveHandler = (e: MouseEvent) => {
      mouseX = e.clientX;
      mouseY = e.clientY;
      dot.style.opacity = '1';
      if (!running) {
        running = true;
        rafId = requestAnimationFrame(loop);
      }
    };

    window.addEventListener('mousemove', moveHandler, { passive: true });
    return () => {
      window.removeEventListener('mousemove', moveHandler);
      cancelAnimationFrame(rafId);
    };
  }, []);

  return (
    <div
      ref={dotRef}
      className="fixed top-0 left-0 w-3 h-3 bg-[#E77025] rounded-full pointer-events-none z-[9999]"
      style={{ opacity: 0, willChange: 'transform' }}
    />
  );
};

export default CursorDot;
