Improve expand/collapse logic