<div
    x-data
    x-on:ct-open-modal.window="
        const el = $el.querySelector('#ct-offcanvas');
        if (el) bootstrap.Offcanvas.getOrCreateInstance(el).show();
    "
>
    {{-- ── Filter bar ──────────────────────────────────────────────────────── --}}
    <div class="d-flex align-items-center justify-content-between mb-2">
        <h6 class="mb-0">Communications</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="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="bounced">Bounced</option>
                <option value="suppressed">Suppressed</option>
            </select>
        </div>
    </div>

    {{-- ── Message list ─────────────────────────────────────────────────────── --}}
    @if($messages->isEmpty())
        <div class="text-muted text-center py-4">
            <i class="mdi mdi-email-off-outline" style="font-size:2rem;"></i>
            <div>No communications yet.</div>
        </div>
    @else
        <div class="list-group mb-2">
            @foreach($messages as $msg)
                @php $isInbound = $msg->direction?->value === 'inbound'; @endphp
                <button
                    type="button"
                    wire:click="openMessage({{ $msg->id }})"
                    class="list-group-item list-group-item-action px-2 py-2 text-start"
                    wire:key="msg-{{ $msg->id }}"
                    style="cursor:pointer;"
                >
                    <div class="d-flex align-items-start gap-2">
                        {{-- Direction --}}
                        <div class="flex-shrink-0 mt-1" title="{{ $isInbound ? 'Received' : 'Sent' }}">
                            @if($isInbound)
                                <i class="mdi mdi-arrow-bottom-left text-primary" style="font-size:1rem;"></i>
                            @else
                                <i class="mdi mdi-arrow-top-right text-success" style="font-size:1rem;"></i>
                            @endif
                        </div>

                        <div class="flex-grow-1 overflow-hidden">
                            <div class="d-flex align-items-start justify-content-between gap-2 mb-1">
                                <div class="d-flex align-items-center gap-2 overflow-hidden">
                                    <i class="{{ $msg->channel->icon() }} text-muted flex-shrink-0"></i>
                                    <span class="fw-semibold text-truncate" style="font-size:.85rem;">
                                        {{ $msg->subject ?: Str::limit($msg->body_text, 60) ?: '(no subject)' }}
                                    </span>
                                </div>
                                <span class="text-muted flex-shrink-0" style="font-size:.75rem;">
                                    {{ $msg->created_at?->format('d M Y') }}
                                </span>
                            </div>

                            <div class="text-muted" style="font-size:.78rem;">
                                @if($isInbound)
                                    <span><i class="mdi mdi-arrow-left me-1"></i>{{ $msg->from_email ?? 'Unknown sender' }}</span>
                                    @if($msg->classification === 'dsar_response')
                                        <span class="badge bg-primary-subtle text-primary ms-2" style="font-size:.68rem;">DSAR Response</span>
                                    @endif
                                    @if($msg->classification_confidence)
                                        <span class="badge bg-light text-muted border ms-1" style="font-size:.68rem;">
                                            {{ ucfirst($msg->classification_confidence) }} confidence
                                        </span>
                                    @endif
                                @else
                                    @if($msg->channel?->value === 'email')
                                        <span><i class="mdi mdi-arrow-right me-1"></i>{{ $msg->recipient_email ?? '—' }}</span>
                                    @else
                                        <span><i class="mdi mdi-arrow-right me-1"></i>{{ $msg->recipient_phone ?? '—' }}</span>
                                    @endif
                                    @if($msg->template)
                                        <span class="ms-2">via <em>{{ $msg->template->name }}</em></span>
                                    @endif
                                    @if($msg->creator)
                                        <span class="ms-2">by {{ $msg->creator->name }}</span>
                                    @elseif($msg->origin_type)
                                        <span class="ms-2">{{ $msg->origin_type->label() }}</span>
                                    @endif
                                @endif
                            </div>

                            @if($msg->failure_reason)
                                <div class="small text-danger mt-1">{{ $msg->failure_reason }}</div>
                            @endif
                        </div>

                        {{-- Status badge (outbound) --}}
                        <div class="flex-shrink-0 text-end">
                            @if(!$isInbound && $msg->status)
                                <span class="badge bg-{{ $msg->status->color() }}" style="font-size:.7rem;">
                                    {{ $msg->status->label() }}
                                </span>
                            @endif
                        </div>
                    </div>
                </button>
            @endforeach
        </div>

        {{ $messages->links() }}
    @endif

    {{-- ── Offcanvas: full message view ────────────────────────────────────── --}}
    <div class="offcanvas offcanvas-end"
         id="ct-offcanvas"
         tabindex="-1"
         aria-labelledby="ct-offcanvas-label"
         style="width: min(700px, 95vw);"
         x-on:hidden.bs.offcanvas="$wire.closeMessage()">

        @if($openMessage)
            @php
                $isInbound = $openMessage->direction?->value === 'inbound';
                $isEmail   = $openMessage->channel?->value === 'email';
            @endphp

            {{-- ── Offcanvas header ── --}}
            <div class="offcanvas-header border-bottom flex-column align-items-start gap-1 pb-2">
                <div class="d-flex w-100 align-items-start justify-content-between gap-2">
                    <div class="d-flex align-items-center gap-2 overflow-hidden">
                        @if($isInbound)
                            <i class="mdi mdi-arrow-bottom-left text-primary flex-shrink-0"></i>
                        @else
                            <i class="mdi mdi-arrow-top-right text-success flex-shrink-0"></i>
                        @endif
                        <h5 class="offcanvas-title mb-0 text-truncate" id="ct-offcanvas-label" style="font-size:.95rem;">
                            {{ $openMessage->subject ?: '(no subject)' }}
                        </h5>
                    </div>
                    <button type="button" class="btn-close flex-shrink-0 mt-1" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>

                {{-- ── Meta grid ── --}}
                <table class="w-100" style="font-size:.82rem; border-collapse:collapse;">
                    @if($isInbound)
                        <tr>
                            <td class="text-muted pe-3 py-0" style="white-space:nowrap; width:1%;">From</td>
                            <td class="py-0 fw-medium">{{ $openMessage->from_email ?? '—' }}</td>
                        </tr>
                    @else
                        <tr>
                            <td class="text-muted pe-3 py-0" style="white-space:nowrap; width:1%;">To</td>
                            <td class="py-0 fw-medium">
                                {{ $isEmail ? ($openMessage->recipient_email ?? '—') : ($openMessage->recipient_phone ?? '—') }}
                                @if($openMessage->recipient_name)
                                    <span class="text-muted fw-normal ms-1">({{ $openMessage->recipient_name }})</span>
                                @endif
                            </td>
                        </tr>
                        @if($openMessage->senderEmail)
                            <tr>
                                <td class="text-muted pe-3 py-0" style="white-space:nowrap;">From</td>
                                <td class="py-0">{{ $openMessage->senderEmail->email }}</td>
                            </tr>
                        @endif
                    @endif
                    <tr>
                        <td class="text-muted pe-3 py-0" style="white-space:nowrap;">Date</td>
                        <td class="py-0">{{ $openMessage->created_at?->format('d M Y, H:i') }}</td>
                    </tr>
                    @if(!$isInbound && $openMessage->template)
                        <tr>
                            <td class="text-muted pe-3 py-0" style="white-space:nowrap;">Template</td>
                            <td class="py-0">{{ $openMessage->template->name }}</td>
                        </tr>
                    @endif
                    @if(!$isInbound && $openMessage->creator)
                        <tr>
                            <td class="text-muted pe-3 py-0" style="white-space:nowrap;">Sent by</td>
                            <td class="py-0">{{ $openMessage->creator->name }}</td>
                        </tr>
                    @endif
                    @if(!$isInbound && $openMessage->origin_type && !$openMessage->creator)
                        <tr>
                            <td class="text-muted pe-3 py-0" style="white-space:nowrap;">Origin</td>
                            <td class="py-0">{{ $openMessage->origin_type->label() }}</td>
                        </tr>
                    @endif
                </table>

                {{-- ── Badges row ── --}}
                <div class="d-flex flex-wrap gap-1 mt-1">
                    @if(!$isInbound && $openMessage->status)
                        <span class="badge bg-{{ $openMessage->status->color() }}" style="font-size:.72rem;">
                            {{ $openMessage->status->label() }}
                        </span>
                    @endif
                    @if($isInbound && $openMessage->classification === 'dsar_response')
                        <span class="badge bg-primary-subtle text-primary border border-primary border-opacity-25" style="font-size:.72rem;">
                            DSAR Response
                        </span>
                    @elseif($isInbound && $openMessage->classification === 'generic')
                        <span class="badge bg-secondary-subtle text-secondary border" style="font-size:.72rem;">Generic</span>
                    @elseif($isInbound && $openMessage->classification)
                        <span class="badge bg-secondary-subtle text-secondary border" style="font-size:.72rem;">{{ $openMessage->classification }}</span>
                    @endif
                    @if($openMessage->classification_confidence)
                        <span class="badge bg-light text-muted border" style="font-size:.72rem;">
                            {{ ucfirst($openMessage->classification_confidence) }} confidence
                        </span>
                    @endif
                    @if($openMessage->channel)
                        <span class="badge bg-light text-muted border" style="font-size:.72rem;">
                            <i class="{{ $openMessage->channel->icon() }} me-1"></i>{{ ucfirst($openMessage->channel->value) }}
                        </span>
                    @endif
                    @if($openMessage->provider)
                        <span class="badge bg-light text-muted border" style="font-size:.72rem;">{{ ucfirst($openMessage->provider->value) }}</span>
                    @endif
                </div>

                {{-- Synapse reasoning --}}
                @if($openMessage->classification_notes)
                    <div class="text-muted fst-italic mt-1" style="font-size:.77rem; line-height:1.4;">
                        <i class="mdi mdi-brain me-1" style="color:#7c3aed;"></i>{{ $openMessage->classification_notes }}
                    </div>
                @endif

                {{-- Failure reason --}}
                @if($openMessage->failure_reason)
                    <div class="alert alert-danger py-1 px-2 mb-0 w-100 mt-1" style="font-size:.8rem;">
                        <i class="mdi mdi-alert-circle-outline me-1"></i>{{ $openMessage->failure_reason }}
                    </div>
                @endif
            </div>

            {{-- ── Scrollable body ── --}}
            <div class="offcanvas-body p-0 d-flex flex-column" style="overflow-y:auto;">

                {{-- Delivery tracking (outbound only) --}}
                @if(!$isInbound && $openMessage->events->isNotEmpty())
                    <div class="border-bottom px-3 py-2 bg-light flex-shrink-0">
                        <div class="text-muted small fw-semibold mb-2 text-uppercase" style="font-size:.7rem; letter-spacing:.05em;">
                            <i class="mdi mdi-timeline-check-outline me-1"></i>Delivery Tracking
                        </div>
                        <div class="d-flex flex-column gap-1">
                            @foreach($openMessage->events as $event)
                                @php
                                    $ip        = $event->payload['ip'] ?? null;
                                    $ua        = $event->payload['useragent'] ?? $event->payload['user_agent'] ?? null;
                                    $url       = $event->payload['url'] ?? null;
                                    $reason    = $event->payload['reason'] ?? $event->payload['response'] ?? null;
                                @endphp
                                <div class="d-flex align-items-start gap-2" style="font-size:.8rem;">
                                    <span class="badge bg-{{ $event->event_type->color() }}-subtle text-{{ $event->event_type->color() }} border flex-shrink-0"
                                          style="font-size:.68rem; min-width:80px; text-align:center;">
                                        {{ $event->event_type->label() }}
                                    </span>
                                    <div>
                                        <div class="text-muted">{{ $event->occurred_at?->format('d M Y, H:i') }}</div>
                                        @if($ip || $ua)
                                            <div class="text-muted" style="font-size:.72rem;">
                                                @if($ip)<span>{{ $ip }}</span>@endif
                                                @if($ua)<span class="ms-1 text-truncate d-inline-block" style="max-width:380px; vertical-align:bottom;">{{ $ua }}</span>@endif
                                            </div>
                                        @endif
                                        @if($url)
                                            <div class="text-muted" style="font-size:.72rem;">
                                                <i class="mdi mdi-link-variant me-1"></i>{{ Str::limit($url, 60) }}
                                            </div>
                                        @endif
                                        @if($reason)
                                            <div class="text-danger" style="font-size:.72rem;">{{ Str::limit($reason, 100) }}</div>
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @elseif(!$isInbound)
                    {{-- Timestamps summary if no detailed events --}}
                    @php
                        $stamps = array_filter([
                            'Queued'    => $openMessage->queued_at,
                            'Sent'      => $openMessage->sent_at,
                            'Delivered' => $openMessage->delivered_at,
                            'Opened'    => $openMessage->opened_at,
                            'Failed'    => $openMessage->failed_at,
                        ]);
                    @endphp
                    @if(count($stamps) > 0)
                        <div class="border-bottom px-3 py-2 bg-light flex-shrink-0">
                            <div class="text-muted small fw-semibold mb-2 text-uppercase" style="font-size:.7rem; letter-spacing:.05em;">
                                <i class="mdi mdi-timeline-check-outline me-1"></i>Delivery Timeline
                            </div>
                            <div class="d-flex flex-wrap gap-3" style="font-size:.8rem;">
                                @foreach($stamps as $label => $ts)
                                    <div>
                                        <span class="text-muted">{{ $label }}:</span>
                                        <span class="ms-1">{{ $ts->format('d M Y H:i') }}</span>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endif
                @endif

                {{-- Email body --}}
                <div class="flex-grow-1 p-3">
                    @if($openMessage->body_html)
                        <iframe
                            srcdoc="{!! htmlspecialchars($openMessage->body_html) !!}"
                            sandbox="allow-same-origin"
                            style="width:100%; min-height:400px; border:0; display:block;"
                            onload="this.style.height = Math.min(this.contentDocument.documentElement.scrollHeight + 20, 800) + 'px'"
                        ></iframe>
                    @elseif($openMessage->body_text)
                        <pre style="white-space:pre-wrap; font-family:inherit; font-size:.88rem; margin:0; line-height:1.6;">{{ $openMessage->body_text }}</pre>
                    @else
                        <p class="text-muted text-center py-5 mb-0">
                            <i class="mdi mdi-email-off-outline d-block mb-2" style="font-size:2rem; opacity:.4;"></i>
                            No message body.
                        </p>
                    @endif
                </div>

                {{-- Attachments --}}
                @if($openMessage->attachments->isNotEmpty())
                    <div class="border-top px-3 py-3 flex-shrink-0">
                        <div class="text-muted small fw-semibold mb-2 text-uppercase" style="font-size:.7rem; letter-spacing:.05em;">
                            <i class="mdi mdi-paperclip me-1"></i>Attachments ({{ $openMessage->attachments->count() }})
                        </div>
                        <div class="d-flex flex-column gap-2">
                            @foreach($openMessage->attachments as $att)
                                @php
                                    $attMime = strtolower($att->mime ?? '');
                                    $attName = strtolower($att->filename ?? '');
                                    $attCanPreview = str_starts_with($attMime, 'image/')
                                        || str_contains($attMime, 'pdf')
                                        || (bool) preg_match('/\.(jpe?g|png|gif|webp|bmp|svg|pdf)$/', $attName);
                                @endphp
                                <div class="border rounded px-3 py-2 d-flex align-items-center gap-2 bg-light" style="font-size:.83rem;">
                                    <i class="mdi mdi-file-outline text-muted flex-shrink-0" style="font-size:1.1rem;"></i>
                                    <div class="flex-grow-1 overflow-hidden">
                                        <div class="fw-medium text-truncate">{{ $att->filename }}</div>
                                        <div class="text-muted" style="font-size:.73rem;">
                                            {{ $att->mime ?? 'unknown type' }}
                                            @if($att->size)
                                                &nbsp;&middot;&nbsp;{{ number_format($att->size / 1024, 1) }} KB
                                            @endif
                                            @if($att->extraction_status === 'completed')
                                                &nbsp;&middot;&nbsp;<span class="text-success"><i class="mdi mdi-text-box-check-outline"></i> Text extracted</span>
                                            @endif
                                        </div>
                                        @if($att->extraction_status === 'completed' && !empty($att->extracted_text))
                                            <details class="mt-1">
                                                <summary class="text-muted" style="font-size:.73rem; cursor:pointer;">View extracted text</summary>
                                                <pre class="bg-white border rounded p-2 mt-1 mb-0" style="font-size:.73rem; white-space:pre-wrap; max-height:160px; overflow-y:auto; font-family:inherit;">{{ $att->extracted_text }}</pre>
                                            </details>
                                        @endif
                                    </div>
                                    <div class="d-flex align-items-center gap-1 flex-shrink-0">
                                        @if($attCanPreview)
                                            <a href="{{ route('inbox.attachment.preview', $att) }}"
                                               target="_blank" rel="noopener"
                                               class="btn btn-sm btn-outline-secondary py-0 px-1"
                                               title="Preview in new tab">
                                                <i class="mdi mdi-eye-outline"></i>
                                            </a>
                                        @endif
                                        <a href="{{ route('inbox.attachment.download', $att) }}"
                                           class="btn btn-sm btn-outline-secondary py-0 px-1"
                                           title="Download">
                                            <i class="mdi mdi-download"></i>
                                        </a>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif

                {{-- Provider message ID / thread info --}}
                @if($openMessage->provider_message_id || $openMessage->thread_key)
                    <div class="border-top px-3 py-2 bg-light flex-shrink-0" style="font-size:.73rem; color:#6c757d;">
                        @if($openMessage->provider_message_id)
                            <div><span class="fw-medium">Provider ID:</span> {{ $openMessage->provider_message_id }}</div>
                        @endif
                        @if($openMessage->thread_key)
                            <div><span class="fw-medium">Thread:</span> {{ $openMessage->thread_key }}</div>
                        @endif
                    </div>
                @endif

            </div>{{-- /offcanvas-body --}}

        @else
            {{-- Loading skeleton --}}
            <div class="offcanvas-header border-bottom">
                <h5 class="offcanvas-title text-muted">Loading…</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
            </div>
            <div class="offcanvas-body d-flex align-items-center justify-content-center text-muted">
                <div class="spinner-border spinner-border-sm me-2"></div> Loading message…
            </div>
        @endif
    </div>{{-- /offcanvas --}}

</div>
