<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-md-4">
                    <livewire:dialler.call-manager
                        :communicable="$model"
                        :wire:key="'call-manager-' . $model->getKey()"
                    />
                </div>

                {{-- ── Email ── --}}
                <div class="col-md-4">
                    <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-md-4">
                    <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  = [
                                                'funding_explanation'    => 'Funding',
                                                'financial_transparency' => 'Transparency',
                                                'neutral_advice'         => 'Neutral Advice',
                                                'client_understanding'   => 'Understanding',
                                                'reflection_cancellation'=> 'Reflection',
                                            ];
                                        @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">
                                                    <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
                                </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">
                                            <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>
</div>
