There's a dap expanding *caulk* (not expanding foam) that works well in situations like this - expanding foam makes a horrific mess, and can expand forcefully enough to tweak your windows so they won't ever open again. The caulk product can still be messy, but it cleans up with water & isn't nearly as messy.
https://www.walmart.com/ip/21153802?...&wl13=&veh=sem
As for the trim, quite often it's attached with self-tapping screws or "pop rivets".. A silicone caulk would probably work, but it's really messy & hard to work with (and not paintable, so you have to get it off anything you hope to paint). The "paintable" acrylic/silicone caulks most likely won't be strong enough to hold the trim.
Best bet would be to find at least a couple places for a real fastener (screw or rivet) & then use acrylic/ silicone (paintable) caulk.
Maybe get the one that's apart now fixed & then evaluate if you want to take on the rest of the windows yourself, or "punt"...