Usually the problem with Sleep Mode not working properly is macOS running into a problem with an app not behaving properly in response to the sleep process.
The best way to narrow things down is to create a new fresh "test" user account, restart your iMac and log directly into that account instead of your normal <user name> account and to see if that works properly. If that works fine then it's a matter of what app or software loading automatically in the background of your normal <user name> account is the issue. If the problem still happens on a fresh "test" user account though, then that means it's something not-related to the software on your specific user account that would need further troubleshooting for something lower level.
If you've never had to create a new user account and don't know how, this page explains how easy it is:
https://support.apple.com/guide/mac-help/set-up-other-users-on-your-mac-mtusr001/mac
Also, when you create the new "test" user and restart your iMac to test it, don't bother to sign into your Apple ID as part of the new user account. You can skip that/indicate you don't have an Apple ID/and don't want to create one, just so you can log into that new user account and not have it sync with your Apple ID data.