import * as THREE from 'three';

export interface FlyConfig {
  duration?: number; // 飞出去和飞回来的总时间，单位 ms
  radius?: number; // 飞出去的最大半径
}

/**
 * 让卡片在正面时无序飞出去并环绕一圈后飞回原位
 * @param cards 卡片 Mesh 数组
 * @param scene three.js 场景
 * @param onStart 回调，开始飞行时触发
 * @param onEnd 回调，飞行结束时触发
 * @param config 配置项
 */
export function flyChaos(
  cards: THREE.Mesh[],
  scene: THREE.Scene,
  onStart?: () => void,
  onEnd?: () => void,
  config: FlyConfig = {}
) {
  const duration = config.duration ?? 2000;
  const radius = config.radius ?? 20;
  const originalPositions = cards.map(card => card.position.clone());
  const randomTargets = cards.map(card => {
    // 随机一个圆环上的点
    const theta = Math.random() * Math.PI * 2;
    const phi = Math.random() * Math.PI;
    const r = radius * (0.7 + Math.random() * 0.3);
    return new THREE.Vector3(
      r * Math.sin(phi) * Math.cos(theta),
      r * Math.sin(phi) * Math.sin(theta),
      r * Math.cos(phi)
    );
  });

  let startTime = performance.now();
  let phase = 0; // 0: 飞出去, 1: 飞回来
  let flying = true;

  if (onStart) onStart();

  function animateFly() {
    const now = performance.now();
    const t = Math.min((now - startTime) / duration, 1);
    for (let i = 0; i < cards.length; i++) {
      if (phase === 0) {
        // 飞出去
        cards[i].position.lerpVectors(originalPositions[i], randomTargets[i], t);
      } else {
        // 飞回来
        cards[i].position.lerpVectors(randomTargets[i], originalPositions[i], t);
      }
    }
    if (t < 1) {
      requestAnimationFrame(animateFly);
    } else {
      if (phase === 0) {
        // 飞出去结束，等待2s再飞回来
        phase = 1;
        startTime = performance.now();
        setTimeout(() => {
          requestAnimationFrame(animateFly);
        }, 2000);
      } else {
        // 飞回来结束
        flying = false;
        if (onEnd) onEnd();
      }
    }
  }

  requestAnimationFrame(animateFly);

  return () => flying; // 返回一个状态查询函数
}
