I suspect it is the internal power supply. I had this issue with two first generation iMac G5's. I did not have any sparks while plugging it in but I did have them unempextanctly shut off.

I bought a replacement power supply from Apple, since it was way out of warranty.

I suggest you either buy a new or refurbished power supply or buy a like model and cannibalize it for parts. Cannibalizing one for parts may be a gamble since its power supply may fail too at some point, since it seems a fairly common issue.

Since I replaced my power supply I have had not further issues with it.

MacRumors attracts a broad audience
of both consumers and professionals interested in
the latest technologies and products. We also boast an active community focused on
purchasing decisions and technical aspects of the iPhone, iPod, iPad, and Mac platforms.