function joinRoutePath(parentPath = '', routePath = '') {
  const joined = `${parentPath}/${routePath}`.replace(/\/+/g, '/')
  return joined.startsWith('/') ? joined : `/${joined}`
}

function routeNameFromPath(path) {
  return path
    .split('/')
    .filter(Boolean)
    .map(segment => segment.replace(/[^a-zA-Z0-9_$-]/g, '').replace(/(^|[-_$])([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase()))
    .join('') || 'Root'
}

/**
 * Vue Router names are global. Backend menu names are generated from the
 * relative leaf path, so common leaves such as index and gis collide across
 * subsystems. Give subsystem routes stable names derived from their absolute
 * route path before registering them.
 */
export function ensureUniqueSubsystemRouteNames(routes = [], parentPath = '') {
  routes.forEach(route => {
    const absolutePath = joinRoutePath(parentPath, route.path)
    if (absolutePath.startsWith('/subSystem/')) {
      route.name = routeNameFromPath(absolutePath)
    }
    if (Array.isArray(route.children) && route.children.length) {
      ensureUniqueSubsystemRouteNames(route.children, absolutePath)
    }
  })
  return routes
}
