This idiom originated from Chan (Zen) Buddhism, where
头头 meant 'in every situation' and
道 referred to Buddhist enlightenment. The original meaning was 'the Way is present in everything.' Over centuries it shifted to its modern meaning of speaking coherently.