const { useEffect, useRef, useMemo } = React;

function Background() {
  const gridRef = useRef(null);

  useEffect(() => {
    let raf = 0;
    let tx = 0,
      ty = 0,
      cx = 0,
      cy = 0;
    const onMove = (e) => {
      const x = (e.clientX / window.innerWidth - 0.5) * 2;
      const y = (e.clientY / window.innerHeight - 0.5) * 2;
      tx = x * -12;
      ty = y * -12;
    };
    const loop = () => {
      cx += (tx - cx) * 0.08;
      cy += (ty - cy) * 0.08;
      if (gridRef.current) {
        gridRef.current.style.transform = `translate3d(${cx}px, ${cy}px, 0)`;
      }
      raf = requestAnimationFrame(loop);
    };
    window.addEventListener("mousemove", onMove, { passive: true });
    loop();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("mousemove", onMove);
    };
  }, []);

  const particles = useMemo(() => {
    return Array.from({ length: 14 }).map((_, i) => ({
      left: Math.random() * 100,
      delay: Math.random() * -18,
      duration: 16 + Math.random() * 14,
      size: 2 + Math.random() * 3,
      opacity: 0.25 + Math.random() * 0.4,
    }));
  }, []);

  return (
    <div className="bg-stage" aria-hidden="true">
      <div className="bg-radial"></div>
      <div className="bg-grid" ref={gridRef}></div>
      {particles.map((p, i) => (
        <span
          key={i}
          className="bg-particle"
          style={{
            left: `${p.left}%`,
            bottom: `-10vh`,
            width: p.size,
            height: p.size,
            opacity: p.opacity,
            animationDelay: `${p.delay}s`,
            animationDuration: `${p.duration}s`,
          }}
        ></span>
      ))}
      <div className="bg-noise"></div>
      <div className="bg-vignette"></div>
    </div>
  );
}

window.Background = Background;
