{%- if kontakt_tags %}
<div style="display: flex; flex-wrap: wrap; gap: 0.25rem;">
    {%- for kt in kontakt_tags %}
    <span class="tag-chip {% if editable %}removable{% endif %}"
          {%- if editable %}
          hx-post="/kontakte/{{ kontakt_id }}/tags/{{ kt.tag_id }}/toggle"
          hx-target="#tag-container"
          hx-swap="innerHTML"
          hx-confirm="Tag '{{ kt.tag.name }}' wirklich entfernen?"
          title="Klicken zum Entfernen"
          {%- endif %}
          style="{% if kt.tag.kategorie and kt.tag.kategorie.farbe %}border-left: 3px solid {{ kt.tag.kategorie.farbe }};{% endif %}">
        {{ kt.tag.name }}
    </span>
    {%- endfor %}
</div>
{%- else %}
<span style="font-size: 0.85rem; color: var(--kw-text-muted);">Keine Tags</span>
{%- endif %}

{%- if editable and kategorien %}
{%- set zugewiesene_tag_ids = kontakt_tags|map(attribute='tag_id')|list if kontakt_tags else [] %}
{%- set ns = namespace(hat_verfuegbare=false) %}
{%- for kat in kategorien %}
    {%- for tag in kat.tags %}
        {%- if tag.id not in zugewiesene_tag_ids %}
            {%- set ns.hat_verfuegbare = true %}
        {%- endif %}
    {%- endfor %}
{%- endfor %}
{%- if ns.hat_verfuegbare %}
<div class="search-dropdown">
    <button type="button" class="search-dropdown-toggle"
            onclick="var menu=this.nextElementSibling; menu.classList.toggle('open'); if(menu.classList.contains('open')){menu.querySelector('input').focus();}">
        + Tag hinzufügen…
    </button>
    <div class="search-dropdown-menu">
        <input type="text" placeholder="Suchen…" autocomplete="off"
               oninput="var q=this.value.toLowerCase(); this.closest('.search-dropdown-menu').querySelectorAll('.search-dropdown-item').forEach(function(el){el.style.display=el.dataset.search.indexOf(q)>=0?'':'none';}); this.closest('.search-dropdown-menu').querySelectorAll('.search-dropdown-group').forEach(function(g){var items=[];var sib=g.nextElementSibling;while(sib&&sib.classList.contains('search-dropdown-item')){items.push(sib);sib=sib.nextElementSibling;}g.style.display=items.some(function(i){return i.style.display!=='none';})?'':'none';});">
        {%- for kat in kategorien %}
        {%- set verfuegbar = [] %}
        {%- for tag in kat.tags %}
            {%- if tag.id not in zugewiesene_tag_ids %}
                {%- if verfuegbar.append(tag) %}{% endif %}
            {%- endif %}
        {%- endfor %}
        {%- if verfuegbar %}
        <div class="search-dropdown-group">{{ kat.name }}</div>
        {%- for tag in verfuegbar %}
        <div class="search-dropdown-item" data-search="{{ tag.name|lower }}"
             onclick="htmx.ajax('POST', '/kontakte/{{ kontakt_id }}/tags/{{ tag.id }}/toggle', {target: '#tag-container', swap: 'innerHTML'});">
            {{ tag.name }}
        </div>
        {%- endfor %}
        {%- endif %}
        {%- endfor %}
    </div>
</div>
{%- endif %}
{%- endif %}
