/* global React */
const { useState, useEffect, useRef } = React;

const TextCursor = ({
  text = 'WEE',
  spacing = 220,
  followMouseDirection = true,
  randomFloat = true,
  exitDuration = 0.5,
  removalInterval = 30,
  maxPoints = 6
}) => {
  const [trail, setTrail] = useState([]);
  const containerRef = useRef(null);
  const lastMoveTimeRef = useRef(Date.now());
  const idCounter = useRef(0);

  const createRandomData = () =>
    randomFloat
      ? {
          randomRotate: Math.random() * 6 - 3
        }
      : { randomRotate: 0 };

  const handleMouseMove = e => {
    const mouseX = e.clientX;
    const mouseY = e.clientY;

    setTrail(prev => {
      const newTrail = [...prev];
      if (newTrail.length === 0) {
        newTrail.push({ id: idCounter.current++, x: mouseX, y: mouseY, angle: 0, ...createRandomData(), removing: false });
      } else {
        const last = newTrail[newTrail.length - 1];
        const dx = mouseX - last.x;
        const dy = mouseY - last.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance >= spacing) {
          const rawAngle = (Math.atan2(dy, dx) * 180) / Math.PI;
          const computedAngle = followMouseDirection ? rawAngle : 0;
          newTrail.push({ id: idCounter.current++, x: mouseX, y: mouseY, angle: computedAngle, ...createRandomData(), removing: false });
        }
      }
      return newTrail.length > maxPoints ? newTrail.slice(newTrail.length - maxPoints) : newTrail;
    });

    lastMoveTimeRef.current = Date.now();
  };

  useEffect(() => {
    window.addEventListener('mousemove', handleMouseMove);
    return () => window.removeEventListener('mousemove', handleMouseMove);
  }, []);

  useEffect(() => {
    const interval = setInterval(() => {
      if (Date.now() - lastMoveTimeRef.current > 100) {
        setTrail(prev => {
          if (prev.length === 0) return prev;
          // mark the first item removing so CSS transition can play
          const first = prev[0];
          if (first && !first.removing) {
            const updated = prev.map((p, idx) => (idx === 0 ? { ...p, removing: true } : p));
            // after exitDuration remove it
            setTimeout(() => {
              setTrail(current => current.filter(item => item.id !== first.id));
            }, exitDuration * 1000);
            return updated;
          }
          return prev;
        });
      }
    }, removalInterval);
    return () => clearInterval(interval);
  }, [removalInterval, exitDuration]);

  return (
    <div ref={containerRef} className="text-cursor-container" style={{ width: '100%', height: '100%' }}>
      <div className="text-cursor-inner">
        {trail.map((item, index) => {
          const opacity = 1 - (trail.length - 1 - index) * 0.18;
          return (
            <div
              key={item.id}
              className={`text-cursor-item ${item.removing ? 'removing' : ''}`}
              style={{
                left: item.x + 'px',
                top: item.y + 'px',
                opacity,
                transform: `translate(-50%,-50%) rotate(${item.angle + (item.randomRotate || 0)}deg)`
              }}
            >
              {text}
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.TextCursor = TextCursor;
