import { useEffect, useMemo, useState } from 'react';

import { userConfigModel } from '@/models/userConfigModel';
import { isAuthenticated } from '@/utils/authUtils';

/**
 * 实时判断登录状态的 hook。
 *
 * 响应来源：
 * - userConfigModel 变更（登录/登出时立即响应）
 * - visibilitychange 事件（切回标签页时重新校验，捕获 token 自然过期）
 */
export function useAuth() {
    const { userConfig } = userConfigModel.useModel();
    const [tick, setTick] = useState(0);

    useEffect(() => {
        const onVisible = () => {
            if (document.visibilityState === 'visible') {
                setTick((t) => t + 1);
            }
        };
        document.addEventListener('visibilitychange', onVisible);
        return () => document.removeEventListener('visibilitychange', onVisible);
    }, []);

    // userConfig 变更驱动重新校验，tick 捕获 visibilitychange
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const isLoggedIn = useMemo(() => isAuthenticated(), [userConfig, tick]);

    return { isLoggedIn };
}
