'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
import { buildLoginRedirectUrl, getCurrentRelativePath } from '@/lib/auth-redirect';

/**
 * 自定义 Hook：用于保护需要认证的页面
 * 等待 Zustand 水合完成后再检查认证状态，避免刷新时误跳转到登录页
 */
interface AuthGuardOptions {
  enabled?: boolean;
  redirectTo?: string; // 自定义时请传完整路径，如 /login?redirect=%2Fxxx
}

export function useAuthGuard(options: AuthGuardOptions = {}) {
  const router = useRouter();
  const { user, isAuthenticated, token } = useAuth();
  const [isHydrated, setIsHydrated] = useState(false);
  const [isReady, setIsReady] = useState(false);
  const { enabled = true, redirectTo = '/login' } = options;

  // 等待 Zustand 水合完成
  useEffect(() => {
    setIsHydrated(true);
  }, []);

  useEffect(() => {
    if (!enabled) {
      setIsReady(true);
      return;
    }

    if (!isHydrated) {
      // 还在水合中，不进行任何判断
      console.log('Auth guard: Waiting for hydration...');
      return;
    }

    console.log('Auth guard: Hydrated, checking auth status', {
      isAuthenticated,
      hasToken: !!token,
      hasUser: !!user,
    });

    if (!isAuthenticated || !token) {
      console.log('Auth guard: Not authenticated, redirecting to login');
      const loginUrl = redirectTo === '/login'
        ? buildLoginRedirectUrl(getCurrentRelativePath())
        : redirectTo;
      router.replace(loginUrl);
      return;
    }

    console.log('Auth guard: Authenticated, page ready');
    setIsReady(true);
  }, [enabled, isHydrated, isAuthenticated, token, user, router, redirectTo]);

  return {
    isReady,        // 页面是否准备好（已认证且水合完成）
    isAuthenticated, // 是否已认证
    user,           // 用户信息
    token,          // Token
  };
}
