{% extends "base.html" %}
{% block title %}Recherche{{ " - " + app_name() }}{% endblock %}

{% block content %}
<div class="page-header">
    <h1>Recherche</h1>
    <div class="btn-group">
        {% if gespeicherte %}
        <a href="/recherche/gespeichert" role="button" class="btn-sm outline">Gespeicherte ({{ gespeicherte|length }})</a>
        {% endif %}
        {% if hat_filter and gesamt > 0 %}
        <button type="button" class="btn-sm outline" onclick="exportAction('/recherche/export/csv')">CSV Export</button>
        <button type="button" class="btn-sm outline" onclick="exportAction('/recherche/export/emails')">E-Mail-Liste</button>
        <button type="button" class="btn-sm" onclick="exportAction('/recherche/zu-kampagne', true)">An Kampagne</button>
        <button type="button" class="btn-sm outline" onclick="openAktivitaetDialog()">Aktivität für alle</button>
        <button type="button" class="btn-sm" onclick="openSpeichernDialog()">Recherche speichern</button>
        {% endif %}
    </div>
</div>

<!-- Filter -->
<div class="card" style="margin-bottom: 1.5rem;">
    <div class="card-header"><h3>Filter kombinieren</h3></div>
    <form method="get" action="/recherche#ergebnisse" autocomplete="off">

        <!-- Zeile 1: Freitext + Suchfelder + Typ -->
        <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Freitext</label>
                <input type="text" name="q" value="{{ params.get('q', '') }}" placeholder="z.B. Müller, Stiftung..."
                       style="margin: 0; font-size: 0.85rem; padding: 0.4rem 0.6rem;">
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Suche in</label>
                {% set aktive_felder = q_felder if q_felder else [] %}
                <div class="search-dropdown" style="margin-top: 0;">
                    <button type="button" class="search-dropdown-toggle" id="felder-toggle"
                            style="font-size: 0.85rem; padding: 0.4rem 0.6rem; height: auto;"
                            onclick="var menu=this.nextElementSibling; menu.classList.toggle('open');">
                        {% if aktive_felder %}{{ aktive_felder|length }} ausgewählt{% else %}Alle Felder{% endif %}
                    </button>
                    <div class="search-dropdown-menu" onclick="event.stopPropagation();" style="max-height: 220px;">
                        {% set felder_optionen = [
                            ('name', 'Name'),
                            ('organisation', 'Organisation'),
                            ('email', 'E-Mail'),
                            ('adresse', 'Adresse / Ort'),
                            ('telefon', 'Telefon'),
                            ('position', 'Position'),
                            ('bemerkung', 'Bemerkung'),
                        ] %}
                        {% for wert, label in felder_optionen %}
                        <label class="search-dropdown-item" style="display: flex; align-items: center; gap: 0.4rem; cursor: pointer; user-select: none;">
                            <input type="checkbox" name="q_feld" value="{{ wert }}"
                                   {% if wert in aktive_felder %}checked{% endif %}
                                   onchange="var checked=this.closest('.search-dropdown-menu').querySelectorAll('input:checked').length; document.getElementById('felder-toggle').textContent=checked?checked+' ausgewählt':'Alle Felder';"
                                   style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                            {{ label }}
                        </label>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Typ</label>
                <select name="typ" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Alle</option>
                    <option value="person" {% if params.get('typ') == 'person' %}selected{% endif %}>Personen</option>
                    <option value="organisation" {% if params.get('typ') == 'organisation' %}selected{% endif %}>Organisationen</option>
                </select>
            </div>
        </div>

        <!-- Zeile 2: Gruppen (Checkboxen) -->
        <div style="margin-bottom: 1rem; padding: 0.75rem; border: 1px solid var(--kw-border); border-radius: 6px;">
            <label style="font-size: 0.8rem; font-weight: 600; margin-bottom: 0.4rem; display: block;">Gruppen</label>
            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                {% for g in gruppen %}
                <label style="display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.85rem; cursor: pointer; user-select: none;">
                    <input type="checkbox" name="gruppe" value="{{ g.id }}" {% if g.id in aktive_gruppe_ids %}checked{% endif %}
                           onclick="event.stopPropagation()"
                           style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                    <span class="gruppe-badge" style="background: {{ g.farbe }};">{{ g.kuerzel }}</span>
                    {{ g.name }}
                </label>
                {% endfor %}
            </div>
        </div>

        <!-- Zeile 3: Tags (Checkboxen) mit AND/OR -->
        <div style="margin-bottom: 1rem; padding: 0.75rem; border: 1px solid var(--kw-border); border-radius: 6px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                <label style="font-size: 0.8rem; font-weight: 600;">Tags</label>
                <div style="display: flex; gap: 0.5rem; align-items: center; font-size: 0.8rem;">
                    <label style="display: flex; align-items: center; gap: 0.2rem; cursor: pointer;">
                        <input type="radio" name="tag_logic" value="oder" {% if params.get('tag_logic', 'oder') == 'oder' %}checked{% endif %}
                               style="margin: 0; width: auto;"> ODER
                    </label>
                    <label style="display: flex; align-items: center; gap: 0.2rem; cursor: pointer;">
                        <input type="radio" name="tag_logic" value="und" {% if params.get('tag_logic') == 'und' %}checked{% endif %}
                               style="margin: 0; width: auto;"> UND
                    </label>
                </div>
            </div>
            {% for kat in kategorien %}
            {% if kat.tags %}
            <div style="margin-bottom: 0.4rem;">
                <span style="font-size: 0.7rem; text-transform: uppercase; color: {{ kat.farbe }}; font-weight: 600;">{{ kat.name }}</span>
                <div style="display: flex; gap: 0.6rem; flex-wrap: wrap; margin-top: 0.2rem;">
                    {% for t in kat.tags %}
                    <label style="display: inline-flex; align-items: center; gap: 0.2rem; font-size: 0.8rem; cursor: pointer; user-select: none;">
                        <input type="checkbox" name="tag" value="{{ t.id }}" {% if t.id in aktive_tag_ids %}checked{% endif %}
                               onclick="event.stopPropagation()"
                               style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                        {{ t.name }}
                    </label>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
            {% endfor %}
        </div>

        <!-- Zeile 4: Ort, PLZ, Betreuer -->
        <div class="form-grid" style="gap: 0.75rem 1.5rem; margin-bottom: 1rem;">
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Ort</label>
                <input type="text" name="ort" value="{{ params.get('ort', '') }}" placeholder="z.B. Koblenz"
                       style="margin: 0; font-size: 0.85rem; padding: 0.4rem 0.6rem;">
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">PLZ (Bereich)</label>
                <input type="text" name="plz" value="{{ params.get('plz', '') }}" placeholder="z.B. 56 für 56xxx"
                       style="margin: 0; font-size: 0.85rem; padding: 0.4rem 0.6rem;">
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Betreuer</label>
                <select name="betreuer" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Alle</option>
                    {% for b in benutzer %}
                    <option value="{{ b.kuerzel }}" {% if params.get('betreuer') == b.kuerzel %}selected{% endif %}>{{ b.name }} ({{ b.kuerzel }})</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Eigentümer</label>
                <select name="eigentuemer" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Alle</option>
                    {% for b in benutzer %}
                    <option value="{{ b.kuerzel }}" {% if params.get('eigentuemer') == b.kuerzel %}selected{% endif %}>{{ b.name }} ({{ b.kuerzel }})</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">E-Mail vorhanden</label>
                <select name="hat_email" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('hat_email') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('hat_email') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Telefon vorhanden</label>
                <select name="hat_telefon" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('hat_telefon') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('hat_telefon') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
        </div>

        <!-- Zeile 5: Kommunikations-Praeferenzen -->
        <div class="form-grid" style="gap: 0.75rem 1.5rem; margin-bottom: 1rem;">
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Newsletter</label>
                <select name="newsletter" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('newsletter') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('newsletter') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Keine Mails</label>
                <select name="keine_mails" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('keine_mails') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('keine_mails') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Keine Briefe</label>
                <select name="keine_briefe" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('keine_briefe') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('keine_briefe') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
            <div>
                <label style="font-size: 0.8rem; margin-bottom: 0.2rem;">Keine Anrufe</label>
                <select name="keine_anrufe" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                    <option value="">Egal</option>
                    <option value="ja" {% if params.get('keine_anrufe') == 'ja' %}selected{% endif %}>Ja</option>
                    <option value="nein" {% if params.get('keine_anrufe') == 'nein' %}selected{% endif %}>Nein</option>
                </select>
            </div>
        </div>

        <!-- Zeile 6: Projekt-Filter -->
        {% if projekte %}
        <div style="margin-bottom: 1rem; padding: 0.75rem; border: 1px solid var(--kw-border); border-radius: 6px;">
            <label style="font-size: 0.8rem; font-weight: 600; margin-bottom: 0.4rem; display: block;">Projekte</label>
            <div class="search-dropdown" style="margin-top: 0;">
                <button type="button" class="search-dropdown-toggle" id="projekt-filter-toggle"
                        style="font-size: 0.85rem; padding: 0.4rem 0.6rem; height: auto;"
                        onclick="var menu=this.nextElementSibling; menu.classList.toggle('open');">
                    {% if aktive_projekte %}{{ aktive_projekte|length }} ausgewählt{% else %}Alle Projekte{% endif %}
                </button>
                <div class="search-dropdown-menu" onclick="event.stopPropagation();" style="max-height: 250px;">
                    <input type="text" placeholder="Projekt 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 p in projekte %}
                    <label class="search-dropdown-item" data-search="{{ p|lower }}" style="display: flex; align-items: center; gap: 0.4rem; cursor: pointer; user-select: none;">
                        <input type="checkbox" name="projekt" value="{{ p }}"
                               {% if p in aktive_projekte %}checked{% endif %}
                               onchange="var checked=this.closest('.search-dropdown-menu').querySelectorAll('input:checked').length; document.getElementById('projekt-filter-toggle').textContent=checked?checked+' ausgewählt':'Alle Projekte';"
                               style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                        {{ p }}
                    </label>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Aktivitäten-Filter -->
        <div style="margin-bottom: 1rem; padding: 0.75rem; border: 1px solid var(--kw-border); border-radius: 6px;">
            <label style="font-size: 0.8rem; font-weight: 600; margin-bottom: 0.6rem; display: block;">
                📋 Aktivitäten – Personen/Orgs mit passenden Aktivitäten finden
            </label>
            <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 0.75rem;">
                <div>
                    <label style="font-size: 0.75rem; color: var(--kw-text-muted); margin-bottom: 0.2rem; display: block;">Freitext (Betreff / Inhalt)</label>
                    <input type="text" name="akt_text" value="{{ params.get('akt_text', '') }}"
                           placeholder="z.B. Sitzung, Förderantrag…"
                           style="margin: 0; font-size: 0.85rem; padding: 0.4rem 0.6rem;">
                </div>
                <div>
                    <label style="font-size: 0.75rem; color: var(--kw-text-muted); margin-bottom: 0.2rem; display: block;">Art der Aktivität</label>
                    <select name="akt_art" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                        <option value="">Alle Arten</option>
                        {% for opt in kat_optionen("aktivitaet_art") %}{% set key = opt.wert %}{% set label = opt.label %}
                        <option value="{{ key }}" {% if params.get('akt_art') == key %}selected{% endif %}>{{ label }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label style="font-size: 0.75rem; color: var(--kw-text-muted); margin-bottom: 0.2rem; display: block;">Status der Aktivität</label>
                    <select name="akt_status" style="margin: 0; font-size: 0.85rem; padding: 0.4rem;">
                        <option value="">Alle Stati</option>
                        <option value="offen" {% if params.get('akt_status') == 'offen' %}selected{% endif %}>Offen</option>
                        <option value="erledigt" {% if params.get('akt_status') == 'erledigt' %}selected{% endif %}>Erledigt</option>
                        <option value="information" {% if params.get('akt_status') == 'information' %}selected{% endif %}>Information</option>
                    </select>
                </div>
            </div>
            <p style="font-size: 0.75rem; color: var(--kw-text-muted); margin: 0.5rem 0 0;">
                Findet Personen &amp; Organisationen, an denen mindestens eine Aktivität mit diesen Kriterien hängt. Kombinierbar mit allen anderen Filtern.
            </p>
        </div>

        <!-- Kampagnen-Filter -->
        {% if kampagnen %}
        <div style="margin-bottom: 1rem; padding: 0.75rem; border: 1px solid var(--kw-border); border-radius: 6px;">
            <label style="font-size: 0.8rem; font-weight: 600; margin-bottom: 0.4rem; display: block;">📢 Kampagne</label>
            <select name="r_kampagne" style="margin: 0; font-size: 0.85rem; padding: 0.4rem; max-width: 350px;">
                <option value="">Alle Kampagnen</option>
                {% for k in kampagnen %}
                <option value="{{ k.id }}" {% if params.get('r_kampagne') == k.id|string %}selected{% endif %}>{{ k.titel }}</option>
                {% endfor %}
            </select>
            <p style="font-size: 0.75rem; color: var(--kw-text-muted); margin: 0.4rem 0 0;">
                Nur Kontakte die in dieser Kampagne enthalten sind.
            </p>
        </div>
        {% endif %}

        <div style="display: flex; gap: 0.75rem;">
            <button type="submit" class="btn-sm" style="margin: 0;">Recherchieren</button>
            {% if hat_filter %}
            <a href="/recherche" class="btn-sm outline" style="margin: 0;">Zurücksetzen</a>
            {% endif %}
        </div>
    </form>
</div>

<!-- Ergebnisse -->
{% if hat_filter %}
<div class="card" id="ergebnisse">
    <div class="card-header" style="flex-wrap: wrap; gap: 0.5rem;">
        <h3>Ergebnisse ({{ gesamt }}{% if gesamt > 1000 %}, zeige 1.000{% endif %})</h3>
        {% if gesamt > 0 %}
        <div style="display: flex; align-items: center; gap: 1rem; font-size: 0.8rem;">
            <span id="sel-counter" style="color: var(--kw-text-muted);"></span>
            <button type="button" class="btn-sm outline" style="margin: 0; font-size: 0.75rem; padding: 0.2rem 0.5rem;" onclick="selectAll(true)">Alle</button>
            <button type="button" class="btn-sm outline" style="margin: 0; font-size: 0.75rem; padding: 0.2rem 0.5rem;" onclick="selectAll(false)">Keine</button>
        </div>
        {% endif %}
    </div>

    {% if ergebnis and (ergebnis.org_gruppen or ergebnis.standalone) %}

    <!-- Spalten-Config fuer Ergebnistabelle -->
    <div style="display: flex; justify-content: flex-end; margin-bottom: 0.3rem;">
        <div class="search-dropdown" style="margin-top: 0;">
            <button type="button" class="search-dropdown-toggle" id="rech-spalten-toggle"
                    style="font-size: 0.75rem; padding: 0.2rem 0.5rem;"
                    onclick="var menu=this.nextElementSibling; menu.classList.toggle('open');">
                Spalten
            </button>
            <div class="search-dropdown-menu" onclick="event.stopPropagation();" style="max-height: 300px; right: 0; left: auto;">
                {% set rech_spalten = [
                    ('r-ort', 'Ort'),
                    ('r-plz', 'PLZ'),
                    ('r-email', 'E-Mail'),
                    ('r-telefon', 'Telefon'),
                    ('r-webseite', 'Webseite'),
                    ('r-betreuer', 'Betreuer'),
                ] %}
                {% for key, label in rech_spalten %}
                <label class="search-dropdown-item" style="display: flex; align-items: center; gap: 0.4rem; cursor: pointer; user-select: none;">
                    <input type="checkbox" class="rech-spalte-cb" data-col="{{ key }}"
                           onchange="toggleRechSpalte('{{ key }}', this.checked)"
                           style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                    {{ label }}
                </label>
                {% endfor %}
            </div>
        </div>
    </div>

    <table class="data-table">
        <thead>
            <tr>
                <th style="width: 2rem;"></th>
                <th style="width: 2rem;"></th>
                <th>Name</th>
                <th data-col="r-ort">Ort</th>
                <th data-col="r-plz" style="display: none;">PLZ</th>
                <th data-col="r-email">E-Mail</th>
                <th data-col="r-telefon">Telefon</th>
                <th data-col="r-webseite" style="display: none;">Webseite</th>
                <th data-col="r-betreuer" style="display: none;">Betreuer</th>
            </tr>
        </thead>
        <tbody>
            {# === Org-Gruppen === #}
            {% for gruppe in ergebnis.org_gruppen %}
            <tr class="org-header" data-org-id="{{ gruppe.org.id }}" style="background: var(--kw-org-bg, #e3f2fd);">
                <td style="text-align: center; white-space: nowrap;">
                    {% if gruppe.mitarbeiter %}
                    <button type="button" class="toggle-btn" id="toggle-{{ gruppe.org.id }}"
                            onclick="event.stopPropagation(); toggleOrg({{ gruppe.org.id }})"
                            style="padding: 0; font-size: 0.65rem; border: none; cursor: pointer; color: var(--kw-text-muted); background: none; vertical-align: middle;"
                            title="Mitarbeiter ein-/ausblenden">&#x25BC;</button>
                    {% endif %}
                    <input type="checkbox" class="kontakt-cb org-cb"
                           data-id="{{ gruppe.org.id }}" data-org-id="{{ gruppe.org.id }}"
                           {% if gruppe.gefunden %}checked{% endif %}
                           onclick="event.stopPropagation(); toggleOrgCheckbox({{ gruppe.org.id }})"
                           style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                </td>
                <td style="text-align: center; width: 2rem;">&#x1F3E2;</td>
                <td style="font-weight: 600;">
                    <a href="/kontakte/{{ gruppe.org.id }}" onclick="event.stopPropagation()">{{ gruppe.org.anzeigename }}</a>
                    {% if gruppe.mitarbeiter %}
                    <span style="font-size: 0.75rem; color: var(--kw-text-muted); font-weight: 400;">({{ gruppe.mitarbeiter|length }} MA)</span>
                    {% endif %}
                </td>
                <td data-col="r-ort" style="font-size: 0.85rem;">{{ gruppe.org.ort or '-' }}</td>
                <td data-col="r-plz" style="font-size: 0.85rem; display: none;">{{ gruppe.org.plz or '-' }}</td>
                <td data-col="r-email" style="font-size: 0.85rem;">
                    {% if gruppe.org.email1 %}<a href="mailto:{{ gruppe.org.email1 }}" onclick="event.stopPropagation()">{{ gruppe.org.email1 }}</a>{% else %}-{% endif %}
                </td>
                <td data-col="r-telefon" style="font-size: 0.85rem;">{{ gruppe.org.telefon or '-' }}</td>
                <td data-col="r-webseite" style="font-size: 0.85rem; display: none;">{% if gruppe.org.webseite %}<a href="{{ gruppe.org.webseite }}" target="_blank">{{ gruppe.org.webseite }}</a>{% else %}-{% endif %}</td>
                <td data-col="r-betreuer" style="font-size: 0.85rem; display: none;">{{ gruppe.org.betreuer or '-' }}</td>
            </tr>
            {% for ma in gruppe.mitarbeiter %}
            <tr class="ma-row ma-of-{{ gruppe.org.id }}">
                <td style="text-align: center;">
                    <input type="checkbox" class="kontakt-cb ma-cb"
                           data-id="{{ ma.kontakt.id }}" data-parent-org="{{ gruppe.org.id }}"
                           checked
                           onclick="event.stopPropagation(); onMaCheckboxChange({{ gruppe.org.id }})"
                           style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                </td>
                <td style="width: 2rem; padding-left: 3rem;">&#x1F464;</td>
                <td style="padding-left: 0.5rem;">
                    <a href="/kontakte/{{ ma.kontakt.id }}" onclick="event.stopPropagation()">{{ ma.kontakt.anzeigename }}</a>
                </td>
                <td data-col="r-ort" style="font-size: 0.85rem;">{{ ma.kontakt.ort or '-' }}</td>
                <td data-col="r-plz" style="font-size: 0.85rem; display: none;">{{ ma.kontakt.plz or '-' }}</td>
                <td data-col="r-email" style="font-size: 0.85rem;">
                    {% if ma.kontakt.email1 %}<a href="mailto:{{ ma.kontakt.email1 }}" onclick="event.stopPropagation()">{{ ma.kontakt.email1 }}</a>{% else %}-{% endif %}
                </td>
                <td data-col="r-telefon" style="font-size: 0.85rem;">{{ ma.kontakt.telefon or ma.kontakt.mobil or ma.kontakt.telefon_direkt or '-' }}</td>
                <td data-col="r-webseite" style="font-size: 0.85rem; display: none;">{% if ma.kontakt.webseite %}<a href="{{ ma.kontakt.webseite }}" target="_blank">{{ ma.kontakt.webseite }}</a>{% else %}-{% endif %}</td>
                <td data-col="r-betreuer" style="font-size: 0.85rem; display: none;">{{ ma.kontakt.betreuer or '-' }}</td>
            </tr>
            {% endfor %}
            {% endfor %}

            {# === Standalone-Personen === #}
            {% for k in ergebnis.standalone %}
            <tr>
                <td style="text-align: center;">
                    <input type="checkbox" class="kontakt-cb" data-id="{{ k.id }}" checked
                           onclick="event.stopPropagation(); updateCounter()"
                           style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                </td>
                <td style="text-align: center; width: 2rem;">&#x1F464;</td>
                <td>
                    <a href="/kontakte/{{ k.id }}" onclick="event.stopPropagation()">{{ k.anzeigename }}</a>
                </td>
                <td data-col="r-ort" style="font-size: 0.85rem;">{{ k.ort or '-' }}</td>
                <td data-col="r-plz" style="font-size: 0.85rem; display: none;">{{ k.plz or '-' }}</td>
                <td data-col="r-email" style="font-size: 0.85rem;">
                    {% if k.email1 %}<a href="mailto:{{ k.email1 }}" onclick="event.stopPropagation()">{{ k.email1 }}</a>{% else %}-{% endif %}
                </td>
                <td data-col="r-telefon" style="font-size: 0.85rem;">{{ k.telefon or k.mobil or k.telefon_direkt or '-' }}</td>
                <td data-col="r-webseite" style="font-size: 0.85rem; display: none;">{% if k.webseite %}<a href="{{ k.webseite }}" target="_blank">{{ k.webseite }}</a>{% else %}-{% endif %}</td>
                <td data-col="r-betreuer" style="font-size: 0.85rem; display: none;">{{ k.betreuer or '-' }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <div style="display: flex; gap: 0.5rem; margin-top: 1rem; padding-top: 0.75rem; border-top: 1px solid var(--kw-border); flex-wrap: wrap;">
        <button type="button" class="btn-sm outline" onclick="exportAction('/recherche/export/csv')">CSV Export</button>
        <button type="button" class="btn-sm outline" onclick="exportAction('/recherche/export/emails')">E-Mail-Liste</button>
        <button type="button" class="btn-sm" onclick="exportAction('/recherche/zu-kampagne', true)">An Kampagne</button>
        <button type="button" class="btn-sm outline" onclick="openAktivitaetDialog()">Aktivität für alle</button>
        <button type="button" class="btn-sm" onclick="openSpeichernDialog()">Recherche speichern</button>
    </div>
    {% else %}
    <div class="empty-state">
        <div class="empty-state-icon">&#x1F50D;</div>
        <p>Keine Kontakte gefunden. Passe die Filter an.</p>
    </div>
    {% endif %}
</div>
{% else %}
<div class="card">
    <div class="empty-state">
        <div class="empty-state-icon">&#x1F3AF;</div>
        <p>Wähle mindestens einen Filter und klicke auf "Recherchieren".</p>
    </div>
</div>
{% endif %}

<!-- Verstecktes Export-Formular -->
<form id="export-form" method="post" style="display: none;">
    <div id="export-ids"></div>
</form>

<!-- Kampagne-Dialog -->
{% if hat_filter and gesamt > 0 %}
<dialog id="kampagne-dialog" style="border-radius: 8px; border: 1px solid var(--kw-border); padding: 1.5rem; max-width: 450px; width: 90%;">
    <form id="kampagne-form" method="post" action="/recherche/zu-kampagne">
        <h3 style="margin-top: 0;" id="kampagne-dialog-titel">Kontakte an Kampagne übergeben</h3>
        <div id="kampagne-ids"></div>

        <div style="margin-bottom: 1rem;">
            <label style="font-size: 0.85rem; font-weight: 600;">Bestehende Kampagne</label>
            <input type="hidden" name="kampagne_id" id="kampagne-id-value" value="">
            <div class="search-dropdown" style="margin-top: 0;">
                <button type="button" class="search-dropdown-toggle" id="kampagne-toggle"
                        style="font-size: 0.85rem; padding: 0.4rem 0.6rem; height: auto;"
                        onclick="var m=this.nextElementSibling; m.classList.toggle('open'); if(m.classList.contains('open')){var inp=m.querySelector('input[type=text]'); if(inp){inp.value='';} m.querySelectorAll('.search-dropdown-item').forEach(function(el){el.style.display='';}); if(inp) inp.focus();}">
                    -- Auswählen --
                </button>
                <div class="search-dropdown-menu" style="max-height: 280px;">
                    <input type="text" placeholder="Kampagne 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';});">
                    <div class="search-dropdown-item" data-search="" data-value=""
                         onclick="document.getElementById('kampagne-id-value').value=''; document.getElementById('kampagne-toggle').textContent='-- Auswählen --'; this.closest('.search-dropdown-menu').classList.remove('open'); document.getElementById('neuer-titel').disabled=true; document.getElementById('neuer-titel').value='';">
                        -- Auswählen --
                    </div>
                    {% for k in kampagnen %}
                    <div class="search-dropdown-item" data-search="{{ k.titel|lower }}" data-value="{{ k.id }}"
                         onclick="document.getElementById('kampagne-id-value').value='{{ k.id }}'; document.getElementById('kampagne-toggle').textContent='{{ k.titel }}'; this.closest('.search-dropdown-menu').classList.remove('open'); document.getElementById('neuer-titel').disabled=true; document.getElementById('neuer-titel').value='';">
                        {{ k.titel }} <span style="font-size:0.75rem; color:var(--kw-text-muted);">({{ k.kontakte|length }} Kontakte)</span>
                    </div>
                    {% endfor %}
                    <div class="search-dropdown-item" data-search="neue kampagne neu anlegen" data-value="neu"
                         style="color: var(--kw-primary); font-weight: 600; border-top: 1px solid var(--kw-border); margin-top: 0.25rem; padding-top: 0.5rem;"
                         onclick="document.getElementById('kampagne-id-value').value='neu'; document.getElementById('kampagne-toggle').textContent='+ Neue Kampagne anlegen'; this.closest('.search-dropdown-menu').classList.remove('open'); document.getElementById('neuer-titel').disabled=false; document.getElementById('neuer-titel').focus();">
                        + Neue Kampagne anlegen
                    </div>
                </div>
            </div>
        </div>

        <div style="margin-bottom: 1.5rem;">
            <label for="neuer-titel" style="font-size: 0.85rem; font-weight: 600;">Titel für neue Kampagne</label>
            <input type="text" id="neuer-titel" name="neuer_titel" placeholder="z.B. Mailing März 2026" disabled style="margin: 0;">
        </div>

        <div class="btn-group">
            <button type="submit">Übergeben</button>
            <button type="button" class="outline" onclick="document.getElementById('kampagne-dialog').close()">Abbrechen</button>
        </div>
    </form>
</dialog>
<!-- Aktivität-Dialog -->
<dialog id="aktivitaet-dialog" style="border-radius: 8px; border: 1px solid var(--kw-border); padding: 1.5rem; max-width: 500px; width: 90%;">
    <form id="aktivitaet-form" method="post" action="/aktivitaeten/bulk">
        <h3 style="margin-top: 0;" id="aktivitaet-dialog-titel">Aktivität für Kontakte erstellen</h3>
        <div id="aktivitaet-ids"></div>

        <div style="margin-bottom: 0.75rem;">
            <label style="font-size: 0.85rem; font-weight: 600;">Art</label>
            <select name="art" style="margin: 0;" required>
                {% for opt in kat_optionen("aktivitaet_art") %}{% set key = opt.wert %}{% set label = opt.label %}
                <option value="{{ key }}">{{ label }}</option>
                {% endfor %}
            </select>
        </div>

        <div style="margin-bottom: 0.75rem;">
            <label style="font-size: 0.85rem; font-weight: 600;">Betreff</label>
            <input type="text" name="betreff" placeholder="z.B. Einladung Jahrestreffen" style="margin: 0;" required>
        </div>

        <div style="margin-bottom: 0.75rem;">
            <label style="font-size: 0.85rem; font-weight: 600;">Bemerkung</label>
            <textarea name="bemerkung" rows="3" style="margin: 0;"></textarea>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin-bottom: 0.75rem;">
            <div>
                <label style="font-size: 0.85rem; font-weight: 600;">Status</label>
                <select name="status" style="margin: 0;">
                    <option value="erledigt">Erledigt</option>
                    <option value="offen">Offen</option>
                </select>
            </div>
            <div>
                <label style="font-size: 0.85rem; font-weight: 600;">Zugewiesen an</label>
                <select name="zugewiesen_an" style="margin: 0;">
                    <option value="">-</option>
                    {% for b in benutzer %}
                    <option value="{{ b.kuerzel }}">{{ b.name }} ({{ b.kuerzel }})</option>
                    {% endfor %}
                </select>
            </div>
        </div>

        <div class="btn-group">
            <button type="submit" id="aktivitaet-submit-btn">Erstellen</button>
            <button type="button" class="outline" onclick="document.getElementById('aktivitaet-dialog').close()">Abbrechen</button>
        </div>
    </form>
</dialog>

<!-- Recherche-Speichern-Dialog -->
<dialog id="speichern-dialog" style="border-radius: 8px; border: 1px solid var(--kw-border); padding: 1.5rem; max-width: 450px; width: 90%;">
    <form id="speichern-form" method="post" action="/recherche/speichern">
        <h3 style="margin-top: 0;" id="speichern-dialog-titel">Recherche speichern</h3>
        <div id="speichern-ids"></div>

        <div style="margin-bottom: 1.5rem;">
            <label style="font-size: 0.85rem; font-weight: 600;">Name</label>
            <input type="text" name="name" placeholder="z.B. Mailing Zielgruppe März 2026" required style="margin: 0;">
        </div>

        <div class="btn-group">
            <button type="submit">Speichern</button>
            <button type="button" class="outline" onclick="document.getElementById('speichern-dialog').close()">Abbrechen</button>
        </div>
    </form>
</dialog>
{% endif %}

{% if hat_filter and gesamt > 0 %}
<script>
/* --- Selektion & Gruppierung --- */

function getCheckedIds() {
    return Array.from(document.querySelectorAll('.kontakt-cb:checked')).map(cb => cb.dataset.id);
}

function countChecked() {
    return document.querySelectorAll('.kontakt-cb:checked').length;
}

function countTotal() {
    return document.querySelectorAll('.kontakt-cb').length;
}

function updateCounter() {
    var el = document.getElementById('sel-counter');
    if (el) el.textContent = countChecked() + ' von ' + countTotal() + ' ausgewählt';
}

/* Alle / Keine */
function selectAll(checked) {
    document.querySelectorAll('.kontakt-cb').forEach(function(cb) { cb.checked = checked; });
    /* Bei "Alle": alle Org-Gruppen mit MA aufklappen. Bei "Keine": alle zuklappen. */
    document.querySelectorAll('.org-header').forEach(function(row) {
        var orgId = row.dataset.orgId;
        var maRows = document.querySelectorAll('.ma-of-' + orgId);
        if (maRows.length > 0) setOrgExpanded(orgId, checked);
    });
    updateCounter();
}

/* Org auf-/zuklappen */
function setOrgExpanded(orgId, expanded) {
    var maRows = document.querySelectorAll('.ma-of-' + orgId);
    maRows.forEach(function(r) { r.style.display = expanded ? '' : 'none'; });
    var btn = document.getElementById('toggle-' + orgId);
    if (btn) btn.innerHTML = expanded ? '&#x25BC;' : '&#x25B6;';
}

function isOrgExpanded(orgId) {
    var first = document.querySelector('.ma-of-' + orgId);
    return first && first.style.display !== 'none';
}

function toggleOrg(orgId) {
    setOrgExpanded(orgId, !isOrgExpanded(orgId));
}

/* Org-Checkbox togglet alle MA */
function toggleOrgCheckbox(orgId) {
    var orgCb = document.querySelector('.org-cb[data-org-id="' + orgId + '"]');
    var checked = orgCb.checked;
    document.querySelectorAll('.ma-cb[data-parent-org="' + orgId + '"]').forEach(function(cb) {
        cb.checked = checked;
    });
    /* Aufklappen wenn angehakt, zuklappen wenn abgehakt */
    var hasMa = document.querySelectorAll('.ma-of-' + orgId).length > 0;
    if (hasMa) {
        if (checked) {
            setOrgExpanded(orgId, true);
        } else {
            setOrgExpanded(orgId, false);
        }
    }
    updateCounter();
}

/* MA-Checkbox Änderung */
function onMaCheckboxChange(orgId) {
    var maCbs = document.querySelectorAll('.ma-cb[data-parent-org="' + orgId + '"]');
    var anyChecked = Array.from(maCbs).some(function(cb) { return cb.checked; });
    var allUnchecked = !anyChecked;

    /* Wenn alle MA abgehakt → zuklappen */
    if (allUnchecked) {
        setOrgExpanded(orgId, false);
    }
    /* Wenn MA angehakt bei zugeklappter Org → aufklappen */
    if (anyChecked && !isOrgExpanded(orgId)) {
        setOrgExpanded(orgId, true);
    }
    updateCounter();
}

/* Export-Aktion */
function exportAction(url, isKampagne) {
    var ids = getCheckedIds();
    if (ids.length === 0) { alert('Keine Kontakte ausgewählt.'); return; }

    if (isKampagne) {
        /* Kampagne-Dialog öffnen, IDs einfügen */
        var container = document.getElementById('kampagne-ids');
        container.innerHTML = '';
        ids.forEach(function(id) {
            var inp = document.createElement('input');
            inp.type = 'hidden'; inp.name = 'kontakt_ids'; inp.value = id;
            container.appendChild(inp);
        });
        document.getElementById('kampagne-dialog-titel').textContent = ids.length + ' Kontakte an Kampagne übergeben';
        document.getElementById('kampagne-dialog').showModal();
    } else {
        /* Direkter Download via hidden form */
        var form = document.getElementById('export-form');
        form.action = url;
        var container = document.getElementById('export-ids');
        container.innerHTML = '';
        ids.forEach(function(id) {
            var inp = document.createElement('input');
            inp.type = 'hidden'; inp.name = 'kontakt_ids'; inp.value = id;
            container.appendChild(inp);
        });
        form.submit();
    }
}

/* Recherche-Speichern-Dialog öffnen */
function openSpeichernDialog() {
    var ids = getCheckedIds();
    if (ids.length === 0) { alert('Keine Kontakte ausgewählt.'); return; }

    var container = document.getElementById('speichern-ids');
    container.innerHTML = '';
    ids.forEach(function(id) {
        var inp = document.createElement('input');
        inp.type = 'hidden'; inp.name = 'kontakt_ids'; inp.value = id;
        container.appendChild(inp);
    });
    document.getElementById('speichern-dialog-titel').textContent = ids.length + ' Kontakte speichern';
    document.getElementById('speichern-dialog').showModal();
}

/* Aktivität-Dialog öffnen */
function openAktivitaetDialog() {
    var ids = getCheckedIds();
    if (ids.length === 0) { alert('Keine Kontakte ausgewählt.'); return; }

    var container = document.getElementById('aktivitaet-ids');
    container.innerHTML = '';
    ids.forEach(function(id) {
        var inp = document.createElement('input');
        inp.type = 'hidden'; inp.name = 'kontakt_ids'; inp.value = id;
        container.appendChild(inp);
    });
    document.getElementById('aktivitaet-dialog-titel').textContent = 'Aktivität für ' + ids.length + ' Kontakte erstellen';
    document.getElementById('aktivitaet-submit-btn').textContent = 'Für ' + ids.length + ' Kontakte erstellen';
    document.getElementById('aktivitaet-dialog').showModal();
}

/* --- Recherche Spalten-Config --- */
var RECH_SPALTEN_DEFAULT = ['r-ort', 'r-email', 'r-telefon'];

function getRechSpalten() {
    try {
        var gespeichert = localStorage.getItem('rech_spalten');
        if (gespeichert) return JSON.parse(gespeichert);
    } catch(e) {}
    return RECH_SPALTEN_DEFAULT;
}

function saveRechSpalten(spalten) {
    try { localStorage.setItem('rech_spalten', JSON.stringify(spalten)); } catch(e) {}
}

function toggleRechSpalte(col, visible) {
    var zellen = document.querySelectorAll('[data-col="' + col + '"]');
    zellen.forEach(function(el) { el.style.display = visible ? '' : 'none'; });
    var spalten = getRechSpalten();
    if (visible && spalten.indexOf(col) < 0) {
        spalten.push(col);
    } else if (!visible) {
        spalten = spalten.filter(function(s) { return s !== col; });
    }
    saveRechSpalten(spalten);
}

/* Initial: Orgs ohne MA zuklappen, Orgs mit MA aufgeklappt lassen */
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.org-header').forEach(function(row) {
        var orgId = row.dataset.orgId;
        var hasMa = document.querySelectorAll('.ma-of-' + orgId).length > 0;
        if (!hasMa) {
            /* Kein Toggle-Button nötig, nichts zu klappen */
        }
        /* MA-Rows sind default sichtbar (kein display:none) → aufgeklappt */
    });
    updateCounter();

    /* Recherche-Spalten aus LocalStorage wiederherstellen */
    var aktiveRech = getRechSpalten();
    document.querySelectorAll('.rech-spalte-cb').forEach(function(cb) {
        var col = cb.dataset.col;
        var sichtbar = aktiveRech.indexOf(col) >= 0;
        cb.checked = sichtbar;
        var zellen = document.querySelectorAll('[data-col="' + col + '"]');
        zellen.forEach(function(el) { el.style.display = sichtbar ? '' : 'none'; });
    });
});
</script>
{% endif %}
{% endblock %}
