// Swarm — many butterflies with independent flight paths, parallax depth.
const Swarm = ({ count = 22, species, onPick, paused = false }) => {
  // Pre-generate flight params per butterfly, deterministic from index.
  const flyers = React.useMemo(() => {
    const isMobile = window.innerWidth < 800;
    const sizeScale = isMobile ? 0.6 : 1;
    const opacityScale = isMobile ? 0.6 : 1;
    const flyerCount = isMobile ? Math.ceil(count / 2) : count;
    const arr = [];
    for (let i = 0; i < flyerCount; i++) {
      const sp = species[i % species.length];
      const depth = Math.random(); // 0 = far, 1 = near
      const baseSize = (60 + depth * 110) * sizeScale;
      arr.push({
        id: `f-${i}-${sp.id}`,
        species: sp,
        size: baseSize,
        depth,
        opacity: (0.55 + depth * 0.45) * opacityScale,
        blur: (1 - depth) * 1.4, // farther = blurrier
        flap: 220 + Math.random() * 220, // 220..440ms
        // a curved, looping flight path:
        path: makePath(),
        duration: 18 + Math.random() * 26, // seconds
        delay: -Math.random() * 30,
        spin: (Math.random() - 0.5) * 30,
      });
    }
    return arr;
  }, [count, species]);

  return (
    <div className="swarm" style={{ position: "absolute", inset: 0, perspective: 1200, overflow: "hidden", pointerEvents: "none" }}>
      {flyers.map((f) => (
        <div
          key={f.id}
          className="flyer"
          style={{
            position: "absolute",
            left: 0,
            top: 0,
            width: f.size * 2,
            height: f.size,
            opacity: f.opacity,
            filter: `blur(${f.blur}px) drop-shadow(0 6px 12px rgba(40,30,10,${0.15 + f.depth * 0.2}))`,
            offsetPath: `path('${f.path}')`,
            offsetRotate: "auto",
            animation: `flyPath ${f.duration}s linear ${f.delay}s infinite`,
            pointerEvents: "auto",
            willChange: "offset-distance, transform",
          }}
        >
          {/* offset-rotate:auto aligns element's +X with path direction.
              The butterfly's head is at -Y (top), so rotate -90deg to point
              the head along the travel direction. */}
          {/* offset-rotate:auto aligns element's +X with path direction.
              Body is laid out along Y with head at -Y (top), so rotate +90deg
              puts head at the LEADING edge of motion (head-first flight). */}
          <div style={{ transform: `translate(-50%, -50%) rotate(${90 + f.spin}deg)` }}>
            <window.Butterfly3D
              species={f.species}
              size={f.size}
              flap={f.flap}
              tilt={20 + f.depth * 30}
              pose="fly"
              paused={paused}
              onClick={() => onPick && onPick(f.species)}
            />
          </div>
        </div>
      ))}
    </div>
  );
};

function makePath() {
  // Random sweeping curve across the viewport (uses CSS pixels via vw/vh-ish numbers).
  // We use a 100x100 path scaled to viewport via offset-path expressed in px? Actually
  // offset-path 'path()' uses the element's own coordinate system in user units (px).
  // We'll size based on viewport via JS for correctness.
  const W = window.innerWidth + 200;
  const H = window.innerHeight + 200;
  const startX = -150 + Math.random() * 100;
  const endX = W - 50 + Math.random() * 100;
  const y0 = Math.random() * H;
  const y1 = Math.random() * H;
  const cx1 = W * (0.25 + Math.random() * 0.2);
  const cy1 = Math.random() * H;
  const cx2 = W * (0.55 + Math.random() * 0.2);
  const cy2 = Math.random() * H;
  // direction 50/50 left-to-right or right-to-left
  if (Math.random() < 0.5) {
    return `M ${endX},${y1} C ${cx2},${cy2} ${cx1},${cy1} ${startX},${y0}`;
  }
  return `M ${startX},${y0} C ${cx1},${cy1} ${cx2},${cy2} ${endX},${y1}`;
}

window.Swarm = Swarm;
