export function moveWithinZone<T>(items: T[], fromIndex: number, toIndex: number): T[] {
  if (fromIndex < 0 || fromIndex >= items.length || toIndex < 0 || toIndex > items.length) {
    return items;
  }

  const next = [...items];
  const [moved] = next.splice(fromIndex, 1);
  const insertionIndex = Math.min(toIndex, next.length);
  next.splice(insertionIndex, 0, moved);

  if (next.every((item, index) => item === items[index])) {
    return items;
  }

  return next;
}

export function moveBetweenZones<T>(
  sourceItems: T[],
  targetItems: T[],
  sourceIndex: number,
  targetIndex: number
): {
  sourceItems: T[];
  targetItems: T[];
} {
  if (
    sourceIndex < 0 ||
    sourceIndex >= sourceItems.length ||
    targetIndex < 0 ||
    targetIndex > targetItems.length
  ) {
    return { sourceItems, targetItems };
  }

  const nextSourceItems = [...sourceItems];
  const [moved] = nextSourceItems.splice(sourceIndex, 1);
  const nextTargetItems = [...targetItems];
  const insertionIndex = Math.min(targetIndex, nextTargetItems.length);
  nextTargetItems.splice(insertionIndex, 0, moved);

  return {
    sourceItems: nextSourceItems,
    targetItems: nextTargetItems,
  };
}
