export interface MenuItem {
  title: string
  icon?: string
  path?: string
  children?: MenuItem[]
  isOpen?: boolean
}

export function isMenuItemRouteActive(item: MenuItem, isActive: (path: string) => boolean): boolean {
  if (item.path && isActive(item.path)) return true
  if (item.children) {
    return item.children.some(child => isMenuItemRouteActive(child, isActive))
  }
  return false
}

export function openActiveMenuAncestors(items: MenuItem[], isActive: (path: string) => boolean) {
  items.forEach(item => {
    if (item.children && isMenuItemRouteActive(item, isActive)) {
      item.isOpen = true
      openActiveMenuAncestors(item.children, isActive)
    }
  })
}

export function findRouteTitle(items: MenuItem[], path: string, parentTitle?: string): string | null {
  for (const item of items) {
    if (item.path === path) {
      return parentTitle ? `${parentTitle} / ${item.title}` : item.title
    }
    if (item.children) {
      const childTitle = findRouteTitle(item.children, path, parentTitle ? `${parentTitle} / ${item.title}` : item.title)
      if (childTitle) return childTitle
    }
    if (item.path && path.startsWith(item.path + '/')) {
      return parentTitle ? `${parentTitle} / ${item.title}` : item.title
    }
    if (item.children) {
      for (const child of item.children) {
        if (child.path && path.startsWith(child.path + '/')) {
          const prefix = parentTitle ? `${parentTitle} / ${item.title}` : item.title
          return `${prefix} / ${child.title}`
        }
        if (child.children) {
          for (const grand of child.children) {
            if (grand.path && path.startsWith(grand.path + '/')) {
              const prefix = parentTitle ? `${parentTitle} / ${item.title}` : item.title
              return `${prefix} / ${child.title} / ${grand.title}`
            }
          }
        }
      }
    }
  }
  return null
}
