{% trans_default_domain 'admin' %}

{% macro fieldset_head(title, hint) %}
    <legend class="text-sm font-semibold leading-6 text-gray-900 dark:text-gray-100">{{ title }}</legend>
    {% if hint %}<p class="mt-1 text-sm leading-6 text-gray-600 dark:text-gray-400">{{ hint }}</p>{% endif %}
{% endmacro %}

{% macro bool_check(id, model, title, description, disabled) %}
    <div class="relative flex items-start">
        <div class="flex h-6 items-center">
            <input id="{{ id }}" data-model="{{ model }}" type="checkbox" {{ disabled ? 'disabled' : '' }}
 class="{{ disabled ? 'opacity-50' : '' }}">
        </div>
        <div class="ml-3 text-sm leading-6">
            <label for="{{ id }}" class="font-medium text-gray-900 dark:text-gray-100">{{ title }}</label>
            {% if description %}<span class="text-gray-500 dark:text-gray-400"> {{ description }}</span>{% endif %}
        </div>
    </div>
{% endmacro %}

{# `checked` must be rendered server-side: the live component only syncs the box
   from the model once its JS has connected, so a preselected filter would look
   unchecked until then — and an unchecked box that filters is how a Rundmail
   ends up with an audience nobody vetted. #}
{% macro list_check(id, model, value, label, checked) %}
    <div class="relative flex gap-x-3">
        <div class="flex h-6 items-center">
            <input id="{{ id }}" data-model="{{ model }}" type="checkbox" value="{{ value }}"{{ checked|default(false) ? ' checked' : '' }}>
        </div>
        <div class="text-sm leading-6">
            <label for="{{ id }}" class="font-medium text-gray-900 dark:text-gray-100">{{ label }}</label>
        </div>
    </div>
{% endmacro %}

{% import _self as ui %}

<div {{ attributes }}>

    {# ── host-confidentiality gate ──
       A selected season (or the edition of a selected offer) still awaits this
       user's confidentiality signature. Block the whole tool — recipients and
       preview included — until every such declaration is signed, mirroring the
       participant-list gate but scoped to the actual selection. #}
    {% if unconsentedEditions is not empty %}

        <div class="mx-auto mt-6 max-w-2xl space-y-4">
            <div class="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 px-5 py-4 dark:border-amber-500/30 dark:bg-amber-500/10">
                <span class="grid size-9 flex-none place-items-center rounded-lg bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300">
                    <twig:ux:icon name="ph:lock-simple" class="size-5" />
                </span>
                <div class="min-w-0">
                    <b class="block text-sm font-bold text-amber-900 dark:text-amber-200">{{ 'hostConsent.gate.mailingTitle'|trans }}</b>
                    <span class="mt-0.5 block text-xs leading-5 text-amber-800 dark:text-amber-200/90">{{ 'hostConsent.gate.mailingText'|trans }}</span>
                </div>
            </div>

            {% for edition in unconsentedEditions %}
                <div class="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
                    <div class="px-5 py-4">
                        <h2 class="text-sm font-semibold tracking-tight text-gray-900 dark:text-gray-100">
                            <span class="text-gray-500 dark:text-gray-400">{{ edition.name }} —</span>
                            {{ edition.hostConsentForm.title|default('')|trim ?: 'hostConsent.gate.untitled'|trans }}
                        </h2>

                        <div class="mt-3 max-h-60 overflow-y-auto whitespace-pre-line rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-[13px] leading-relaxed text-gray-700 dark:border-gray-700 dark:bg-gray-800/60 dark:text-gray-300">{{ edition.hostConsentForm.text }}</div>

                        <button type="button"
                                data-action="live#action:prevent"
                                data-live-action-param="signConsent"
                                data-live-edition-param="{{ edition.id }}"
                                class="mt-4 flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900">
                            <twig:ux:icon name="ph:check" class="size-4" />
                            {{ 'hostConsent.gate.mailingSubmit'|trans }}
                        </button>

                        <p class="mt-3 text-center text-[11px] text-gray-400 dark:text-gray-500">{{ 'hostConsent.gate.foot'|trans }}</p>
                    </div>
                </div>
            {% endfor %}
        </div>

    {% else %}

    {% if not is_granted('ROLE_ADMIN') and offerOptions is empty %}

        <twig:Admin:Alert type="error"
                          class="shadow-sm border border-red-700/30"
                          message="Bitte rufen Sie die Rundmail-Funktion direkt über das Angebot auf."/>

    {% else %}

        {# ───────── Stepper ───────── #}
        {% set steps = [
            { n: 1, title: 'Verfassen', sub: 'Empfänger & Nachricht' },
            { n: 2, title: 'Vorschau & Prüfen', sub: 'So sieht die Mail aus' },
            { n: 3, title: 'Versendet', sub: 'Bestätigung' }
        ] %}
        <nav class="-mt-2 flex items-stretch border-b border-gray-200 dark:border-gray-800" aria-label="Fortschritt">
            {% for s in steps %}
                {% set isActive = step == s.n %}
                {% set isDone = step > s.n %}
                {% set canGoBack = isDone and step != 3 %}
                <div class="relative flex flex-1 items-center gap-3 px-2 py-3.5 -mb-px border-b-2 {{ isActive ? 'border-primary-600' : 'border-transparent' }} {{ canGoBack ? 'cursor-pointer' : '' }}"
                     {% if canGoBack %}role="button" tabindex="0" data-action="click->live#action:prevent" data-live-action-param="back"{% endif %}>
                    <span class="flex size-8 flex-none items-center justify-center rounded-full border text-sm font-bold transition-all {{ isActive
                        ? 'border-primary-600 bg-primary-600 text-white ring-4 ring-primary-100 dark:ring-primary-900/40'
                        : isDone
                            ? 'border-green-600 bg-green-600 text-white'
                            : 'border-gray-200 bg-gray-100 text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400' }}">
                        {% if isDone %}<twig:ux:icon name="ph:check-bold" class="size-4" />{% else %}{{ s.n }}{% endif %}
                    </span>
                    <span class="min-w-0">
                        <span class="block text-sm font-semibold {{ isActive ? 'text-primary-600' : isDone ? 'text-gray-800 dark:text-gray-200' : 'text-gray-500 dark:text-gray-400' }}">{{ s.title }}</span>
                        <span class="block truncate text-xs text-gray-400 dark:text-gray-500 max-sm:hidden">{{ s.sub }}</span>
                    </span>
                </div>
            {% endfor %}
        </nav>

        {# ───────── STEP 1: COMPOSE ───────── #}
        {% if step == 1 %}
            <div class="mt-6 grid grid-cols-1 gap-8 lg:grid-cols-12">
                <div class="lg:col-span-8">

                    {# Recipients #}
                    <section>
                        <div class="flex items-start gap-3 border-b border-gray-200 pb-4 dark:border-gray-800">
                            <span class="flex size-9 flex-none items-center justify-center rounded-lg bg-primary-50 text-primary-600 dark:bg-primary-900/30 dark:text-primary-300">
                                <twig:ux:icon name="ph:users" class="size-5" />
                            </span>
                            <div class="min-w-0">
                                <h2 class="text-base font-semibold text-gray-900 dark:text-gray-100">Empfänger</h2>
                                <p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">Wählen Sie eine Empfänger-Gruppe und grenzen Sie diese bei Bedarf ein.</p>
                            </div>
                        </div>

                        <div class="space-y-8 pt-6">

                            {% if is_granted('ROLE_ADMIN') %}
                                <fieldset>
                                    {{ ui.fieldset_head('Empfänger-Gruppe') }}
                                    <div class="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
                                        {% set groups = [
                                            { key: 'veranstaltende', label: 'Veranstaltende', count: countAllHosts, icon: 'ph:buildings' },
                                            { key: 'teilnehmende', label: 'Teilnehmende', count: countAllParticipants, icon: 'ph:users' }
                                        ] %}
                                        {% for g in groups %}
                                            {% set on = group == g.key %}
                                            <button type="button"
                                                    data-action="live#emit"
                                                    data-live-event-param="group"
                                                    data-live-group-param="{{ g.key }}"
                                                    class="flex items-center gap-3 rounded-lg border p-4 text-left transition-colors {{ on ? 'border-primary-600 bg-primary-50 dark:border-primary-500 dark:bg-primary-900/20' : 'border-gray-200 bg-white hover:border-gray-300 dark:border-gray-800 dark:bg-gray-900' }}">
                                                <span class="flex size-10 flex-none items-center justify-center rounded-lg {{ on ? 'bg-white text-primary-600 dark:bg-gray-900' : 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400' }}">
                                                    <twig:ux:icon name="{{ g.icon }}" class="size-5" />
                                                </span>
                                                <span class="min-w-0 flex-1">
                                                    <span class="block text-sm font-semibold text-gray-900 dark:text-gray-100">{{ g.label }}</span>
                                                    <span class="block text-xs {{ on ? 'font-medium text-primary-600 dark:text-primary-300' : 'text-gray-500 dark:text-gray-400' }}">{{ g.count }} E-Mails</span>
                                                </span>
                                                <span class="flex size-5 flex-none items-center justify-center rounded-full border-2 {{ on ? 'border-primary-600' : 'border-gray-300 dark:border-gray-600' }}">
                                                    <span class="size-2.5 rounded-full bg-primary-600 transition-transform {{ on ? 'scale-100' : 'scale-0' }}"></span>
                                                </span>
                                            </button>
                                        {% endfor %}
                                    </div>
                                </fieldset>
                            {% endif %}

                            {% if 'veranstaltende' == group %}
                                <fieldset>
                                    {{ ui.fieldset_head('Filter') }}
                                    <div class="mt-4 space-y-5">
                                        {{ ui.bool_check('opt-hostsnotdisabled', 'hostsNotDisabled', 'Nicht-deaktivierte Accounts:', 'Nur Accounts, die einen aktiven Account haben.', false) }}
                                        {{ ui.bool_check('opt-hostswithoffer', 'hostsWithOffer', 'Mit Angebot:', 'Veranstalter bietet oder hat in Vergangenheit ein Angebot angeboten.', edition is not null) }}
                                    </div>
                                </fieldset>
                            {% endif %}

                            {% if (('teilnehmende' == group and not selectedOffers) or hostsWithOffer) and edition is null %}
                                <fieldset>
                                    {{ ui.fieldset_head('Saisons', 'Nur mit Angeboten einer dieser Saisons.') }}
                                    <div class="mt-4 space-y-2">
                                        {% for editionOption in editionOptions %}
                                            {{ ui.list_check('edition-' ~ loop.index, 'selectedEditions[]', editionOption.id, editionOption.name, editionOption.id in selectedEditions) }}
                                        {% endfor %}
                                    </div>
                                </fieldset>
                            {% endif %}

                            {% if 'teilnehmende' == group and selectedOffers is not empty %}
                                <fieldset>
                                    {{ ui.fieldset_head('Angebote', 'Nur an Teilnehmende aus folgenden Angeboten.') }}
                                    <div class="mt-4 space-y-2">
                                        {% for offer in offerOptions %}
                                            {{ ui.list_check('offer-' ~ loop.index, 'selectedOffers[]', offer.id, offer.name, offer.id in selectedOffers) }}
                                        {% endfor %}
                                    </div>
                                </fieldset>
                            {% endif %}

                            {# Always shown for Teilnehmende, offer selected or not: the status is
                               what decides whether a family reads "Ihr Kind hat einen Platz" or the
                               waiting list does. Nothing checked means nobody, never everybody. #}
                            {% if 'teilnehmende' == group %}
                                <fieldset>
                                    {{ ui.fieldset_head('Anmeldestatus', 'Nur an Teilnehmende mit dem/den ausgewählten Status.') }}
                                    <div class="mt-3 flex flex-wrap items-center gap-2 text-xs">
                                        <button type="button" data-action="live#action:prevent" data-live-action-param="selectConfirmedOnly"
                                                class="rounded-full border border-gray-200 px-2.5 py-1 font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">Nur zugesagte</button>
                                        <button type="button" data-action="live#action:prevent" data-live-action-param="selectAllStatuses"
                                                class="rounded-full border border-gray-200 px-2.5 py-1 font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">Alle Status</button>
                                    </div>
                                    <div class="mt-4 space-y-2">
                                        {% for status in statusOptions %}
                                            {{ ui.list_check('status-' ~ loop.index, 'attendanceStatus[]', status, "mailing.attendanceStatus.#{status}"|trans, status in attendanceStatus) }}
                                        {% endfor %}
                                    </div>

                                    {% if attendanceStatus is empty %}
                                        <p class="mt-3 flex items-start gap-2 rounded-lg bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:bg-gray-800/60 dark:text-gray-300">
                                            <twig:ux:icon name="ph:info" class="mt-0.5 size-4 flex-none text-gray-400" />
                                            Ohne ausgewählten Status wird niemand angeschrieben.
                                        </p>
                                    {% elseif statusesWithoutSeat is not empty %}
                                        <p class="mt-3 flex items-start gap-2 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:bg-amber-500/10 dark:text-amber-200">
                                            <twig:ux:icon name="ph:warning" class="mt-0.5 size-4 flex-none" />
                                            <span>Diese Rundmail geht auch an Anmeldungen <b class="font-semibold">ohne Platz</b>:
                                                {% for status in statusesWithoutSeat %}{{ ("mailing.attendanceStatus.#{status}")|trans }}{{ not loop.last ? ', ' }}{% endfor %}.</span>
                                        </p>
                                    {% endif %}
                                </fieldset>
                            {% endif %}

                            {% if 'teilnehmende' == group %}
                                <fieldset>
                                    {{ ui.fieldset_head('Filter', 'Die Teilnehmende, die eine E-Mail bekommen, weiter einschränken.') }}
                                    <div class="mt-4 space-y-5">
                                        {{ ui.bool_check('opt-onlyparticipantsunacknowledged', 'onlyParticipantsUnacknowledged', 'Unbestätigte Angebote:', 'Teilnehmende sind zu Angeboten angemeldet, die noch nicht bezahlt oder alternativ bestätigt wurden.', false) }}
                                        {% if onlyParticipantsUnacknowledged %}
                                            {{ ui.bool_check('opt-onlyparticipantsunpaid', 'onlyParticipantsUnpaid', 'Zahlung ausstehend:', 'Nur Anmeldungen, bei denen auch wirklich eine Zahlung ausstehend ist.', false) }}
                                            {% if canCreatePaymentLinks %}
                                                {{ ui.bool_check('opt-addpaymentlink', 'addPaymentLink', 'Zahlungsaufforderung generieren:', 'Es wird eine Zahlungsaufforderung erstellt und ein Link zum Bezahlen der Rechnung eingefügt.', false) }}
                                            {% endif %}
                                        {% endif %}
                                    </div>
                                </fieldset>
                            {% endif %}

                            {% if selectedHosts is not empty %}
                                <fieldset>
                                    {{ ui.fieldset_head('Veranstalter-Profile', 'Nur an Ansprechpartner von folgenden Veranstaltern versenden.') }}
                                    <div class="mt-4 space-y-2">
                                        {% for host in hostOptions %}
                                            {{ ui.list_check('host-' ~ loop.index, 'selectedHosts[]', host.id, host.name, host.id in selectedHosts) }}
                                        {% endfor %}
                                    </div>
                                </fieldset>
                            {% endif %}

                        </div>
                    </section>

                    {# Recipient addresses #}
                    <section class="mt-10">
                        <div class="flex items-start gap-3 border-b border-gray-200 pb-4 dark:border-gray-800">
                            <span class="flex size-9 flex-none items-center justify-center rounded-lg bg-primary-50 text-primary-600 dark:bg-primary-900/30 dark:text-primary-300">
                                <twig:ux:icon name="ph:envelope" class="size-5" />
                            </span>
                            <div class="min-w-0 flex-1">
                                <h2 class="text-base font-semibold text-gray-900 dark:text-gray-100">{{ 'mailing.recipients.0'|trans }}</h2>
                                <p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">{{ 'mailing.recipients.1'|trans }}</p>
                            </div>
                            <span class="ml-auto flex-none self-center rounded-full bg-primary-50 px-2.5 py-0.5 text-xs font-bold text-primary-600 dark:bg-primary-900/30 dark:text-primary-300">{{ recipients|length }} E-Mails</span>
                        </div>
                        <div class="flex flex-wrap gap-1.5 pt-6">
                            {% for email, users in recipients %}
                                <span class="inline-flex max-w-full items-center rounded-full border border-gray-200 bg-white py-1 pl-1 pr-1.5 dark:border-gray-800 dark:bg-gray-900">
                                    <span class="isolate inline-flex flex-none -space-x-1 overflow-hidden">
                                        {% for user in users %}
                                            <span class="relative z-30 inline-flex size-5 flex-none items-center justify-center rounded-full bg-green-50 text-[9px] font-bold text-green-700 ring-2 ring-white dark:bg-green-900/30 dark:text-green-300 dark:ring-gray-900" title="{{ user.name }}">{{ user.firstname|first|upper ~ user.lastname|first|upper }}</span>
                                        {% endfor %}
                                    </span>
                                    <span class="ml-1.5 truncate text-xs text-gray-700 dark:text-gray-300">{{ email }}</span>
                                    <button type="button" title="Empfänger entfernen"
                                            class="ml-1 flex size-4 flex-none items-center justify-center rounded-full text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"
                                            data-action="live#action:prevent" data-live-action-param="remove" data-live-email-param="{{ email }}">
                                        <twig:ux:icon name="ph:x" class="size-3" />
                                    </button>
                                </span>
                            {% else %}
                                <p class="text-sm text-gray-500 dark:text-gray-400">Keine Empfänger:innen mit der aktuellen Auswahl.</p>
                            {% endfor %}
                        </div>
                    </section>

                    {# Message #}
                    <section class="mt-10">
                        <div class="flex items-start gap-3 border-b border-gray-200 pb-4 dark:border-gray-800">
                            <span class="flex size-9 flex-none items-center justify-center rounded-lg bg-primary-50 text-primary-600 dark:bg-primary-900/30 dark:text-primary-300">
                                <twig:ux:icon name="ph:pencil-simple" class="size-5" />
                            </span>
                            <div class="min-w-0">
                                <h2 class="text-base font-semibold text-gray-900 dark:text-gray-100">Nachricht verfassen</h2>
                                <p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">Betreff und Text der E-Mail. Markdown und Tokens werden unterstützt.</p>
                            </div>
                        </div>

                        <form class="space-y-5 pt-6">
                            <div>
                                <label for="emailSubject" class="mb-1.5 block text-sm font-medium leading-6 text-gray-900 dark:text-gray-100">E-Mail-Betreff</label>
                                <input type="text" data-model="emailSubject" id="emailSubject"
                                       placeholder="z. B. Wichtige Informationen zum Ferienpass"
                                       class="block w-full rounded-md border-gray-300 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100">
                            </div>

                            <div>
                                <label for="emailText" class="mb-1.5 block text-sm font-medium leading-6 text-gray-900 dark:text-gray-100">E-Mail-Text</label>
                                {% set tokensDialogId = 'lexical-tokens-mailing' %}
                                <div data-controller="ferienpass--admin-lexical">
                                    <div data-live-ignore class="lexical-container flex flex-col rounded-md border border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-800">
                                        <div data-ferienpass--admin-lexical-target="toolbar" class="lexical-toolbar flex flex-wrap items-center gap-1 rounded-t-md border-b border-gray-200 bg-gray-50 p-1 dark:border-gray-700 dark:bg-gray-900">
                                            {% set buttons = [
                                                { action: 'bold', icon: 'ph:text-b', label: 'Fett' },
                                                { action: 'italic', icon: 'ph:text-italic', label: 'Kursiv' },
                                                { type: 'separator' },
                                                { action: 'ul', icon: 'ph:list-bullets', label: 'Aufzählung' },
                                                { action: 'ol', icon: 'ph:list-numbers', label: 'Nummerierte Liste' }
                                            ] %}
                                            {% for btn in buttons %}
                                                {% if btn.type|default == 'separator' %}
                                                    <div class="mx-1 h-6 w-px bg-gray-300 dark:bg-gray-600"></div>
                                                {% else %}
                                                    <button type="button"
                                                            class="flex items-center justify-center rounded p-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-300 dark:hover:bg-gray-700 [&>svg]:size-4"
                                                            title="{{ btn.label }}"
                                                            data-action="click->ferienpass--admin-lexical#dispatchAction"
                                                            data-ferienpass--admin-lexical-action-param="{{ btn.action }}">
                                                        {{ ux_icon(btn.icon) }}
                                                    </button>
                                                {% endif %}
                                            {% endfor %}
                                        </div>
                                        <div data-ferienpass--admin-lexical-target="editor" contenteditable="true" class="lexical-editor prose prose-sm min-h-[200px] max-w-none px-4 py-3 text-gray-900 outline-none dark:prose-invert dark:text-gray-100/90"></div>
                                        <div class="lexical-footer flex items-center justify-end gap-1 rounded-b-md border-t border-gray-200 bg-gray-50 p-1 dark:border-gray-700 dark:bg-gray-900">
                                            <twig:Admin:Button variant="ghost" size="sm" command="show-modal" :commandfor="tokensDialogId">
                                                <span class="flex items-center gap-1.5">
                                                    <twig:ux:icon name="ph:brackets-curly" class="size-4" />
                                                    <span>Tokens</span>
                                                </span>
                                            </twig:Admin:Button>
                                        </div>
                                    </div>
                                    <textarea id="emailText" data-model="emailText" data-ferienpass--admin-lexical-target="input" data-live-ignore class="hidden"></textarea>
                                </div>
                                <p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">Markdown wird unterstützt.</p>
                            </div>

                            <div>
                                <label class="mb-1.5 block text-sm font-medium leading-6 text-gray-900 dark:text-gray-100">E-Mail-Anhang</label>
                                {% if emailAttachment %}
                                    <div class="flex items-center gap-3 rounded-md border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
                                        <span class="flex size-9 flex-none items-center justify-center rounded-lg bg-primary-50 text-primary-600 dark:bg-primary-900/30 dark:text-primary-300">
                                            <twig:ux:icon name="ph:file-pdf" class="size-5" />
                                        </span>
                                        <div class="min-w-0 flex-1">
                                            <p class="truncate text-sm font-medium text-gray-900 dark:text-gray-100">{{ emailAttachment|split('/')|last }}</p>
                                            <p class="text-xs text-gray-500 dark:text-gray-400">PDF angehängt</p>
                                        </div>
                                        <button type="button" title="Anhang entfernen"
                                                class="flex size-8 flex-none items-center justify-center rounded-md text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"
                                                data-action="live#action:prevent" data-live-action-param="removeAttachment">
                                            <twig:ux:icon name="ph:x" class="size-4" />
                                        </button>
                                    </div>
                                {% else %}
                                    <input type="file" name="emailAttachment" accept="application/pdf"
                                           data-action="change->live#action" data-live-action-param="files|uploadAttachment"
                                           class="block w-full text-sm text-gray-500 file:mr-3 file:rounded-md file:border-0 file:bg-primary-50 file:px-3 file:py-1.5 file:text-sm file:font-semibold file:text-primary-700 hover:file:bg-primary-100 dark:text-gray-400 dark:file:bg-primary-900/30 dark:file:text-primary-300">
                                    {% if attachmentError %}
                                        <p class="mt-1.5 text-xs text-red-600 dark:text-red-400">{{ attachmentError }}</p>
                                    {% else %}
                                        <p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">Als beste Praxis gilt: maximal eine Datei, nur PDF, nicht größer als 1&nbsp;MB.</p>
                                    {% endif %}
                                {% endif %}
                            </div>

                            {% if currentUserEmail %}
                                <div>
                                    <label for="selfCopyMode" class="mb-1.5 block text-sm font-medium leading-6 text-gray-900 dark:text-gray-100">Kopie an mich</label>
                                    <select id="selfCopyMode" data-model="selfCopyMode"
                                            class="block w-full rounded-md border-gray-300 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 sm:max-w-sm">
                                        <option value="" {{ selfCopyMode == '' ? 'selected' : '' }}>Keine</option>
                                        <option value="copy" {{ selfCopyMode == 'copy' ? 'selected' : '' }}>Kopie an mich senden</option>
                                        <option value="bcc" {{ selfCopyMode == 'bcc' ? 'selected' : '' }}>Mich als BCC hinzufügen</option>
                                    </select>
                                    <p class="mt-1.5 text-xs leading-5 text-gray-500 dark:text-gray-400">
                                        Zugestellt an Ihre persönliche Adresse <span class="font-medium text-gray-700 dark:text-gray-300">{{ currentUserEmail }}</span>.
                                        <b class="font-semibold">Kopie an mich senden</b> verschickt eine einzelne, nicht personalisierte Beispiel-Mail;
                                        <b class="font-semibold">Mich als BCC hinzufügen</b> setzt Sie bei jeder versendeten E-Mail in Blindkopie – für Empfänger:innen nicht sichtbar.
                                    </p>
                                </div>
                            {% endif %}

                            <div class="flex items-center justify-end border-t border-gray-200 pt-5 dark:border-gray-800">
                                <twig:Admin:Button
                                        variant="primary" size="lg"
                                        :disabled="recipients|length == 0 or emailSubject|trim is empty or emailText|trim is empty"
                                        data-action="live#action:prevent" data-live-action-param="toReview">
                                    Vorschau ansehen
                                    <twig:ux:icon name="ph:arrow-right" class="ml-2 size-4" />
                                </twig:Admin:Button>
                            </div>
                        </form>
                    </section>
                </div>

                {# Sidebar #}
                <aside class="flex flex-col gap-8 lg:col-span-4">

                    <div>
                        <div class="flex items-center gap-2 border-b border-gray-200 pb-2.5 dark:border-gray-800">
                            <twig:ux:icon name="ph:clock-counter-clockwise" class="size-4 text-gray-500 dark:text-gray-400" />
                            <b class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ 'mailing.recent'|trans }}</b>
                        </div>
                        <div class="py-2">
                            {% for mailing in recentMailings %}
                                <a href="{{ path('admin_tools_dispatch', { uuid: mailing.logEntry.group.uuid.toBase58 }) }}" class="group flex items-start gap-2.5 rounded-lg p-2 hover:bg-gray-50 dark:hover:bg-gray-800/60">
                                    <span class="mt-1.5 size-1.5 flex-none rounded-full bg-green-500"></span>
                                    <span class="min-w-0">
                                        <span class="block truncate text-xs font-medium text-gray-800 group-hover:text-primary-600 dark:text-gray-200">{{ mailing.subject ?? 'Rundmail' }}</span>
                                        <span class="text-[11px] text-gray-400 dark:text-gray-500">{{ mailing.createdAt|time_diff }}</span>
                                    </span>
                                </a>
                            {% else %}
                                <p class="px-2 py-2 text-xs text-gray-500 dark:text-gray-400">Keine Rundmails gefunden.</p>
                            {% endfor %}
                        </div>
                    </div>
                </aside>
            </div>

            {# Tokens dialog (opened from the editor footer) #}
            <el-dialog>
                <dialog id="{{ tokensDialogId }}" class="fixed inset-0 size-auto max-h-none max-w-none overflow-y-auto bg-transparent backdrop:bg-transparent">
                    <el-dialog-backdrop class="fixed inset-0 bg-gray-500/75 transition-opacity data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in"></el-dialog-backdrop>
                    <div tabindex="0" class="flex min-h-full items-center justify-center p-4 text-center focus:outline-none sm:p-0">
                        <el-dialog-panel class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all dark:bg-gray-900 sm:my-8 sm:w-full sm:max-w-2xl sm:p-6">
                            <div class="absolute right-0 top-0 z-20 hidden pr-4 pt-4 sm:block">
                                <button type="button" command="close" commandfor="{{ tokensDialogId }}" aria-label="Schließen"
                                        class="cursor-pointer rounded-md p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 focus:outline-none dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300">
                                    <twig:ux:icon name="ph:x" class="size-5" />
                                </button>
                            </div>
                            <h3 class="text-lg font-bold text-gray-900 dark:text-gray-50">Benachrichtigungstokens</h3>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Sie können folgende Tokens verwenden, die vor dem Versenden mit dem richtigen Inhalt ersetzt werden.</p>
                            <div class="mt-6 border-t border-gray-100 dark:border-gray-700">
                                <dl class="divide-y divide-gray-100 dark:divide-gray-800">
                                    <div class="px-4 py-2 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
                                        <dt class="text-sm font-semibold leading-6 text-gray-900 dark:text-gray-100">Token</dt>
                                        <dd class="mt-1 text-sm font-semibold leading-6 text-gray-700 dark:text-gray-200 sm:col-span-2 sm:mt-0">Beispiel</dd>
                                    </div>
                                    {% for tokenName, tokenValue in availableTokens %}
                                        <div class="px-4 py-2 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
                                            <dt class="font-mono text-xs font-medium leading-6 text-gray-900 dark:text-gray-100">{{ '{{ ' ~ tokenName ~ ' }}' }}</dt>
                                            <dd class="mt-1 break-all text-sm leading-6 text-gray-700 dark:text-gray-200 sm:col-span-2 sm:mt-0">{{ tokenValue }}</dd>
                                        </div>
                                    {% endfor %}
                                </dl>
                            </div>
                        </el-dialog-panel>
                    </div>
                </dialog>
            </el-dialog>
        {% endif %}

        {# ───────── STEP 2: REVIEW ───────── #}
        {% if step == 2 %}
            <div class="mx-auto mt-6 max-w-3xl">

                <div class="grid grid-cols-1 divide-y divide-gray-100 border-y border-gray-200 dark:divide-gray-800 dark:border-gray-800 sm:grid-cols-3 sm:divide-x sm:divide-y-0">
                    <div class="px-0 py-4 sm:pr-5">
                        <div class="mb-1.5 text-xs font-bold uppercase tracking-wider text-gray-400">Empfänger</div>
                        <div class="flex items-center gap-2 text-base font-bold text-gray-900 dark:text-gray-100">
                            <twig:ux:icon name="ph:users" class="size-4 text-primary-600" />
                            {{ recipients|length }} <span class="text-sm font-medium text-gray-500 dark:text-gray-400">{{ group == 'veranstaltende' ? 'Veranstaltende' : 'Teilnehmende' }}</span>
                        </div>
                    </div>
                    <div class="px-0 py-4 sm:px-5">
                        <div class="mb-1.5 text-xs font-bold uppercase tracking-wider text-gray-400">Anhang</div>
                        <div class="flex items-center gap-2 text-base font-bold text-gray-900 dark:text-gray-100">
                            {% if emailAttachment %}
                                <twig:ux:icon name="ph:paperclip" class="size-4 text-primary-600" /> <span class="text-sm font-medium text-gray-500 dark:text-gray-400">1 Datei</span>
                            {% else %}
                                <span class="text-sm font-medium text-gray-400">Kein Anhang</span>
                            {% endif %}
                        </div>
                    </div>
                    <div class="px-0 py-4 sm:pl-5">
                        {% if group == 'teilnehmende' %}
                            {# The audience the sender is about to commit to, spelled out: a count
                               alone never showed whether the waiting list is in it. #}
                            <div class="mb-1.5 text-xs font-bold uppercase tracking-wider text-gray-400">Anmeldestatus</div>
                            <div class="flex items-start gap-2 text-gray-900 dark:text-gray-100">
                                <twig:ux:icon name="ph:funnel" class="mt-0.5 size-4 flex-none text-primary-600" />
                                <span class="text-sm font-medium text-gray-500 dark:text-gray-400">
                                    {%- for status in attendanceStatus -%}
                                        {{ ("mailing.attendanceStatus.#{status}")|trans }}{{ not loop.last ? ', ' }}
                                    {%- else -%}
                                        keiner
                                    {%- endfor -%}
                                </span>
                            </div>
                        {% else %}
                            <div class="mb-1.5 text-xs font-bold uppercase tracking-wider text-gray-400">Saisons</div>
                            <div class="flex items-center gap-2 text-base font-bold text-gray-900 dark:text-gray-100">
                                <twig:ux:icon name="ph:calendar" class="size-4 text-primary-600" />
                                <span class="text-sm font-medium text-gray-500 dark:text-gray-400">{{ selectedEditions|length }} {{ selectedEditions|length == 1 ? 'Saison' : 'Saisons' }}</span>
                            </div>
                        {% endif %}
                    </div>
                </div>

                {% if group == 'teilnehmende' and statusesWithoutSeat is not empty %}
                    <div class="mt-6 flex items-start gap-2 rounded-lg bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:bg-amber-500/10 dark:text-amber-200">
                        <twig:ux:icon name="ph:warning" class="mt-0.5 size-4 flex-none" />
                        <span>Diese Rundmail geht auch an Anmeldungen <b class="font-semibold">ohne Platz</b>
                            ({% for status in statusesWithoutSeat %}{{ ("mailing.attendanceStatus.#{status}")|trans }}{{ not loop.last ? ', ' }}{% endfor %}).
                            Zum Ändern zurück zu Schritt&nbsp;1.</span>
                    </div>
                {% endif %}

                {# Email preview — shared shell with the notification previews #}
                {% set exampleEmail = availableTokens.recipientEmail|default('empfaenger@beispiel.de') %}
                <div class="mt-6">
                    <twig:Admin:MailPreview
                        subject="{{ subjectPreview ?: '(Kein Betreff)' }}"
                        fromAddress="{{ fromAddress ?? '—' }}"
                        replyTo="{{ replyToAddress }}"
                        to="{{ exampleEmail }}"
                        attachment="{{ emailAttachment ? emailAttachment|split('/')|last }}"
                        label="E-Mail-Vorschau"
                    >
                        {% if preview is same as(false) %}
                            <div class="px-6 py-6">
                                <twig:Admin:Alert type="error" message="Es gibt einen Fehler mit dem E-Mail-Text. Die E-Mail kann so nicht versendet werden." />
                            </div>
                        {% else %}
                            {# Render the real email template (incl. its CSS) isolated in a shadow root #}
                            <div {{ stimulus_controller('ferienpass/admin-shadow-root') }} class="bg-white">
                                <template shadowrootmode="open">
                                    {{ include('@email/mailing.html.twig', { content: preview, baseUrl: context.baseUrl }, with_context = false) }}
                                </template>
                            </div>
                        {% endif %}
                    </twig:Admin:MailPreview>
                </div>

                <div class="mt-6 flex flex-wrap items-center justify-between gap-4">
                    <div class="flex flex-col gap-1.5 text-xs text-gray-500 dark:text-gray-400">
                        <span class="inline-flex items-center gap-2">
                            <twig:ux:icon name="ph:warning" class="size-4 flex-none text-gray-400" />
                            Der Versand kann nicht rückgängig gemacht werden.
                        </span>
                        {% if currentUserEmail and selfCopyMode in ['copy', 'bcc'] %}
                            <span class="inline-flex items-center gap-2">
                                <twig:ux:icon name="ph:copy" class="size-4 flex-none text-gray-400" />
                                {% if selfCopyMode == 'copy' %}
                                    Eine nicht personalisierte Kopie geht an <span class="font-medium text-gray-700 dark:text-gray-300">{{ currentUserEmail }}</span>.
                                {% else %}
                                    Sie werden bei jeder E-Mail in Blindkopie gesetzt (<span class="font-medium text-gray-700 dark:text-gray-300">{{ currentUserEmail }}</span>).
                                {% endif %}
                            </span>
                        {% endif %}
                    </div>
                    <div class="ml-auto flex gap-3">
                        <twig:Admin:Button variant="secondary" size="lg" data-action="live#action:prevent" data-live-action-param="back">
                            <twig:ux:icon name="ph:arrow-left" class="mr-2 size-4" />
                            Zurück bearbeiten
                        </twig:Admin:Button>
                        <twig:Admin:Button variant="primary" size="lg" data-action="live#action:prevent" data-live-action-param="submit">
                            <twig:ux:icon name="ph:paper-plane-tilt" class="mr-2 size-4" />
                            An {{ recipients|length }} Empfänger senden
                        </twig:Admin:Button>
                    </div>
                </div>
            </div>
        {% endif %}

        {# ───────── STEP 3: SENT — embeds the dispatch tracker (with polling) ───────── #}
        {% if step == 3 %}
            <div class="mt-8">
                <div class="mb-6">
                    <h2 class="text-base font-semibold text-gray-900 dark:text-gray-100">Versand nachverfolgen</h2>
                    <p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">Ihre Rundmail wurde in die Warteschlange gestellt. Sie können dem Versand nun zuschauen — die Seite aktualisiert sich automatisch.</p>
                </div>

                {% if dispatchLog %}
                    <twig:Admin:SentMessages :log="dispatchLog" />
                {% else %}
                    <p class="text-sm text-gray-500 dark:text-gray-400">Der Versand wird gestartet …</p>
                {% endif %}
            </div>
        {% endif %}

    {% endif %}

    {% if showConfirm %}
        <twig:Turbo:Stream:Update target="#modal">
            <twig:Admin:MailingModal numberOfEmails="{{ recipients|length }}" :emailText="emailText" />
        </twig:Turbo:Stream:Update>
    {% endif %}

    {% endif %}{# unconsentedEditions gate #}

</div>
