The most important thing here is a workaround for an OS bug: rapidly hiding and showing the dock icon can result in multiple icons for the same app, and those icons will ignore NSApp.applicationIconImage. Making sure transitions happen no less than 0.5 seconds apart from one another seems to fix it.
Also, hiding a dock icon will deactivate an app. That's not desirable if it still has visible windows, so attempt to force a reactivation. That's often not successful on Sonoma due to the cooperative app activation heuristics, but it's the best we can do, and it should be a rare case.
Also, there is some logic in -transformProcessToForeground: that we often want to happen regardless of whether the app is getting a dock icon (e.g. App Nap and activation). So I've renamed that function to more accurately communicate what it does, and consolidate it with -tryToActivateIgnoringOtherApps:.