import { useCallback, useMemo } from 'react';

import { useTranslation } from 'react-i18next';
import { matchPath, useLocation } from 'react-router-dom';

import { getNavMenuItems, type NavMenuItem } from '@/utils/navUtils';

/**
 * Topbar 业务逻辑 Hook
 * 处理菜单项获取、路由匹配、翻译等业务逻辑
 */
export function useService() {
    const { t } = useTranslation();
    const location = useLocation();

    const menuItems = useMemo(() => getNavMenuItems(), []);

    const isActive = useCallback(
        (path: string): boolean => {
            return matchPath({ path, end: false }, location.pathname) !== null;
        },
        [location.pathname]
    );

    const getMenuItemLabel = useCallback(
        (item: NavMenuItem): string => {
            // getNavMenuItems 中已经设置了 locale，item.locale 总是存在
            return t(item.locale!, { defaultValue: item.name });
        },
        [t]
    );

    return {
        menuItems,
        isActive,
        getMenuItemLabel,
    };
}
