To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:
You did provide substantial code, but better if its embedded in a minimal app that can be run without forum user writing boilerplate around it. The forum posts permit editing so feel free to use that feature.