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

{% block content %}
<div class="page-header">
    <h1>{{ recherche.name }}</h1>
    <div class="btn-group">
        <a href="/recherche/gespeichert" role="button" class="btn-sm outline">← Alle Recherchen</a>
        <a href="/recherche" role="button" class="btn-sm outline">Neue Recherche</a>
        {% if 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>
        {% endif %}
        <form method="post" action="/recherche/gespeichert/{{ recherche.id }}/loeschen" style="display: inline;"
              onsubmit="return confirm('Recherche wirklich löschen?');">
            <button type="submit" class="btn-sm outline" style="color: var(--kw-danger); border-color: var(--kw-danger);">Löschen</button>
        </form>
    </div>
</div>

<p style="font-size: 0.85rem; color: var(--kw-text-muted); margin-bottom: 1rem;">
    Gespeichert am {{ recherche.erstellt_am.strftime('%d.%m.%Y %H:%M') if recherche.erstellt_am else '-' }}
    {% if recherche.erstellt_von %} von {{ recherche.erstellt_von }}{% endif %}
    &mdash; {{ gesamt }} Kontakte
</p>

<div class="card" id="ergebnisse">
    <div class="card-header" style="flex-wrap: wrap; gap: 0.5rem;">
        <h3>Kontakte ({{ gesamt }})</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) %}
    <table class="data-table">
        <thead>
            <tr>
                <th style="width: 2rem;"></th>
                <th style="width: 2rem;"></th>
                <th>Name</th>
                <th>Rolle / Ort</th>
                <th>E-Mail</th>
                <th>Telefon</th>
            </tr>
        </thead>
        <tbody>
            {% 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 style="font-size: 0.85rem;">{{ gruppe.org.plz or '' }} {{ gruppe.org.ort or '' }}</td>
                <td 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 style="font-size: 0.85rem;">{{ gruppe.org.telefon 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 style="font-size: 0.85rem;">{{ ma.rolle or '' }}</td>
                <td 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 style="font-size: 0.85rem;">{{ ma.kontakt.telefon or ma.kontakt.mobil or ma.kontakt.telefon_direkt or '-' }}</td>
            </tr>
            {% endfor %}
            {% endfor %}

            {% 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 style="font-size: 0.85rem;">{{ k.plz or '' }} {{ k.ort or '' }}</td>
                <td style="font-size: 0.85rem;">
                    {% if k.email1 %}<a href="mailto:{{ k.email1 }}" onclick="event.stopPropagation()">{{ k.email1 }}</a>{% else %}-{% endif %}
                </td>
                <td style="font-size: 0.85rem;">{{ k.telefon or k.mobil or k.telefon_direkt 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>
    </div>
    {% else %}
    <div class="empty-state">
        <div class="empty-state-icon">&#x1F50D;</div>
        <p>Keine Kontakte gefunden. Möglicherweise wurden einige zwischenzeitlich gelöscht.</p>
    </div>
    {% endif %}
</div>

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

<!-- Kampagne-Dialog -->
{% if 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>
            <select name="kampagne_id" id="kampagne-select" style="margin: 0;"
                    onchange="document.getElementById('neuer-titel').disabled = this.value !== 'neu'; if(this.value !== 'neu') document.getElementById('neuer-titel').value = '';">
                <option value="">-- Auswählen --</option>
                {% for k in kampagnen %}
                <option value="{{ k.id }}">{{ k.titel }} ({{ k.kontakte|length }} Kontakte)</option>
                {% endfor %}
                <option value="neu">+ Neue Kampagne anlegen</option>
            </select>
        </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>

<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';
}

function selectAll(checked) {
    document.querySelectorAll('.kontakt-cb').forEach(function(cb) { cb.checked = checked; });
    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();
}

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));
}

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;
    });
    var hasMa = document.querySelectorAll('.ma-of-' + orgId).length > 0;
    if (hasMa) setOrgExpanded(orgId, checked);
    updateCounter();
}

function onMaCheckboxChange(orgId) {
    var maCbs = document.querySelectorAll('.ma-cb[data-parent-org="' + orgId + '"]');
    var anyChecked = Array.from(maCbs).some(function(cb) { return cb.checked; });
    if (!anyChecked) setOrgExpanded(orgId, false);
    if (anyChecked && !isOrgExpanded(orgId)) setOrgExpanded(orgId, true);
    updateCounter();
}

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

    if (isKampagne) {
        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 {
        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();
    }
}

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();
}

document.addEventListener('DOMContentLoaded', function() {
    updateCounter();
});
</script>
{% endif %}
{% endblock %}
