/**
 * DC 入场特效 - 粒子星场模块
 * 纵深粒子向观察者飞来（Nova.app starfield 风格）
 * 绿青色调呼应品牌色
 */

const PARTICLE_COUNT = 600;
const SPEED_MIN = 0.4;
const SPEED_MAX = 2.0;
const SPREAD = 80;       // 粒子 xy 散布范围
const DEPTH = 120;       // z 轴纵深范围（0=观察者, DEPTH=最远）

/**
 * 创建粒子星场
 * @param {THREE.Scene} scene
 * @returns {{ mesh: THREE.Points, update: function(number): void, slowDown: function, speedUp: function }}
 */
export function createStarfield(scene) {
  // 动态导入 Three.js（由 dc-intro.js 保证已加载）
  const THREE = window.THREE;

  const positions = new Float32Array(PARTICLE_COUNT * 3);
  const colors = new Float32Array(PARTICLE_COUNT * 3);
  const speeds = new Float32Array(PARTICLE_COUNT);

  // 金色为主 + 翠青点缀
  const colorPalette = [
    new THREE.Color('#fbbf24'),  // 金
    new THREE.Color('#f59e0b'),  // 琥珀
    new THREE.Color('#fcd34d'),  // 浅金
    new THREE.Color('#fbbf24'),  // 金（双倍权重）
    new THREE.Color('#4ade80'),  // 翠绿点缀
    new THREE.Color('#22d3ee'),  // 青点缀
    new THREE.Color('#fef3c7'),  // 亮金白
  ];

  for (let i = 0; i < PARTICLE_COUNT; i++) {
    const i3 = i * 3;

    // 随机分布在 xy 平面和 z 深度
    positions[i3]     = (Math.random() - 0.5) * SPREAD;   // x
    positions[i3 + 1] = (Math.random() - 0.5) * SPREAD;   // y
    positions[i3 + 2] = Math.random() * DEPTH;             // z (远处)

    // 随机选取调色板颜色
    const color = colorPalette[Math.floor(Math.random() * colorPalette.length)];
    colors[i3]     = color.r;
    colors[i3 + 1] = color.g;
    colors[i3 + 2] = color.b;

    // 随机速度
    speeds[i] = SPEED_MIN + Math.random() * (SPEED_MAX - SPEED_MIN);
  }

  const geometry = new THREE.BufferGeometry();
  geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
  geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));

  const material = new THREE.PointsMaterial({
    size: 0.55,
    vertexColors: true,
    transparent: true,
    opacity: 0.9,
    sizeAttenuation: true,
    blending: THREE.AdditiveBlending,
    depthWrite: false,
  });

  const mesh = new THREE.Points(geometry, material);
  scene.add(mesh);

  // 速度倍率（用于减速/加速控制）
  let speedMultiplier = 1.0;

  /**
   * 每帧更新粒子位置
   * @param {number} delta - 帧间隔（秒）
   */
  function update(delta) {
    const posArr = geometry.attributes.position.array;

    for (let i = 0; i < PARTICLE_COUNT; i++) {
      const i3 = i * 3;

      // 粒子向观察者移动（z 减小）
      posArr[i3 + 2] -= speeds[i] * speedMultiplier * delta * 30;

      // 粒子飞过观察者后重置到远处
      if (posArr[i3 + 2] < -5) {
        posArr[i3]     = (Math.random() - 0.5) * SPREAD;
        posArr[i3 + 1] = (Math.random() - 0.5) * SPREAD;
        posArr[i3 + 2] = DEPTH;
      }
    }

    geometry.attributes.position.needsUpdate = true;
  }

  function slowDown() {
    speedMultiplier = 0.15;
  }

  function speedUp() {
    speedMultiplier = 1.0;
  }

  return { mesh, update, slowDown, speedUp };
}
