Custom roles and capabilities media not work right

This happens because on every page load you call remove_role

As the docs note:

When a role is removed, the users who have this role lose all rights on the site.

Roles are not like post types, they exist in the database, and removing/adding a role updates the database. For that reason you shouldn’t add them on every page load, it’s better to do it on theme activation or plugin activation