Natural goal-directed behaviors often involve complex sequences of many stimulus-triggered components. Understanding how brain circuits organize such behaviors requires mapping the interactions between an animal, its environment, and its nervous system. Here, we use brain-wide neuronal imaging to study the full performance of mating by the C. elegans male. We show that as mating unfolds in a sequence of component behaviors, the brain operates similarly between instances of each component but distinctly between different components. When the full sensory and behavioral context is taken into account, unique roles emerge for each neuron. Functional correlations between neurons are not fixed but change with behavioral dynamics. From individual neurons to circuits, our study shows how diverse brain-wide dynamics emerge from the integration of sensory perception and motor actions in their natural context.