// useAuth hook — Manage auth state with automatic token refresh
function useAuth() {
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(true);
  const [isRefreshing, setIsRefreshing] = React.useState(false);
  const [error, setError] = React.useState(null);
  const refreshIntervalRef = React.useRef(null);

  React.useEffect(() => {
    initializeAuth();
    return () => {
      if (refreshIntervalRef.current) {
        clearInterval(refreshIntervalRef.current);
      }
    };
  }, []);

  const initializeAuth = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const auth = window.AuthStorage.getAuth();
      console.log('[Auth] Initializing, auth exists:', !!auth);

      if (!auth) {
        console.log('[Auth] No auth found');
        setIsAuthenticated(false);
        setIsLoading(false);
        return;
      }

      // Always try to refresh token on initialization to ensure it's valid
      console.log('[Auth] Attempting initial token refresh...');
      try {
        await ensureTokenValid();
        setIsAuthenticated(true);
        startPeriodicRefresh();
        console.log('[Auth] Initial token refresh successful');
      } catch (err) {
        console.error('[Auth] Initial token refresh failed:', err);
        setIsAuthenticated(false);
        setError('Session expired. Please log in again.');
      }
    } catch (err) {
      console.error('[Auth] Initialization error:', err);
      setIsAuthenticated(false);
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const ensureTokenValid = async () => {
    const isExpired = window.AuthStorage.isTokenExpired();
    console.log('[Auth] Checking token validity. Expired:', isExpired);

    if (isExpired) {
      console.log('[Auth] Token expired, refreshing...');
      return await window.AuthService.refreshToken();
    }

    console.log('[Auth] Token still valid');
    return window.AuthStorage.getAuth();
  };

  const startPeriodicRefresh = () => {
    // Refresh token every 5 minutes (300000ms)
    // This ensures token stays valid even if user keeps page open
    if (refreshIntervalRef.current) {
      clearInterval(refreshIntervalRef.current);
    }

    refreshIntervalRef.current = setInterval(async () => {
      console.log('[Auth] Periodic refresh check...');
      try {
        const isExpiringSoon = window.AuthStorage.isTokenExpiringSoon();
        if (isExpiringSoon) {
          console.log('[Auth] Token expiring soon, performing periodic refresh...');
          setIsRefreshing(true);
          await window.AuthService.refreshToken();
          console.log('[Auth] Periodic refresh successful');
        }
      } catch (err) {
        console.error('[Auth] Periodic refresh failed:', err);
        // Don't immediately logout, let user try to continue
        // It will fail on next API call if refresh really doesn't work
      } finally {
        setIsRefreshing(false);
      }
    }, 5 * 60 * 1000); // 5 minutes
  };

  const logout = async () => {
    try {
      if (refreshIntervalRef.current) {
        clearInterval(refreshIntervalRef.current);
      }
      await window.AuthService.logout();
      setIsAuthenticated(false);
    } catch (err) {
      console.error('Logout error:', err);
    }
  };

  const login = (accessToken, refreshToken, expiresAt) => {
    window.AuthStorage.setAuth(accessToken, refreshToken, expiresAt);
    setIsAuthenticated(true);
    startPeriodicRefresh();
  };

  return {
    isAuthenticated,
    isLoading,
    isRefreshing,
    error,
    logout,
    login,
    initializeAuth,
    ensureTokenValid
  };
}
