<div>
    <div class="card shadow-sm">
        <div class="card-body p-4">

            {{-- ══════════════════════════════════════════════════════════════
                 Channel Bar  –  Call · Email · SMS
            ══════════════════════════════════════════════════════════════ --}}
            <div class="row g-3 mb-4">

                {{-- ── Call ── --}}
                <div class="col-12 col-lg-4 col-xl-3">
                    <livewire:dialler.call-manager
                        :communicable="$model"
                        :wire:key="'call-manager-' . $model->getKey()"
                    />
                </div>

                {{-- ── Call Institute ── --}}
                @if($model instanceof \App\Models\Client\Client)
                <div class="col-12 col-lg-4 col-xl-3">
                        <livewire:dialler.call-institute
                            :client="$model"
                            :wire:key="'call-institute-' . $model->getKey()"
                        />
                    </div>
                @endif

                {{-- ── Email ── --}}
                <div class="col-12 col-lg-4 col-xl-3">
                    <div class="border rounded-3 p-3 h-100 d-flex flex-column">
                        <div class="d-flex align-items-center gap-2 mb-2">
                            <div class="d-flex align-items-center justify-content-center rounded-circle bg-primary bg-opacity-10 text-primary flex-shrink-0"
                                 style="width:36px;height:36px">
                                <i class="mdi mdi-email-outline fs-5"></i>
                            </div>
                            <span class="fw-semibold">Email</span>
                            @if($emailValidity)
                                <span class="badge ms-auto bg-{{ $emailValidity->validity->color() }}">
                                    <i class="{{ $emailValidity->validity->icon() }} me-1"></i>{{ $emailValidity->validity->label() }}
                                </span>
                            @endif
                        </div>

                        @if($emailValidity?->email)
                            <div class="text-muted small mb-3 text-truncate">{{ $emailValidity->email }}</div>
                        @elseif($emailValidity?->reason)
                            <div class="text-danger small mb-3">{{ $emailValidity->reason }}</div>
                        @else
                            <div class="text-muted small mb-3">—</div>
                        @endif

                        <div class="mt-auto d-flex flex-column gap-1">
                            @can('communications.send.email')
                                <button class="btn btn-primary btn-sm w-100"
                                        @disabled(!$emailValidity?->canSend())
                                        wire:click="$dispatch('contact:compose', { channel: 'email' })">
                                    <i class="mdi mdi-email-outline me-1"></i>Compose Email
                                </button>
                                <button class="btn btn-link btn-sm w-100 text-muted p-0 small"
                                        @disabled(!$emailValidity?->canSend())
                                        wire:click="$dispatch('contact:compose', { channel: 'email', freeText: true })">
                                    <i class="mdi mdi-pencil me-1"></i>Free text
                                </button>
                            @else
                                <button class="btn btn-secondary btn-sm w-100 disabled">
                                    <i class="mdi mdi-email-outline me-1"></i>Compose Email
                                </button>
                            @endcan
                        </div>
                    </div>
                </div>

                {{-- ── SMS ── --}}
                <div class="col-12 col-lg-4 col-xl-3">

                    <div class="border rounded-3 p-3 h-100 d-flex flex-column">
                        <div class="d-flex align-items-center gap-2 mb-2">
                            <div class="d-flex align-items-center justify-content-center rounded-circle bg-info bg-opacity-10 text-info flex-shrink-0"
                                 style="width:36px;height:36px">
                                <i class="mdi mdi-message-text-outline fs-5"></i>
                            </div>
                            <span class="fw-semibold">SMS</span>
                            @if($smsValidity)
                                <span class="badge ms-auto bg-{{ $smsValidity->validity->color() }}">
                                    <i class="{{ $smsValidity->validity->icon() }} me-1"></i>{{ $smsValidity->validity->label() }}
                                </span>
                            @endif
                        </div>

                        @if($smsValidity?->phone)
                            <div class="text-muted small mb-3">{{ $smsValidity->phone }}</div>
                        @elseif($smsValidity?->reason)
                            <div class="text-danger small mb-3">{{ $smsValidity->reason }}</div>
                        @else
                            <div class="text-muted small mb-3">—</div>
                        @endif

                        <div class="mt-auto d-flex flex-column gap-1">
                            @can('communications.send.sms')
                                <button class="btn btn-info btn-sm w-100 text-white"
                                        @disabled(!$smsValidity?->canSend())
                                        wire:click="$dispatch('contact:compose', { channel: 'sms' })">
                                    <i class="mdi mdi-message-text-outline me-1"></i>Compose SMS
                                </button>
                                <button class="btn btn-link btn-sm w-100 text-muted p-0 small"
                                        @disabled(!$smsValidity?->canSend())
                                        wire:click="$dispatch('contact:compose', { channel: 'sms', freeText: true })">
                                    <i class="mdi mdi-pencil me-1"></i>Free text
                                </button>
                            @else
                                <button class="btn btn-secondary btn-sm w-100 disabled">
                                    <i class="mdi mdi-message-text-outline me-1"></i>Compose SMS
                                </button>
                            @endcan
                        </div>
                    </div>
                </div>

            </div>{{-- /row --}}
            
            {{-- ══════════════════════════════════════════════════════════════
                 Inline Compose Panel
            ══════════════════════════════════════════════════════════════ --}}
            <livewire:contact.compose-message
                :model="$model"
                :key="'contact-compose-' . $model->getKey()"
            />

            {{-- ══════════════════════════════════════════════════════════════
                 Activity Feed
            ══════════════════════════════════════════════════════════════ --}}
            <div class="border-top pt-4">

                <div class="d-flex align-items-center justify-content-between mb-3">
                    <h6 class="mb-0 fw-semibold">Activity</h6>
                    <div class="d-flex gap-2">
                        <select class="form-select form-select-sm" style="width:auto"
                                wire:model.live="filterChannel">
                            <option value="">All channels</option>
                            <option value="call">Call</option>
                            <option value="email">Email</option>
                            <option value="sms">SMS</option>
                        </select>
                        <select class="form-select form-select-sm" style="width:auto"
                                wire:model.live="filterStatus">
                            <option value="">All statuses</option>
                            <option value="queued">Queued</option>
                            <option value="sent">Sent</option>
                            <option value="delivered">Delivered</option>
                            <option value="opened">Opened</option>
                            <option value="failed">Failed</option>
                            <option value="completed">Completed</option>
                            <option value="missed">Missed</option>
                        </select>
                    </div>
                </div>

                @if($activities->isEmpty())
                    <div class="text-center text-muted py-5">
                        <i class="mdi mdi-timeline-outline d-block mb-2" style="font-size:2.4rem;opacity:.3"></i>
                        <div class="small">No activity yet.</div>
                    </div>
                @else
                    <div class="list-group list-group-flush">
                        @foreach($activities as $activity)

                            @if($activity['kind'] === 'call')
                                @php $comm = $activity['data']; @endphp
                                <div class="list-group-item px-0 py-3 border-0 border-bottom"
                                     wire:key="comm-{{ $comm->id }}">
                                    <div class="d-flex align-items-start justify-content-between gap-2">
                                        <div class="d-flex align-items-center gap-2 min-w-0">
                                            <div class="d-flex align-items-center justify-content-center rounded-circle flex-shrink-0"
                                                 style="width:32px;height:32px;background:#f1f5f9">
                                                <i class="mdi {{ $comm->direction === 'inbound' ? 'mdi-phone-incoming text-info' : 'mdi-phone-outgoing text-success' }}"
                                                   style="font-size:.95rem"></i>
                                            </div>
                                            <div class="min-w-0">
                                                <div class="small fw-semibold text-truncate">
                                                    {{ $comm->preview ?? 'Voice call' }}
                                                </div>
                                                <div class="text-muted" style="font-size:.72rem">
                                                    {{ $comm->started_at?->diffForHumans() }}
                                                    @if($comm->agent)
                                                        &nbsp;·&nbsp;{{ $comm->agent->name_first }}
                                                    @endif
                                                    @if($comm->recordings->isNotEmpty())
                                                        &nbsp;·&nbsp;<i class="mdi mdi-record-circle-outline text-danger"></i> Recorded
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                        <span @class([
                                            'badge rounded-pill flex-shrink-0',
                                            'text-bg-success'   => $comm->status === 'completed',
                                            'text-bg-danger'    => in_array($comm->status, ['failed', 'missed']),
                                            'text-bg-warning'   => $comm->status === 'voicemail',
                                            'text-bg-secondary' => !in_array($comm->status, ['completed', 'failed', 'missed', 'voicemail']),
                                        ])>{{ ucfirst(str_replace('_', ' ', $comm->status)) }}</span>
                                    </div>

                                    {{-- Waveform player for completed recordings --}}
                                    @foreach($comm->recordings->where('status', 'completed') as $rec)
                                        <div class="mt-2 ms-5"
                                             x-data="waveformPlayer('{{ route('recordings.stream', $rec) }}')"
                                             x-init="init()">
                                            <div class="d-flex align-items-center gap-2 px-2 py-1 rounded"
                                                 style="background:#f1f5f9">
                                                <button @click="toggle()" :disabled="error"
                                                        class="btn btn-sm btn-primary rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                                                        style="width:26px;height:26px;padding:0">
                                                    <span x-show="loading" class="spinner-border"
                                                          style="width:.55rem;height:.55rem;border-width:1.5px"></span>
                                                    <i x-show="!loading && !playing && !error" class="mdi mdi-play"
                                                       style="font-size:.8rem;margin-left:1px"></i>
                                                    <i x-show="!loading && playing" class="mdi mdi-pause"
                                                       style="font-size:.8rem"></i>
                                                    <i x-show="error" class="mdi mdi-alert-circle-outline"
                                                       style="font-size:.8rem"></i>
                                                </button>
                                                <div class="flex-grow-1 overflow-hidden" style="min-width:0">
                                                    <div x-ref="waveform" x-show="!error"></div>
                                                    <span x-show="error" class="text-danger"
                                                          style="font-size:.7rem">Could not load audio.</span>
                                                </div>
                                                <div class="flex-shrink-0 font-monospace text-muted"
                                                     style="font-size:.66rem;white-space:nowrap">
                                                    <span x-text="currentTime">00:00</span>
                                                    <span class="opacity-50">/</span>
                                                    <span x-text="ready ? totalTime : '{{ $rec->duration_label }}'">{{ $rec->duration_label }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        {{-- ── Synapse Panel ── --}}
                                        @php
                                            $st         = $rec->synapseTranscript;
                                            $cs         = $rec->callScore;
                                            $hasT       = $st && $st->status === 'completed';
                                            $hasS       = $cs && $cs->status === 'completed' && $cs->is_initial_call === true;
                                            $canExpand  = $hasT || $hasS;
                                            $autoOpen   = $hasS && ($cs->auto_fail || !$cs->passed);
                                            $secLabels = [
                                                'introduction_identity_recording' => 'Intro & ID',
                                                'vulnerability_wellbeing'         => 'Wellbeing',
                                                'purpose_of_call'                 => 'Purpose',
                                                'client_options_funding'          => 'Options & Funding',
                                                'private_funding_fees'            => 'Fees',
                                                'no_guarantee_scope_waiver'       => 'Scope & Waiver',
                                                'cancellation_pressure'           => 'Cancellation',
                                                'aml_identity_verification'       => 'AML / ID',
                                                'information_gathering'           => 'Info & Statements',
                                                'payment_types_next_steps'        => 'Payments & Next Steps',
                                            ];
                                        @endphp
                                        <div class="mt-2" x-data="{ open: {{ $autoOpen ? 'true' : 'false' }} }">

                                            {{-- Header bar --}}
                                            <div class="d-flex align-items-center justify-content-between gap-2 px-2 rounded"
                                                 style="background:#f5f3ff;border:1px solid #ede9fe;min-height:26px;">

                                                {{-- Left: status / badges --}}
                                                <div class="d-flex align-items-center gap-1 py-1" style="font-size:.65rem;min-width:0;">
                                                    <i class="mdi mdi-brain flex-shrink-0" style="color:#7c3aed;"></i>

                                                    @if(!$st)
                                                        <span style="color:#a78bfa;">No transcript yet</span>

                                                    @elseif($st->status === 'processing')
                                                        <span class="spinner-border flex-shrink-0" style="width:.45rem;height:.45rem;border-width:1px;color:#7c3aed;"></span>
                                                        <span style="color:#7c3aed;">Transcribing…</span>

                                                    @elseif($st->status === 'failed')
                                                        <span class="text-danger"><i class="mdi mdi-alert-circle-outline"></i> Transcription failed</span>

                                                    @elseif(!$cs)
                                                        <span style="color:#7c3aed;">Transcript ready</span>

                                                    @elseif($cs->status === 'processing')
                                                        <span class="spinner-border flex-shrink-0" style="width:.45rem;height:.45rem;border-width:1px;color:#7c3aed;"></span>
                                                        <span style="color:#7c3aed;">Analysing…</span>

                                                    @elseif($cs->status === 'failed')
                                                        <span class="text-danger"><i class="mdi mdi-alert-circle-outline"></i> Analysis failed</span>

                                                    @elseif($cs->status === 'completed' && $cs->is_initial_call === null)
                                                        <span class="badge" style="background:#d97706;font-size:.55rem;">Not Applicable</span>
                                                        <span style="color:#92400e;">No scoreable content</span>

                                                    @elseif($cs->status === 'completed' && $cs->is_initial_call === false)
                                                        <span class="badge bg-secondary" style="font-size:.55rem;">Follow-up</span>
                                                        <span style="color:#64748b;">Compliance scoring not applicable</span>

                                                    @elseif($cs->status === 'completed' && $cs->is_initial_call === true)
                                                        <span class="badge" style="background:#7c3aed;font-size:.55rem;">Initial Call</span>
                                                        @if($cs->auto_fail)
                                                            <span class="badge bg-danger" style="font-size:.55rem;">AUTO FAIL</span>
                                                        @elseif($cs->passed)
                                                            <span class="badge bg-success" style="font-size:.55rem;">PASS</span>
                                                        @else
                                                            <span class="badge bg-danger" style="font-size:.55rem;">FAIL</span>
                                                        @endif
                                                        <span class="badge {{ $cs->risk_rating_badge }}" style="font-size:.55rem;">{{ $cs->risk_rating_label }}</span>
                                                        <span class="fw-semibold" style="color:#374151;">{{ $cs->total_score }}/100</span>
                                                    @endif
                                                </div>

                                                {{-- Right: icon action buttons + expand toggle --}}
                                                <div class="d-flex align-items-center gap-1 flex-shrink-0">
                                                    {{-- Re-fetch audio --}}
                                                    <button wire:click="refetchRecording({{ $rec->id }})"
                                                            wire:loading.attr="disabled"
                                                            wire:target="refetchRecording({{ $rec->id }})"
                                                            title="Re-fetch audio"
                                                            class="btn btn-sm p-0 border-0 d-flex align-items-center justify-content-center"
                                                            style="width:18px;height:18px;background:none;color:#dc2626;opacity:.7;">
                                                        <span wire:loading
                                                            wire:target="refetchRecording({{ $rec->id }})"
                                                            class="spinner-border"
                                                            style="width:.35rem;height:.35rem;border-width:1px;"></span>

                                                        <i wire:loading.remove
                                                            wire:target="refetchRecording({{ $rec->id }})"
                                                            class="mdi mdi-cloud-download-outline"
                                                            style="font-size:.75rem;line-height:1;">
                                                        </i>
                                                    </button>
                                                    <button wire:click="retranscribeRecording({{ $rec->id }})"
                                                            wire:loading.attr="disabled"
                                                            wire:target="retranscribeRecording({{ $rec->id }})"
                                                            title="Re-transcribe"
                                                            class="btn btn-sm p-0 border-0 d-flex align-items-center justify-content-center"
                                                            style="width:18px;height:18px;background:none;color:#7c3aed;opacity:.6;">
                                                        <span wire:loading wire:target="retranscribeRecording({{ $rec->id }})" class="spinner-border" style="width:.35rem;height:.35rem;border-width:1px;"></span>
                                                        <i wire:loading.remove wire:target="retranscribeRecording({{ $rec->id }})" class="mdi mdi-waveform" style="font-size:.75rem;line-height:1;"></i>
                                                    </button>

                                                    @if($hasT)
                                                        <button wire:click="reclassifyRecording({{ $rec->id }})"
                                                                wire:loading.attr="disabled"
                                                                wire:target="reclassifyRecording({{ $rec->id }})"
                                                                title="Re-analyse"
                                                                class="btn btn-sm p-0 border-0 d-flex align-items-center justify-content-center"
                                                                style="width:18px;height:18px;background:none;color:#7c3aed;opacity:.6;">
                                                            <span wire:loading wire:target="reclassifyRecording({{ $rec->id }})" class="spinner-border" style="width:.35rem;height:.35rem;border-width:1px;"></span>
                                                            <i wire:loading.remove wire:target="reclassifyRecording({{ $rec->id }})" class="mdi mdi-refresh" style="font-size:.75rem;line-height:1;"></i>
                                                        </button>
                                                    @endif

                                                    @if($canExpand)
                                                        <button @click="open = !open"
                                                                class="btn btn-sm p-0 border-0 d-flex align-items-center justify-content-center"
                                                                style="width:18px;height:18px;background:none;color:#7c3aed;opacity:.6;">
                                                            <i :class="open ? 'mdi-chevron-up' : 'mdi-chevron-down'" class="mdi" style="font-size:.85rem;line-height:1;"></i>
                                                        </button>
                                                    @endif
                                                </div>
                                            </div>

                                            {{-- Expandable body --}}
                                            @if($canExpand)
                                                <div x-show="open" style="display:none;">
                                                    <div class="px-2 pt-2 pb-2" style="background:#faf9ff;border:1px solid #ede9fe;border-top:none;border-radius:0 0 4px 4px;">

                                                        {{-- Score breakdown --}}
                                                        @if($hasS)
                                                            @if($cs->auto_fail && !empty($cs->auto_fail_triggers))
                                                                <div class="rounded p-1 mb-2" style="background:#fee2e2;font-size:.62rem;">
                                                                    <div class="fw-semibold text-danger mb-1">Auto-fail triggers:</div>
                                                                    @foreach($cs->auto_fail_triggers as $trigger)
                                                                        <div class="text-danger"><i class="mdi mdi-close-circle me-1"></i>{{ $trigger }}</div>
                                                                    @endforeach
                                                                </div>
                                                            @endif

                                                            @if($cs->section_scores)
                                                                @foreach($secLabels as $key => $label)
                                                                    @if(isset($cs->section_scores[$key]))
                                                                        @php
                                                                            $s   = $cs->section_scores[$key];
                                                                            $pct = $s['max'] > 0 ? ($s['score'] / $s['max'] * 100) : 0;
                                                                            $col = $pct >= 100 ? '#16a34a' : ($pct > 0 ? '#d97706' : '#dc2626');
                                                                        @endphp
                                                                        <div class="d-flex align-items-center gap-2 mb-1" style="font-size:.62rem;">
                                                                            <span class="text-truncate" style="width:100px;flex-shrink:0;color:#6b7280;">{{ $label }}</span>
                                                                            <div class="flex-grow-1 rounded-pill" style="background:#e9d8fd;height:3px;overflow:hidden;">
                                                                                <div style="width:{{ $pct }}%;height:3px;background:{{ $col }};"></div>
                                                                            </div>
                                                                            <span style="width:28px;text-align:right;font-weight:600;color:{{ $col }};flex-shrink:0;">{{ $s['score'] }}/{{ $s['max'] }}</span>
                                                                        </div>
                                                                    @endif
                                                                @endforeach
                                                            @endif

                                                            @if($cs->summary)
                                                                <p class="mb-2 mt-1" style="font-size:.62rem;color:#374151;border-top:1px solid #ede9fe;padding-top:6px;">{{ $cs->summary }}</p>
                                                            @endif

                                                            @if($hasT)
                                                                <div style="border-top:1px solid #ede9fe;margin-bottom:6px;"></div>
                                                            @endif
                                                        @endif

                                                        {{-- AI Summary + Sentiment (AssemblyAI) --}}
                                                        @if($hasT && ($st->ai_summary || $st->sentiment_data))
                                                            <div style="border-top:1px solid #ede9fe;padding-top:6px;margin-bottom:6px;">

                                                                @if($st->ai_summary)
                                                                    <div class="mb-2" style="font-size:.62rem;">
                                                                        <span class="fw-semibold" style="color:#7c3aed;">Summary&nbsp;</span>
                                                                        <span style="color:#374151;">{{ $st->ai_summary }}</span>
                                                                    </div>
                                                                @endif

                                                                @if($st->sentiment_data)
                                                                    @php $sb = $st->sentiment_breakdown; @endphp
                                                                    <div class="d-flex align-items-center gap-2 mb-1" style="font-size:.62rem;">
                                                                        <span class="fw-semibold flex-shrink-0" style="color:#7c3aed;">Sentiment</span>
                                                                        <div class="d-flex rounded-pill overflow-hidden flex-grow-1" style="height:5px;">
                                                                            <div style="width:{{ $sb['positive'] ?? 0 }}%;background:#16a34a;"></div>
                                                                            <div style="width:{{ $sb['neutral']  ?? 0 }}%;background:#9ca3af;"></div>
                                                                            <div style="width:{{ $sb['negative'] ?? 0 }}%;background:#dc2626;"></div>
                                                                        </div>
                                                                        <span style="color:#16a34a;flex-shrink:0;">{{ $sb['positive'] ?? 0 }}%</span>
                                                                        <span style="color:#6b7280;flex-shrink:0;">{{ $sb['neutral'] ?? 0 }}%</span>
                                                                        <span style="color:#dc2626;flex-shrink:0;">{{ $sb['negative'] ?? 0 }}%</span>
                                                                    </div>
                                                                @endif

                                                            </div>
                                                        @endif

                                                        {{-- Transcript --}}
                                                        @if($hasT)
                                                            <pre style="font-size:.62rem;white-space:pre-wrap;font-family:inherit;color:#374151;margin:0;max-height:240px;overflow-y:auto;line-height:1.55;">{{ $st->formatted_transcript }}</pre>
                                                        @endif

                                                    </div>
                                                </div>
                                            @endif

                                        </div>{{-- /synapse panel --}}
                                    @endforeach

                                    @if($comm->call?->notes)
                                        <div class="mt-2 ms-5 text-muted" style="font-size:.78rem;">
                                            <i class="mdi mdi-note-text-outline me-1"></i>{{ $comm->call->notes }}
                                        </div>
                                    @endif
                                </div>

                            @else
                                @php $msg = $activity['data']; @endphp
                                <div class="list-group-item px-0 py-3 border-0 border-bottom"
                                     wire:key="msg-{{ $msg->id }}">
                                    <div class="d-flex align-items-start justify-content-between gap-2">
                                        <div class="d-flex align-items-center gap-2 min-w-0 flex-grow-1"
                                             wire:click="viewMessage({{ $msg->id }})"
                                             role="button" style="cursor:pointer">
                                            <div class="d-flex align-items-center justify-content-center rounded-circle flex-shrink-0"
                                                 style="width:32px;height:32px;background:#f1f5f9">
                                                <i class="{{ $msg->channel->icon() }}"
                                                   style="font-size:.95rem"></i>
                                            </div>
                                            <div class="min-w-0">
                                                <div class="small fw-semibold text-truncate">
                                                    {{ $msg->subject ?: Str::limit($msg->body_text, 80) }}
                                                </div>
                                                <div class="text-muted" style="font-size:.72rem">
                                                    @if($msg->channel->value === 'email')
                                                        <i class="mdi mdi-arrow-right"></i> {{ $msg->recipient_email ?? '—' }}
                                                    @else
                                                        <i class="mdi mdi-arrow-right"></i> {{ $msg->recipient_phone ?? '—' }}
                                                    @endif
                                                    @if($msg->template)
                                                        &nbsp;·&nbsp;via <em>{{ $msg->template->name }}</em>
                                                    @endif
                                                    @if($msg->creator)
                                                        &nbsp;·&nbsp;{{ $msg->creator->name }}
                                                    @elseif($msg->origin_type)
                                                        &nbsp;·&nbsp;{{ $msg->origin_type->label() }}
                                                    @endif
                                                    &nbsp;·&nbsp;{{ $msg->created_at?->diffForHumans() }}
                                                </div>
                                                @if($msg->failure_reason)
                                                    <div class="small text-danger mt-1">{{ $msg->failure_reason }}</div>
                                                @endif
                                            </div>
                                        </div>
                                        <div class="d-flex flex-column align-items-end gap-1 flex-shrink-0">
                                            <span class="badge bg-{{ $msg->status->color() }}">
                                                {{ $msg->status->label() }}
                                            </span>
                                            <livewire:contact.communication-event-viewer
                                                :message-id="$msg->id"
                                                :wire:key="'evt-' . $msg->id"
                                            />
                                        </div>
                                    </div>
                                </div>

                            @endif

                        @endforeach
                    </div>
                @endif

            </div>{{-- /activity feed --}}

        </div>
    </div>

    {{-- ══════════════════════════════════════════════════════════════
         Message Detail Offcanvas
    ══════════════════════════════════════════════════════════════ --}}
    <div class="offcanvas offcanvas-end" tabindex="-1" id="msgDetailOffcanvas" style="width:520px">

        <div class="offcanvas-header border-bottom py-3">
            @if($selectedMessage)
                <div class="d-flex align-items-center gap-2 min-w-0">
                    <div class="d-flex align-items-center justify-content-center rounded-circle flex-shrink-0"
                         style="width:32px;height:32px;background:#f1f5f9">
                        <i class="{{ $selectedMessage->channel->icon() }}" style="font-size:.95rem"></i>
                    </div>
                    <div class="min-w-0">
                        <h6 class="offcanvas-title mb-0 text-truncate">
                            {{ $selectedMessage->subject ?: ucfirst($selectedMessage->channel->value) . ' Message' }}
                        </h6>
                        <div style="font-size:.7rem">
                            <span class="badge bg-{{ $selectedMessage->status->color() }}">
                                {{ $selectedMessage->status->label() }}
                            </span>
                        </div>
                    </div>
                </div>
            @else
                <h6 class="offcanvas-title mb-0">Message Detail</h6>
            @endif
            <button type="button" class="btn-close ms-auto flex-shrink-0" data-bs-dismiss="offcanvas"></button>
        </div>

        <div class="offcanvas-body p-0 d-flex flex-column" style="min-height:0">
            @if($selectedMessage)
                @php $m = $selectedMessage; @endphp

                {{-- ── Tabs ── --}}
                <div class="px-4 border-bottom bg-white flex-shrink-0">
                    <ul class="nav nav-tabs border-0" id="msgDetailTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active px-3 py-2" id="msgDetailTab-message"
                                    data-bs-toggle="tab" data-bs-target="#msgDetailPane-message"
                                    type="button" role="tab" style="font-size:.82rem">
                                <i class="mdi mdi-email-outline me-1"></i>Message
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link px-3 py-2" id="msgDetailTab-events"
                                    data-bs-toggle="tab" data-bs-target="#msgDetailPane-events"
                                    type="button" role="tab" style="font-size:.82rem">
                                <i class="mdi mdi-timeline-outline me-1"></i>Events
                                @if($m->events->isNotEmpty())
                                    <span class="badge bg-secondary ms-1" style="font-size:.65rem">{{ $m->events->count() }}</span>
                                @endif
                            </button>
                        </li>
                    </ul>
                </div>

                {{-- ── Tab content ── --}}
                <div class="tab-content flex-grow-1 overflow-auto" id="msgDetailTabContent">

                    {{-- Message tab --}}
                    <div class="tab-pane fade show active" id="msgDetailPane-message" role="tabpanel">

                        {{-- Metadata --}}
                        <div class="px-4 py-3 border-bottom bg-light" style="font-size:.82rem">
                            <dl class="mb-0" style="display:grid;grid-template-columns:72px 1fr;row-gap:4px;column-gap:8px;">

                                <dt class="text-muted fw-normal d-flex align-items-start pt-1">From</dt>
                                <dd class="mb-0 text-truncate">
                                    @if($m->sender_display && $m->sender_value && $m->sender_display !== $m->sender_value)
                                        {{ $m->sender_display }}
                                        <span class="text-muted">&lt;{{ $m->sender_value }}&gt;</span>
                                    @else
                                        {{ $m->sender_display ?: $m->sender_value ?: '—' }}
                                    @endif
                                </dd>

                                <dt class="text-muted fw-normal d-flex align-items-start pt-1">To</dt>
                                <dd class="mb-0 text-truncate">
                                    @if($m->recipient_name && ($m->recipient_email ?: $m->recipient_phone))
                                        {{ $m->recipient_name }}
                                        <span class="text-muted">&lt;{{ $m->recipient_email ?: $m->recipient_phone }}&gt;</span>
                                    @else
                                        {{ $m->recipient_name ?: ($m->recipient_email ?: ($m->recipient_phone ?: '—')) }}
                                    @endif
                                </dd>

                                @if($m->reply_to)
                                    <dt class="text-muted fw-normal d-flex align-items-start pt-1">Reply-to</dt>
                                    <dd class="mb-0 text-truncate">{{ $m->reply_to }}</dd>
                                @endif

                                @if($m->template)
                                    <dt class="text-muted fw-normal d-flex align-items-start pt-1">Template</dt>
                                    <dd class="mb-0">{{ $m->template->name }}</dd>
                                @endif

                                <dt class="text-muted fw-normal d-flex align-items-start pt-1">Sent by</dt>
                                <dd class="mb-0">
                                    @if($m->creator){{ $m->creator->name }}
                                    @elseif($m->origin_type){{ $m->origin_type->label() }}
                                    @else—@endif
                                </dd>

                                @php
                                    $stamps = array_filter([
                                        'Queued'    => $m->queued_at,
                                        'Sent'      => $m->sent_at,
                                        'Delivered' => $m->delivered_at,
                                        'Opened'    => $m->opened_at,
                                        'Failed'    => $m->failed_at,
                                    ]);
                                @endphp
                                @foreach($stamps as $label => $ts)
                                    <dt class="text-muted fw-normal d-flex align-items-start pt-1">{{ $label }}</dt>
                                    <dd class="mb-0 text-muted">
                                        {{ $ts->format('d M Y, H:i') }}
                                        <span class="opacity-50">({{ $ts->diffForHumans() }})</span>
                                    </dd>
                                @endforeach

                                @if($m->failure_reason)
                                    <dt class="text-muted fw-normal d-flex align-items-start pt-1">Reason</dt>
                                    <dd class="mb-0 text-danger">{{ $m->failure_reason }}</dd>
                                @endif

                            </dl>
                        </div>

                        {{-- Body --}}
                        <div class="px-4 py-3">
                            @if($m->channel->value === 'email')
                                @if($m->body_html)
                                    <div class="border rounded bg-white p-3" style="font-size:.85rem">
                                        {!! $m->body_html !!}
                                    </div>
                                @elseif($m->body_text)
                                    <pre class="border rounded bg-white p-3 mb-0" style="font-size:.82rem;white-space:pre-wrap;font-family:inherit">{{ $m->body_text }}</pre>
                                @else
                                    <p class="text-muted fst-italic mb-0">No message body.</p>
                                @endif
                            @else
                                <div class="border rounded bg-white p-3" style="font-size:.88rem;white-space:pre-wrap">
                                    {{ $m->body_text ?: '—' }}
                                </div>
                            @endif
                        </div>

                        {{-- Attachments --}}
                        @if($m->attachments->isNotEmpty())
                            <div class="px-4 py-3 border-top">
                                <div class="small fw-semibold text-muted mb-2">
                                    <i class="mdi mdi-paperclip me-1"></i>Attachments ({{ $m->attachments->count() }})
                                </div>
                                <div class="d-flex flex-column gap-2">
                                    @foreach($m->attachments as $att)
                                        <div class="d-flex align-items-center gap-2 border rounded px-3 py-2" style="font-size:.82rem">
                                            <i class="mdi mdi-file-outline text-muted flex-shrink-0 fs-5"></i>
                                            <div class="min-w-0 flex-grow-1">
                                                <div class="text-truncate fw-medium">{{ $att->filename }}</div>
                                                @if($att->size)
                                                    <div class="text-muted" style="font-size:.72rem">{{ number_format($att->size / 1024, 1) }} KB</div>
                                                @endif
                                            </div>
                                            <a href="{{ route('inbox.attachment.download', $att) }}"
                                               class="btn btn-sm btn-outline-secondary flex-shrink-0"
                                               title="Download">
                                                <i class="mdi mdi-download"></i>
                                            </a>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                    </div>{{-- /message tab --}}

                    {{-- Events tab --}}
                    <div class="tab-pane fade" id="msgDetailPane-events" role="tabpanel">
                        @if($m->events->isEmpty())
                            <div class="d-flex flex-column align-items-center justify-content-center text-muted py-5">
                                <i class="mdi mdi-timeline-outline mb-2" style="font-size:2rem;opacity:.3"></i>
                                <div class="small">No events recorded yet.</div>
                            </div>
                        @else
                            <ul class="list-unstyled mb-0">
                                @foreach($m->events->sortBy('occurred_at') as $event)
                                    <li class="d-flex align-items-start gap-3 px-4 py-3 border-bottom">
                                        <div class="flex-shrink-0 d-flex flex-column align-items-center" style="padding-top:2px">
                                            <div class="rounded-circle bg-{{ $event->event_type->color() }} bg-opacity-15 d-flex align-items-center justify-content-center"
                                                 style="width:28px;height:28px">
                                                <i class="mdi mdi-circle-small text-{{ $event->event_type->color() }}" style="font-size:1.1rem"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 min-w-0" style="font-size:.82rem">
                                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                                <span class="badge bg-{{ $event->event_type->color() }}">
                                                    {{ $event->event_type->label() }}
                                                </span>
                                                @if($event->mapped_status)
                                                    <span class="text-muted">
                                                        → <span class="badge bg-{{ $event->mapped_status->color() }}">{{ $event->mapped_status->label() }}</span>
                                                    </span>
                                                @endif
                                            </div>
                                            <div class="text-muted mt-1" style="font-size:.75rem">
                                                {{ $event->occurred_at?->format('d M Y, H:i:s') }}
                                                <span class="opacity-60">({{ $event->occurred_at?->diffForHumans() }})</span>
                                            </div>
                                            @if($event->provider_event_id)
                                                <div class="text-muted font-monospace mt-1" style="font-size:.68rem;opacity:.6">
                                                    {{ $event->provider_event_id }}
                                                </div>
                                            @endif
                                        </div>
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>{{-- /events tab --}}

                </div>{{-- /tab-content --}}

            @else
                <div class="d-flex align-items-center justify-content-center h-100 text-muted">
                    <span>No message selected.</span>
                </div>
            @endif
        </div>

    </div>

    @script
    <script>
        const _offcanvasEl = document.getElementById('msgDetailOffcanvas');
        const _offcanvas   = new bootstrap.Offcanvas(_offcanvasEl);

        _offcanvasEl.addEventListener('hidden.bs.offcanvas', () => {
            $wire.set('selectedMessageId', null);
        });

        $wire.$watch('selectedMessageId', id => {
            id ? _offcanvas.show() : _offcanvas.hide();
        });
    </script>
    @endscript

</div>
