import * as TWEEN from "@tweenjs/tween.js";

const THREE = window.THREE;
let currentTween = null;

function flyArc(viewer, cameraArr, duration = 3000) {
  // 🛑 停掉前一個動畫
  if (currentTween) {
    TWEEN.remove(currentTween);
  }

  const startPos = viewer.navigation.getPosition().clone();
  const startTarget = viewer.navigation.getTarget().clone();

  const endPos = new THREE.Vector3(cameraArr[0], cameraArr[1], cameraArr[2]);

  const endTarget = new THREE.Vector3(cameraArr[3], cameraArr[4], cameraArr[5]);

  const distance = startPos.distanceTo(endPos);

  // 🎯 建立「控制點」（讓路徑變弧形）
  const mid = startPos.clone().lerp(endPos, 0.5);
  mid.z += distance * 1.5; // 弧度高度

  // 👉 建立 Bezier 曲線
  const curve = new THREE.QuadraticBezierCurve3(startPos, mid, endPos);

  const obj = { t: 0 };

  const tween = new TWEEN.Tween(obj)
    .to({ t: 1 }, duration)
    .easing(TWEEN.Easing.Cubic.InOut)
    .onUpdate(() => {
      const t = obj.t;

      // 🎯 沿曲線取點
      const pos = curve.getPoint(t);

      // 👉 target 用線性插值（穩定）
      const target = startTarget.clone().lerp(endTarget, t);

      viewer.navigation.setView(pos, target);
    })
    .onComplete(() => {
      currentTween = null;
    })
    .start();

  currentTween = tween;

  // 🧠 確保 Tween 有在跑
  function animate(time) {
    if (currentTween) {
      requestAnimationFrame(animate);
      currentTween.update(time);
    }
  }

  animate();
}

export default function changeCameraView(forgeViewer, Viewpoint) {
  flyArc(forgeViewer, Viewpoint.camera);
}
