You can try installing macOS to an external USB3 SSD & boot from the external SSD to see how the iMac works. If this works fine, then you know that something is either wrong with macOS on the internal drive or the internal drive itself is the problem.
You can try installing macOS to a new APFS volume on the internal drive assuming you have at least 80GB+ of Free storage space....ignore the "Available" storage value as it is very misleading. This option is not as good since it you are still using the same APFS file system and drive.
When installing macOS with either method, it is important NOT to restore from a backup, and do NOT install any third party apps, and do not sign into your AppleID or iCloud since you want a fresh OS for testing to confirm a hardware issue.
You can check the health of the internal drive(s) by running DriveDx (free trial period) and posting the complete text report here using the "Additional Text" icon which looks like a piece of paper on the forum editing toolbar.
You can also run the third party app EtreCheck and posting the complete report here so we can examine it for possible clues.
Try booting into Safe Mode to see how it works. If this works, then you most likely have an issue with third party software that is installed.
Try running Disk Utility First Aid on the hidden Container or Fusion Drive. Within Disk Utility you may need to click "View" and select "Show All Devices" before the hidden Container appears on the left pane of Disk Utility. Even if First Aid says everything is "Ok", click "Show Details" and scroll back through the log to see if any unfixed errors are listed. If there are errors listed, then run First Aid again until they are gone. If after several attempts the errors remain, then run First Aid while booted into Recovery Mode. If the errors still remain after several more attempts, then you will need to perform a clean install of macOS by first erasing the whole physical drive (or Fusion Drive item) followed by reinstalling macOS & restoring from a backup.
Try running the Apple Diagnostics to see if any hardware issues are detected.
Disconnect all external devices in case one of them is causing a problem.
You can try using the following command in the Terminal app to see if the system is actually triggering sleep mode or if it may be something else.
pmset -g log
To narrow the results down to a single day, you can use "grep" to filter output for a particular date such as "2024-06-16" (adjust accordingly):
pmset -g log | grep '2024-06-16'