Cortical regulation of collective social dynamics during environmental challenge