{% comment %}Auth groups fragment for HTMX replacement{% endcomment %}
<div id="auth-groups-{{ user.pk }}" class="mt-1 d-flex flex-wrap gap-2 align-items-center">
    {% if user.groups.all %}
        {% for perm_group in user.groups.all %}
            {% if request.user.is_superuser or is_cid_user_manager %}
                <button
                    class="btn btn-sm btn-info text-dark"
                    hx-post="{% url 'generic:user_toggle_group' user.pk perm_group.pk %}?type=auth"
                    hx-target="#auth-groups-{{ user.pk }}"
                    hx-swap="outerHTML"
                >
                    {{ perm_group.name }}
                    <span class="ms-1 text-muted small">&times;</span>
                </button>
            {% else %}
                <span class="badge bg-info text-dark me-1">{{ perm_group.name }}</span>
            {% endif %}
        {% endfor %}
    {% else %}
        <span class="badge bg-light text-muted">No permission groups</span>
    {% endif %}

    {% if request.user.is_superuser or is_cid_user_manager %}
        <div class="dropdown">
            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="addAuthGroupDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                Add
            </button>
            <ul class="dropdown-menu" aria-labelledby="addAuthGroupDropdown">
                {% if available_auth_groups.count %}
                    {% for ag in available_auth_groups %}
                        <li>
                            <button
                                class="dropdown-item"
                                hx-post="{% url 'generic:user_toggle_group' user.pk ag.pk %}?type=auth"
                                hx-target="#auth-groups-{{ user.pk }}"
                                hx-swap="outerHTML"
                            >
                                {{ ag.name }}
                            </button>
                        </li>
                    {% endfor %}
                {% else %}
                    {% if request.user.is_superuser %}
                        <li>
                            <a class="dropdown-item" href="{% url 'admin:auth_group_add' %}" target="_blank" rel="noopener">Create permission group</a>
                        </li>
                    {% else %}
                        <li><span class="dropdown-item disabled">No groups available to add</span></li>
                    {% endif %}
                {% endif %}
            </ul>
        </div>
    {% endif %}
</div>
