Explain something to me in Italian

I’m on a hunt to find out how and when “lei” came to mean both she and formal you in Italian. Do any of you know?

hi how are you doing

Grazie. È molto interessante.