Found the solution. Simply add
$args = array(
'parent' => '0',
);
at the top, and change
$cats = get_terms('category');
to
$cats = get_terms('category', $args);
There are more values, see https://codex.wordpress.org/Function_Reference/get_terms