export const KEYFRAME_TRACK_NAMES = Object.freeze([
  'scenes',
  'shaders',
  'images',
  'postfx',
  'luts',
  'texts',
  'audios',
]);

export function upsertKeyframe(keyframes, time, value, easing = 'linear', epsilon = 0.001) {
  const updated = keyframes.filter(keyframe => Math.abs(keyframe.time - time) >= epsilon);
  updated.push({ time, value, easing });
  updated.sort((left, right) => left.time - right.time);
  return updated;
}

export function interpolateKeyframes(keyframes, time, curveType = 'linear') {
  if (!Array.isArray(keyframes) || keyframes.length === 0) return null;
  if (keyframes.length === 1) return keyframes[0].value;

  let before = keyframes[0];
  let after = keyframes[keyframes.length - 1];
  for (let index = 0; index < keyframes.length - 1; index += 1) {
    if (time >= keyframes[index].time && time <= keyframes[index + 1].time) {
      before = keyframes[index];
      after = keyframes[index + 1];
      break;
    }
  }
  if (time <= before.time) return before.value;
  if (time >= after.time) return after.value;

  const progress = (time - before.time) / (after.time - before.time);
  if (curveType === 'step') return before.value;
  if (curveType === 'bezier') {
    const eased = progress < 0.5
      ? 4 * progress * progress * progress
      : 1 - Math.pow(-2 * progress + 2, 3) / 2;
    return before.value + (after.value - before.value) * eased;
  }
  return before.value + (after.value - before.value) * progress;
}
