export const DEFAULT_KEYFRAME_LANE_HEIGHT = 120;
export const MIN_KEYFRAME_LANE_HEIGHT = 80;
export const MAX_KEYFRAME_LANE_HEIGHT = 480;

export function normalizeKeyframeLaneHeight(
  value,
  {
    fallback = DEFAULT_KEYFRAME_LANE_HEIGHT,
    min = MIN_KEYFRAME_LANE_HEIGHT,
    max = MAX_KEYFRAME_LANE_HEIGHT,
  } = {},
) {
  const numeric = Number(value);
  const height = Number.isFinite(numeric) ? numeric : fallback;
  return Math.round(Math.max(min, Math.min(max, height)));
}

export function keyframeLaneHeightFromWheel(currentHeight, deltaY, options = {}) {
  const sensitivity = Number.isFinite(options.sensitivity)
    ? options.sensitivity
    : 0.5;
  return normalizeKeyframeLaneHeight(
    normalizeKeyframeLaneHeight(currentHeight, options) - Number(deltaY || 0) * sensitivity,
    options,
  );
}

export function isKeyframeLaneSelectionKey(key) {
  return key === 'Enter';
}

export function reorderKeyframeParams(params, draggedParam, targetParam, placement = 'before') {
  const ordered = [...(params || [])];
  if (
    !draggedParam
    || !targetParam
    || draggedParam === targetParam
    || !ordered.includes(draggedParam)
    || !ordered.includes(targetParam)
  ) {
    return new Set(ordered);
  }

  ordered.splice(ordered.indexOf(draggedParam), 1);
  let targetIndex = ordered.indexOf(targetParam);
  if (placement === 'after') targetIndex += 1;
  ordered.splice(targetIndex, 0, draggedParam);
  return new Set(ordered);
}
