<div>
    @if($open)

        <x-wip-timer />

        <div class="border rounded-3 bg-light p-3 mt-4 mb-4">

            {{-- ── Header ─────────────────────────────────────────────────── --}}
            <div class="d-flex align-items-center justify-content-between mb-3">
                <h6 class="mb-0 fw-semibold">
                    @if($freeTextMode)
                        @if($channelFilter === 'email')
                            <i class="mdi mdi-email-edit-outline me-1"></i>Free text email
                        @elseif($channelFilter === 'sms')
                            <i class="mdi mdi-message-draw me-1"></i>Free text SMS
                        @else
                            <i class="mdi mdi-pencil me-1"></i>Free text message
                        @endif
                    @elseif($currentTemplate)
                        <i class="{{ $currentTemplate->channel->icon() }} me-1"></i>
                        {{ $currentTemplate->name }}
                    @elseif($channelFilter === 'email')
                        <i class="mdi mdi-email-outline me-1"></i>New Email
                    @elseif($channelFilter === 'sms')
                        <i class="mdi mdi-message-text-outline me-1"></i>New SMS
                    @else
                        <i class="mdi mdi-send me-1"></i>New Message
                    @endif
                </h6>
                <div class="d-flex align-items-center gap-3">
                    {{-- Mode toggle (only when a channel is fixed) --}}
                    @if($channelFilter)
                        @if($freeTextMode)
                            <button type="button" class="btn btn-link btn-sm p-0 text-muted text-decoration-none"
                                    wire:click.prevent="switchToTemplate">
                                <i class="mdi mdi-file-document-outline me-1"></i>Use template
                            </button>
                        @else
                            <button type="button" class="btn btn-link btn-sm p-0 text-muted text-decoration-none"
                                    wire:click.prevent="switchToFreeText">
                                <i class="mdi mdi-pencil me-1"></i>Free text
                            </button>
                        @endif
                    @endif
                    <button type="button" class="btn-close" wire:click.prevent="close" aria-label="Close"></button>
                </div>
            </div>

            {{-- ── Alerts ──────────────────────────────────────────────────── --}}
            @if($error)
                <div class="alert alert-danger py-2 px-3 small mb-3">{{ $error }}</div>
            @endif
            @if($success)
                <div class="alert alert-success py-2 px-3 small mb-3">{{ $success }}</div>
            @endif

            <form wire:submit.prevent="send">

                @if($freeTextMode)
                    {{-- ── Free text mode ──────────────────────────────────── --}}
                    <div class="row g-3 mb-3">
                        <div class="col-sm-6">
                            <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Send from</label>
                            <select class="form-select form-select-sm" wire:model.live="senderId">
                                <option value="">— default sender —</option>
                                @foreach($senders as $s)
                                    <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                @endforeach
                            </select>
                        </div>

                        @if($channelFilter === 'email')
                            <div class="col-sm-6">
                                <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Subject</label>
                                <input type="text" class="form-control form-control-sm"
                                       placeholder="Email subject…"
                                       wire:model.live="freeSubject">
                            </div>
                        @endif
                    </div>

                    <div class="mb-3">
                        <div class="d-flex align-items-center justify-content-between mb-1">
                            <label class="form-label small fw-semibold text-muted text-uppercase mb-0">Message</label>
                            @if($smsLength !== null)
                                <small class="text-muted">
                                    {{ $smsLength }} chars &middot; {{ $smsSegments }} segment{{ $smsSegments === 1 ? '' : 's' }}
                                    @if($smsSegments > 1)
                                        <span class="text-warning fw-semibold">(multi-part)</span>
                                    @endif
                                </small>
                            @endif
                        </div>
                        <textarea class="form-control form-control-sm"
                                  rows="7"
                                  placeholder="{{ $channelFilter === 'sms' ? 'Type your SMS…' : 'Type your message…' }}"
                                  wire:model.live="freeBodyText"></textarea>
                    </div>

                    @php
                        $freeReady = trim($freeBodyText) && ($channelFilter !== 'email' || trim($freeSubject));
                    @endphp
                    <div class="d-flex justify-content-end gap-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                                wire:click.prevent="close">Cancel</button>
                        <button type="submit" class="btn btn-sm btn-primary" @disabled(!$freeReady)>
                            <i class="mdi mdi-send me-1"></i>Send
                        </button>
                    </div>

                @else
                    {{-- ── Template mode ───────────────────────────────────── --}}

                    <div class="row g-3 mb-3">
                        <div class="{{ $currentTemplate ? 'col-sm-6' : 'col-12' }}">
                            <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Template</label>
                            <select class="form-select form-select-sm"
                                    wire:change="selectTemplate($event.target.value)">
                                <option value="">— choose a template —</option>
                                @php $byChannel = $templates->groupBy(fn($t) => $t->channel?->value); @endphp
                                @foreach($byChannel as $channelValue => $group)
                                    <optgroup label="{{ strtoupper($channelValue) }}">
                                        @foreach($group as $tpl)
                                            <option value="{{ $tpl->id }}"
                                                    @selected($tpl->id === $templateId)>
                                                {{ $tpl->name }}
                                                @if($tpl->category) — {{ $tpl->category->name }} @endif
                                            </option>
                                        @endforeach
                                    </optgroup>
                                @endforeach
                            </select>
                        </div>

                        @if($currentTemplate)
                            <div class="col-sm-6">
                                <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Send from</label>
                                <select class="form-select form-select-sm" wire:model.live="senderId">
                                    <option value="">— default sender —</option>
                                    @foreach($senders as $s)
                                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif
                    </div>

                    @if($currentTemplate && $recipientType === 'institution')
                        {{-- Institution + contact picker (recipient_type = institution) --}}
                        <div class="row g-3 mb-3">
                            <div class="col-sm-6">
                                <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Institution</label>
                                <select class="form-select form-select-sm" wire:model.live="institutionId">
                                    <option value="">— choose institution —</option>
                                    @foreach($claimInstitutions as $inst)
                                        <option value="{{ $inst->id }}">{{ $inst->display_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-sm-6">
                                <label class="form-label small fw-semibold text-muted text-uppercase mb-1">Contact</label>
                                <select class="form-select form-select-sm" wire:model.live="institutionContactId"
                                        @disabled(!$institutionId)>
                                    <option value="">— choose contact —</option>
                                    @foreach($institutionContacts as $contact)
                                        <option value="{{ $contact->id }}">
                                            {{ $contact->name }} ({{ $contact->email }}) @if($contact->job_title) — {{ $contact->job_title }}@endif
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        @if($claimInstitutions->isEmpty())
                            <div class="alert alert-warning py-2 px-3 small mb-3">
                                <i class="mdi mdi-alert-outline me-1"></i>No institutions are linked to this claim.
                            </div>
                        @elseif($institutionId && $institutionContacts->isEmpty())
                            <div class="alert alert-warning py-2 px-3 small mb-3">
                                <i class="mdi mdi-alert-outline me-1"></i>This institution has no contacts on file.
                            </div>
                        @endif
                    @endif

                    @if($currentTemplate)
                        <div class="mb-3">
                            <div class="d-flex align-items-center justify-content-between mb-1">
                                @if($reviewMode)
                                    <label class="form-label small fw-semibold text-muted text-uppercase mb-0">
                                        <i class="mdi mdi-pencil me-1"></i>Review &amp; edit
                                    </label>
                                    <button type="button" class="btn btn-link btn-sm p-0 text-muted text-decoration-none small"
                                            wire:click.prevent="exitReviewMode">
                                        <i class="mdi mdi-eye-outline me-1"></i>Back to preview
                                    </button>
                                @else
                                    <label class="form-label small fw-semibold text-muted text-uppercase mb-0">Preview</label>
                                    <button type="button" class="btn btn-link btn-sm p-0 text-muted text-decoration-none small"
                                            wire:click.prevent="enterReviewMode">
                                        <i class="mdi mdi-pencil me-1"></i>Edit before sending
                                    </button>
                                @endif
                                @if($smsLength !== null)
                                    <small class="text-muted">
                                        {{ $smsLength }} chars &middot; {{ $smsSegments }} segment{{ $smsSegments === 1 ? '' : 's' }}
                                        @if($smsSegments > 1)
                                            <span class="text-warning fw-semibold">(multi-part)</span>
                                        @endif
                                    </small>
                                @endif
                            </div>

                            @if($reviewMode)
                                {{-- Editable review fields --}}
                                @if($currentTemplate->isEmail())
                                    <input type="text" class="form-control form-control-sm mb-2"
                                           placeholder="Subject"
                                           wire:model.live="reviewSubject">
                                @endif
                                <textarea class="form-control form-control-sm"
                                          rows="8"
                                          wire:model.live="reviewBodyText"></textarea>
                                <div class="small text-muted mt-1">
                                    <i class="mdi mdi-information-outline me-1"></i>Editing this send only — the template is unchanged.
                                    @if($currentTemplate->isEmail())
                                        HTML formatting will be rebuilt from your text.
                                    @endif
                                </div>
                            @else
                                {{-- Read-only preview --}}
                                <div class="border rounded bg-white" style="max-height:260px;overflow:auto">
                                    @if($previewSubject)
                                        <div class="px-3 py-2 border-bottom">
                                            <small class="text-muted d-block">Subject</small>
                                            <strong class="small">{{ $previewSubject }}</strong>
                                        </div>
                                    @endif
                                    <div class="p-3 small">
                                        @if($currentTemplate->isEmail() && $previewBodyHtml)
                                            {!! $previewBodyHtml !!}
                                        @elseif($previewBodyText)
                                            <pre style="white-space:pre-wrap;font-family:inherit;font-size:inherit;margin:0">{{ $previewBodyText }}</pre>
                                        @else
                                            <em class="text-muted">Template has no body content.</em>
                                        @endif
                                    </div>
                                </div>

                                @if(!empty($previewUnknown))
                                    <div class="small text-danger mt-1">
                                        Unknown placeholders:
                                        @foreach($previewUnknown as $u)
                                            <code>{{ $u }}</code>{{ !$loop->last ? ', ' : '' }}
                                        @endforeach
                                    </div>
                                @endif
                            @endif
                        </div>

                        {{-- Attachments panel --}}
                        @if(!empty($loadedAttachments))
                            <div class="mb-3">
                                <label class="form-label small text-muted text-uppercase fw-semibold">
                                    <i class="mdi mdi-paperclip me-1"></i>Attachments
                                </label>
                                <div class="border rounded">
                                    @foreach($loadedAttachments as $att)
                                        <div class="d-flex align-items-center gap-2 p-2 border-bottom last:border-0"
                                            wire:key="att-{{ $att['type']->id }}">
                                            <div class="flex-grow-1">
                                                <div class="small fw-semibold">{{ $att['type']->display_name }}</div>
                                                @if($att['documents']->isNotEmpty())
                                                    @foreach($att['documents'] as $document)
                                                        <div class="small text-muted">
                                                            <i class="mdi mdi-file-outline me-1"></i>
                                                            {{ $document->display_name }}
                                                            <span class="text-muted ms-1">({{ $document->created_at->format('d/m/Y') }})</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="small text-danger">
                                                        <i class="mdi mdi-alert-circle-outline me-1"></i>Not found
                                                    </div>
                                                @endif
                                            </div>

                                            @if($att['available']->isNotEmpty())
                                                <div>
                                                    <select class="form-select form-select-sm"
                                                            style="width: auto; max-width: 180px;"
                                                            wire:change="replaceAttachment({{ $att['type']->id }}, $event.target.value)">
                                                        <option value="">Replace...</option>
                                                        @foreach($att['available'] as $doc)
                                                            <option value="{{ $doc->id }}"
                                                                    @selected(($attachmentOverrides[$att['type']->id] ?? null) == $doc->id)>
                                                                {{ $doc->display_name }}
                                                                ({{ $doc->created_at->format('d/m/Y') }})
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            @endif
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endif
                    @endif

                    @if($currentTemplate && !empty($recipientValidities))
                        <div class="small mb-2">
                            <span class="text-muted text-uppercase fw-semibold">To:</span>
                            @foreach($recipientValidities as $rv)
                                <span class="d-inline-flex align-items-center me-2">
                                    <span class="text-dark">{{ $rv->name ?: 'Unknown recipient' }}</span>
                                    @if($rv->value())
                                        <span class="text-muted ms-1">&lt;{{ $rv->value() }}&gt;</span>
                                    @endif
                                    @if(!$rv->canSend())
                                        <i class="mdi mdi-alert-circle-outline text-danger ms-1"
                                           title="{{ $rv->reason }}"></i>
                                    @endif
                                </span>
                            @endforeach
                            @php $blocked = collect($recipientValidities)->filter(fn ($rv) => !$rv->canSend()); @endphp
                            @if($blocked->isNotEmpty())
                                <span class="d-block text-danger mt-1">
                                    <i class="mdi mdi-alert-circle-outline me-1"></i>
                                    @foreach($blocked as $b){{ $b->name ?: 'Recipient' }}: {{ $b->reason }}@if(!$loop->last); @endif @endforeach
                                </span>
                            @endif
                        </div>
                    @endif

                    <div class="d-flex justify-content-end gap-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                                wire:click.prevent="close">Cancel</button>
                        <button type="submit" class="btn btn-sm btn-primary"
                                @disabled(!$currentTemplate || !$canSendAny)>
                            <i class="mdi mdi-send me-1"></i>Send
                        </button>
                    </div>
                @endif

            </form>
        </div>
    @endif
</div>
