{%- set zugeordnete = [] %}
{%- set verfuegbare = [] %}
{%- for b in alle_branchen %}
    {%- if b.id in zugeordnete_branchen_ids %}
        {%- if zugeordnete.append(b) %}{% endif %}
    {%- else %}
        {%- if verfuegbare.append(b) %}{% endif %}
    {%- endif %}
{%- endfor %}

{%- if zugeordnete %}
<div style="display: flex; flex-wrap: wrap; gap: 0.25rem;">
    {%- for b in zugeordnete %}
    <span class="tag-chip {% if editable %}removable{% endif %}"
          style="background: #bbdefb; color: #1565c0; border: 1px solid #90caf9;"
          {%- if editable %}
          hx-post="/kontakte/{{ kontakt_id }}/branchen/{{ b.id }}/toggle"
          hx-target="#branchen-container"
          hx-swap="innerHTML"
          hx-confirm="Branche '{{ b.name }}' wirklich entfernen?"
          title="Klicken zum Entfernen"
          {%- endif %}>
        {{ b.name }}
    </span>
    {%- endfor %}
</div>
{%- else %}
<span style="font-size: 0.85rem; color: var(--kw-text-muted);">Keine Branchen</span>
{%- endif %}

{%- if editable and 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').value=''; menu.querySelectorAll('.search-dropdown-item').forEach(function(el){el.style.display='';}); menu.querySelector('input').focus();}">
        + Branche hinzufügen…
    </button>
    <div class="search-dropdown-menu">
        <input type="text" placeholder="Suchen…" autocomplete="off"
               onclick="event.stopPropagation();"
               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';});">
        {%- for b in verfuegbare %}
        <div class="search-dropdown-item" data-search="{{ b.name|lower }}"
             onclick="htmx.ajax('POST', '/kontakte/{{ kontakt_id }}/branchen/{{ b.id }}/toggle', {target: '#branchen-container', swap: 'innerHTML'});">
            {{ b.name }}
        </div>
        {%- endfor %}
    </div>
</div>
{%- elif editable and not alle_branchen %}
<span style="font-size: 0.85rem; color: var(--kw-text-muted); margin-top: 0.5rem; display: inline-block;">Keine Branchen angelegt. <a href="/einstellungen/branchen">Einrichten</a></span>
{%- endif %}
