import { getFinalKeyframe } from "../animators/waapi/utils/get-final-keyframe.js";
import { getDefaultTransition } from "../utils/default-transitions.js";
import { isTransitionDefined } from "../utils/is-transition-defined.js";
import { getValueTransition } from "../../../../../motion-dom/dist/es/animation/utils/get-value-transition.js";
import { secondsToMilliseconds } from "../../../../../motion-utils/dist/es/time-conversion.js";
import { MotionGlobalConfig } from "../../../../../motion-utils/dist/es/global-config.js";
import { frame } from "../../../../../motion-dom/dist/es/frameloop/frame.js";
import { JSAnimation } from "../../../../../motion-dom/dist/es/animation/JSAnimation.js";
import { AsyncMotionValueAnimation } from "../../../../../motion-dom/dist/es/animation/AsyncMotionValueAnimation.js";
const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
  const valueTransition = getValueTransition(transition, name) || {};
  const delay = valueTransition.delay || transition.delay || 0;
  let { elapsed = 0 } = transition;
  elapsed = elapsed - secondsToMilliseconds(delay);
  const options = {
    keyframes: Array.isArray(target) ? target : [null, target],
    ease: "easeOut",
    velocity: value.getVelocity(),
    ...valueTransition,
    delay: -elapsed,
    onUpdate: (v) => {
      value.set(v);
      valueTransition.onUpdate && valueTransition.onUpdate(v);
    },
    onComplete: () => {
      onComplete();
      valueTransition.onComplete && valueTransition.onComplete();
    },
    name,
    motionValue: value,
    element: isHandoff ? void 0 : element
  };
  if (!isTransitionDefined(valueTransition)) {
    Object.assign(options, getDefaultTransition(name, options));
  }
  options.duration && (options.duration = secondsToMilliseconds(options.duration));
  options.repeatDelay && (options.repeatDelay = secondsToMilliseconds(options.repeatDelay));
  if (options.from !== void 0) {
    options.keyframes[0] = options.from;
  }
  let shouldSkip = false;
  if (options.type === false || options.duration === 0 && !options.repeatDelay) {
    options.duration = 0;
    if (options.delay === 0) {
      shouldSkip = true;
    }
  }
  if (MotionGlobalConfig.instantAnimations || MotionGlobalConfig.skipAnimations) {
    shouldSkip = true;
    options.duration = 0;
    options.delay = 0;
  }
  options.allowFlatten = !valueTransition.type && !valueTransition.ease;
  if (shouldSkip && !isHandoff && value.get() !== void 0) {
    const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
    if (finalKeyframe !== void 0) {
      frame.update(() => {
        options.onUpdate(finalKeyframe);
        options.onComplete();
      });
      return;
    }
  }
  return valueTransition.isSync ? new JSAnimation(options) : new AsyncMotionValueAnimation(options);
};
export {
  animateMotionValue
};
//# sourceMappingURL=motion-value.js.map
