// Cursor-following flies. Subtle swarm; orbits the cursor when over .swarm targets,
// drifts off-screen when not.

// Parent gates this component on touch / reduced-motion, but as belt-and-suspenders
// CSS also hides .fly elements on coarse-pointer devices.
function FlySwarm({ count = 5 }) {
  const flies = React.useRef([]);
  const targetRef = React.useRef({ x: -200, y: -200, active: false });
  const driftRef = React.useRef({ vx: 0, vy: 0 });

  if (flies.current.length === 0) {
    for (let i = 0; i < count; i++) {
      flies.current.push({
        x: -200, y: -200,
        vx: 0, vy: 0,
        phase: Math.random() * Math.PI * 2,
        speed: 1.5 + Math.random() * 1.2,
        radius: 24 + Math.random() * 26,
        ref: React.createRef(),
      });
    }
  }

  React.useEffect(() => {
    const onMove = (e) => {
      const t = e.target;
      const swarmable = t && t.closest && t.closest(".swarm");
      targetRef.current.active = !!swarmable;
      targetRef.current.x = e.clientX;
      targetRef.current.y = e.clientY;
    };
    const onLeave = () => {
      targetRef.current.active = false;
      driftRef.current = {
        vx: (Math.random() - 0.5) * 4,
        vy: -2 - Math.random() * 2,
      };
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseout", (e) => {
      if (!e.relatedTarget && !e.toElement) onLeave();
    });
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  React.useEffect(() => {
    let raf;
    let t = 0;
    const step = () => {
      t += 0.06;
      const tgt = targetRef.current;
      flies.current.forEach((f) => {
        if (tgt.active) {
          const ox = Math.cos(t * f.speed + f.phase) * f.radius;
          const oy = Math.sin(t * f.speed * 1.3 + f.phase) * (f.radius * 0.7);
          const tx = tgt.x + ox;
          const ty = tgt.y + oy;
          f.vx += (tx - f.x) * 0.16;
          f.vy += (ty - f.y) * 0.16;
          f.vx *= 0.55;
          f.vy *= 0.55;
        } else {
          f.vx += driftRef.current.vx * 0.02 + (Math.random() - 0.5) * 0.4;
          f.vy += driftRef.current.vy * 0.02 + (Math.random() - 0.5) * 0.4;
          f.vx *= 0.99;
          f.vy *= 0.99;
        }
        f.x += f.vx;
        f.y += f.vy;
        if (f.ref.current) {
          f.ref.current.style.transform = `translate(${f.x}px, ${f.y}px) rotate(${f.vx * 4}deg)`;
        }
      });
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <React.Fragment>
      {flies.current.map((f, i) => (
        <div key={i} ref={f.ref} className="fly" style={{ left: 0, top: 0 }} aria-hidden>
          <svg viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg">
            <ellipse cx="7" cy="7" rx="2.6" ry="1.6" fill="#1A1A1A" />
            <g className="wing">
              <ellipse cx="5.5" cy="5.5" rx="2.4" ry="1.4" fill="rgba(26,26,26,0.55)" />
              <ellipse cx="8.5" cy="5.5" rx="2.4" ry="1.4" fill="rgba(26,26,26,0.55)" />
            </g>
            <circle cx="9.6" cy="7" r="1.1" fill="#1A1A1A" />
          </svg>
        </div>
      ))}
    </React.Fragment>
  );
}

window.FlySwarm = FlySwarm;
