
const viewModules = import.meta.glob('../views/**/*.vue')

function resolveView(component) {
  if (!component) return undefined
  const key = `../views/${component}.vue`
  const loader = viewModules[key]
  if (!loader) return undefined
  return loader
}

export function buildAdminRoutesFromMenus(menus) {
  const routes = []

  const normalizeAdminChildPath = (rawPath) => {
    if (!rawPath) return ''
    if (rawPath.startsWith('/admin/')) return rawPath.slice('/admin/'.length)
    if (rawPath === '/admin') return ''
    return rawPath.startsWith('/') ? rawPath.slice(1) : rawPath
  }

  const walk = (nodes) => {
    for (const n of nodes) {
      if (n.type === 'M') {
        const component = resolveView(n.component)
        if (!component) continue
        const childPath = normalizeAdminChildPath(n.path || '')
        if (!childPath) continue
        routes.push({
          path: childPath,
          component,
          meta: { title: n.name, icon: n.icon },
        })
      }
      if (n.children?.length) walk(n.children)
    }
  }

  walk(menus)
  return routes
}
