I get it sometimes. It's horrible. It takes about an hour of constant mild pain to finally go to sleep.
I take ibuprofen or I get up and walk around. I notice that it's less frequent if I have exercised during that day. Like running or doing leg exercises with weights.
The refined sugar is an interesting idea. I tend to eat ice cream before I go to bed.
Try stopping the ice cream and see what happens.
I cannot recall the exact circumstances of the instances when I experienced this, but my recollection at the time is refined carbs came to mind. I do know this for a fact, it is something in the food supply because it seemed very much to depend on what I had been eating.
Exercising would tend to burn excess carbs, as carbs are burned first. Ice cream is probably the last thing you should be eating before going to bed in my book depending on your lactose tolerance especially. I actually find fruit or peanut butter on a crusty rye cracker works well for me.
If you want some sugar I found that canned fruit even in syrup was no problem for me or sometimes I have a Popsicle or frozen fruit bar in the evening.
Half of a 3mg melatonin really helps sleep too.
I will also say that I am a type O blood - meat eater type.
If you are the same, maybe this will help you because I do not believe we all can eat the same things with the same result necessarily.
I think we all will benefit from never eating conventional white bread except as a last resort.