import type { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { i18n } from '/@/lang/index'

/**
 * 后台菜单/标签标题：优先按路由 name（对应 admin_rule.name）匹配 menu.names.*
 */
export function menuI18nKeyFromName(name: string | symbol | null | undefined): string {
    if (name == null || name === '') {
        return ''
    }
    const n = String(name).trim()
    if (!n) {
        return ''
    }
    return `menu.names.${n.replace(/\//g, '_')}`
}

export function menuTitleFromName(name: string | symbol | null | undefined, fallback?: string): string {
    const key = menuI18nKeyFromName(name)
    if (key && i18n.global.te(key)) {
        return String(i18n.global.t(key))
    }
    if (fallback && i18n.global.te(fallback)) {
        return String(i18n.global.t(fallback))
    }
    return fallback || ''
}

export function menuTitleFromRoute(route: RouteRecordRaw | RouteLocationNormalized): string {
    const name = route.name
    const metaTitle = route.meta && typeof route.meta.title === 'string' ? route.meta.title : ''
    return menuTitleFromName(name, metaTitle) || metaTitle || String(i18n.global.t('noTitle'))
}
