<div class="container-fluid py-4">
    <x-title>
        Communications log
        <x-slot:buttons>
            <button class="btn btn-outline-secondary btn-sm" wire:click="clearFilters">
                <i class="mdi mdi-filter-off-outline me-1"></i>Clear filters
            </button>
        </x-slot:buttons>
    </x-title>

    @if(session('log_success'))
        <div class="alert alert-success alert-dismissible fade show">
            {{ session('log_success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif
    @if(session('log_error'))
        <div class="alert alert-danger alert-dismissible fade show">
            {{ session('log_error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    {{-- Stats summary cards --}}
    <div class="row g-2 mb-3">
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Total</div>
                    <div class="fs-4 fw-bold">{{ number_format($stats['total']) }}</div>
                    <div class="small text-muted">
                        <i class="mdi mdi-email-outline"></i> {{ number_format($stats['by_channel']['email'] ?? 0) }}
                        &middot;
                        <i class="mdi mdi-message-text-outline"></i> {{ number_format($stats['by_channel']['sms'] ?? 0) }}
                    </div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Queued / Sending</div>
                    <div class="fs-4 fw-bold text-info">{{ number_format($stats['queued']) }}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Delivered</div>
                    <div class="fs-4 fw-bold text-success">{{ number_format($stats['delivered']) }}</div>
                    <div class="small text-muted">{{ $stats['delivery_rate'] }}% of sent</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Opens</div>
                    <div class="fs-4 fw-bold text-success">{{ number_format($stats['opened']) }}</div>
                    <div class="small text-muted">{{ $stats['open_rate'] }}% of delivered</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Clicks</div>
                    <div class="fs-4 fw-bold text-success">{{ number_format($stats['clicked']) }}</div>
                    <div class="small text-muted">{{ $stats['click_rate'] }}% of delivered</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Bounces</div>
                    <div class="fs-4 fw-bold text-danger">{{ number_format($stats['bounced']) }}</div>
                    <div class="small text-muted">{{ $stats['bounce_rate'] }}% bounce rate</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg">
            <div class="card border-0 bg-light h-100">
                <div class="card-body py-2 px-3">
                    <div class="text-muted small text-uppercase">Failed / Suppressed</div>
                    <div class="fs-4 fw-bold text-danger">{{ number_format($stats['failed'] + $stats['suppressed']) }}</div>
                </div>
            </div>
        </div>
    </div>

    {{-- Filter row --}}
    <div class="card mb-3">
        <div class="card-body py-3">
            <div class="row g-2 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Search</label>
                    <input type="search" class="form-control form-control-sm"
                           wire:model.live.debounce.500ms="search"
                           placeholder="Subject, body, recipient, provider id...">
                </div>
                <div class="col-md-2">
                    <label class="form-label small text-muted mb-1">Channel</label>
                    <select class="form-select form-select-sm" wire:model.live="channel">
                        <option value="">All</option>
                        <option value="email">Email</option>
                        <option value="sms">SMS</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small text-muted mb-1">Status</label>
                    <select class="form-select form-select-sm" wire:model.live="status">
                        <option value="">All</option>
                        @foreach($statuses as $s)
                            <option value="{{ $s->value }}">{{ $s->label() }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small text-muted mb-1">Template</label>
                    <select class="form-select form-select-sm" wire:model.live="templateId">
                        <option value="">All</option>
                        @foreach($templates as $t)
                            <option value="{{ $t->id }}">{{ $t->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small text-muted mb-1">Origin</label>
                    <select class="form-select form-select-sm" wire:model.live="origin">
                        <option value="">All</option>
                        @foreach($origins as $o)
                            <option value="{{ $o->value }}">{{ $o->label() }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-1">
                    <label class="form-label small text-muted mb-1">From</label>
                    <input type="date" class="form-control form-control-sm" wire:model.live="dateFrom">
                </div>
                <div class="col-md-1">
                    <label class="form-label small text-muted mb-1">To</label>
                    <input type="date" class="form-control form-control-sm" wire:model.live="dateTo">
                </div>

                <div class="col-md-3 mt-2">
                    <label class="form-label small text-muted mb-1">Email sender</label>
                    <select class="form-select form-select-sm" wire:model.live="senderEmailId">
                        <option value="">All email senders</option>
                        @foreach($emailSenders as $s)
                            <option value="{{ $s->id }}">{{ $s->display_name }} &lt;{{ $s->email_address }}&gt;</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mt-2">
                    <label class="form-label small text-muted mb-1">SMS sender</label>
                    <select class="form-select form-select-sm" wire:model.live="smsSenderId">
                        <option value="">All SMS senders</option>
                        @foreach($smsSenders as $s)
                            <option value="{{ $s->id }}">{{ $s->label }} ({{ $s->value }})</option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>
    </div>

    {{-- Results table --}}
    <div class="card">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>When</th>
                        <th>Channel</th>
                        <th>Subject / preview</th>
                        <th>Recipient</th>
                        <th>Sender</th>
                        <th>Template</th>
                        <th>By / Origin</th>
                        <th>Status</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($messages as $m)
                        <tr wire:key="logmsg-{{ $m->id }}"
                            style="cursor:pointer;"
                            wire:click="view({{ $m->id }})">
                            <td class="small text-nowrap">
                                <div>{{ $m->created_at?->format('Y-m-d') }}</div>
                                <div class="text-muted">{{ $m->created_at?->format('H:i:s') }}</div>
                            </td>
                            <td>
                                <i class="{{ $m->channel?->icon() }}" title="{{ $m->channel?->label() }}"></i>
                            </td>
                            <td>
                                <div class="fw-semibold">
                                    {{ \Illuminate\Support\Str::limit($m->subject ?: $m->body_text, 70) ?: '—' }}
                                </div>
                                @if($m->failure_reason)
                                    <div class="small text-danger">{{ \Illuminate\Support\Str::limit($m->failure_reason, 100) }}</div>
                                @endif
                            </td>
                            <td class="small">
                                <div>{{ $m->recipient_name ?? '—' }}</div>
                                <div class="text-muted">{{ $m->recipient_email ?? $m->recipient_phone }}</div>
                                @php $linkedUrl = $m->messageableUrl(); $linkedLabel = $m->messageableLabel(); @endphp
                                @if($linkedLabel)
                                    @if($linkedUrl)
                                        <a wire:navigate href="{{ $linkedUrl }}"
                                           wire:navigate
                                           class="small text-decoration-none"
                                           onclick="event.stopPropagation();">
                                            <i class="mdi mdi-link-variant"></i> {{ $linkedLabel }}
                                        </a>
                                    @else
                                        <span class="small text-muted">{{ $linkedLabel }}</span>
                                    @endif
                                @endif
                            </td>
                            <td class="small text-muted">
                                {{ $m->sender_display ?: $m->sender_value ?: '—' }}
                            </td>
                            <td class="small">
                                {{ $m->template?->name ?? '—' }}
                            </td>
                            <td class="small">
                                @if($m->creator)
                                    {{ $m->creator->name }}
                                @endif
                                @if($m->origin_type)
                                    <div class="text-muted">{{ $m->origin_type->label() }}</div>
                                @endif
                            </td>
                            <td>
                                <span class="badge bg-{{ $m->status?->color() }}">
                                    {{ $m->status?->label() }}
                                </span>
                            </td>
                            <td class="text-end">
                                <i class="mdi mdi-chevron-right text-muted"></i>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9" class="text-center py-5 text-muted">
                                <i class="mdi mdi-email-search-outline" style="font-size:2rem;"></i>
                                <div>No communications match these filters.</div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <div class="card-footer">
            {{ $messages->links() }}
        </div>
    </div>

    {{-- Detail drawer --}}
    @if($detail)
        <div class="offcanvas offcanvas-end show" tabindex="-1"
             style="visibility: visible; --bs-offcanvas-width: 760px;">
            <div class="offcanvas-header border-bottom">
                <div>
                    <h5 class="offcanvas-title mb-0">
                        <i class="{{ $detail->channel?->icon() }} me-1"></i>
                        {{ $detail->subject ?: \Illuminate\Support\Str::limit($detail->body_text, 60) ?: 'Message #' . $detail->id }}
                    </h5>
                    <div class="small text-muted mt-1">
                        <span class="badge bg-{{ $detail->status?->color() }}">{{ $detail->status?->label() }}</span>
                        &middot; {{ $detail->created_at?->format('Y-m-d H:i:s') }}
                        &middot; ID #{{ $detail->id }}
                    </div>
                </div>
                <button type="button" class="btn-close" wire:click="closeDetail"></button>
            </div>
            <div class="offcanvas-body">

                {{-- Metadata --}}
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <div class="small text-muted">Recipient</div>
                        <div class="fw-semibold">{{ $detail->recipient_name ?? '—' }}</div>
                        <div class="small">{{ $detail->recipient_email ?? $detail->recipient_phone }}</div>
                    </div>
                    <div class="col-6">
                        <div class="small text-muted">Sender</div>
                        <div class="fw-semibold">{{ $detail->sender_display ?? '—' }}</div>
                        <div class="small">{{ $detail->sender_value }}</div>
                        @if($detail->reply_to)
                            <div class="small text-muted">Reply-to: {{ $detail->reply_to }}</div>
                        @endif
                    </div>
                    <div class="col-6">
                        <div class="small text-muted">Template</div>
                        <div>{{ $detail->template?->name ?? '—' }}</div>
                    </div>
                    <div class="col-6">
                        <div class="small text-muted">Origin</div>
                        <div>{{ $detail->origin_type?->label() ?? '—' }}</div>
                        @if($detail->creator)
                            <div class="small">by {{ $detail->creator->name }}</div>
                        @endif
                    </div>
                    <div class="col-6">
                        <div class="small text-muted">Provider</div>
                        <div>{{ $detail->provider?->label() ?? '—' }}</div>
                        @if($detail->provider_message_id)
                            <div class="small">
                                <code>{{ $detail->provider_message_id }}</code>
                            </div>
                        @endif
                    </div>
                    <div class="col-6">
                        <div class="small text-muted">Linked record</div>
                        @php
                            $detailUrl = $detail->messageableUrl();
                            $detailLabel = $detail->messageableLabel();
                        @endphp
                        @if($detailLabel)
                            @if($detailUrl)
                                <a wire:navigate href="{{ $detailUrl }}" wire:navigate>
                                    <i class="mdi mdi-open-in-new"></i> {{ $detailLabel }}
                                </a>
                            @else
                                <div>{{ $detailLabel }}</div>
                            @endif
                        @else
                            <div class="text-muted">—</div>
                        @endif
                    </div>
                </div>

                {{-- Lifecycle timestamps --}}
                <div class="mb-3">
                    <div class="d-flex flex-wrap gap-2 small">
                        @foreach([
                            'queued_at' => 'Queued',
                            'sent_at' => 'Sent',
                            'delivered_at' => 'Delivered',
                            'opened_at' => 'Opened',
                            'failed_at' => 'Failed',
                        ] as $col => $label)
                            @if($detail->{$col})
                                <span class="badge bg-light text-dark border">
                                    <strong>{{ $label }}:</strong>
                                    {{ $detail->{$col}?->format('Y-m-d H:i:s') }}
                                </span>
                            @endif
                        @endforeach
                    </div>
                </div>

                @if($detail->failure_reason)
                    <div class="alert alert-danger small">
                        <strong>Failure:</strong> {{ $detail->failure_reason }}
                    </div>
                @endif

                {{-- Tabs: content / events / payload --}}
                <ul class="nav nav-tabs" role="tablist">
                    <li class="nav-item"><a wire:navigate class="nav-link active" data-bs-toggle="tab" href="#tab-content">Content</a></li>
                    <li class="nav-item"><a wire:navigate class="nav-link" data-bs-toggle="tab" href="#tab-events">Events ({{ $detail->events->count() }})</a></li>
                    <li class="nav-item"><a wire:navigate class="nav-link" data-bs-toggle="tab" href="#tab-placeholders">Placeholders</a></li>
                    <li class="nav-item"><a wire:navigate class="nav-link" data-bs-toggle="tab" href="#tab-payload">Provider payload</a></li>
                </ul>
                <div class="tab-content border border-top-0 rounded-bottom p-3 bg-white">

                    <div class="tab-pane fade show active" id="tab-content">
                        @if($detail->subject)
                            <div class="mb-2">
                                <small class="text-muted d-block">Subject</small>
                                <strong>{{ $detail->subject }}</strong>
                            </div>
                        @endif

                        @if($detail->body_html)
                            <div class="mb-3">
                                <small class="text-muted d-block">HTML body</small>
                                <div class="border rounded p-3 bg-light"
                                     style="max-height: 360px; overflow:auto;">
                                    {!! $detail->body_html !!}
                                </div>
                            </div>
                        @endif

                        @if($detail->body_text)
                            <div class="mb-3">
                                <small class="text-muted d-block">Plain text body</small>
                                <pre class="border rounded p-3 bg-light mb-0"
                                     style="max-height: 240px; overflow:auto; white-space: pre-wrap; font-family: inherit; font-size: 0.9rem;">{{ $detail->body_text }}</pre>
                            </div>
                        @endif

                        @if($detail->attachments->isNotEmpty())
                            <div>
                                <small class="text-muted d-block mb-1">Attachments</small>
                                <ul class="list-group">
                                    @foreach($detail->attachments as $a)
                                        <li class="list-group-item small d-flex justify-content-between">
                                            <span>
                                                <i class="mdi mdi-paperclip me-1"></i>{{ $a->filename }}
                                                <span class="text-muted">({{ $a->mime }})</span>
                                            </span>
                                            <span class="text-muted">{{ number_format(($a->size ?? 0) / 1024, 1) }} KB</span>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif
                    </div>

                    <div class="tab-pane fade" id="tab-events">
                        @if($detail->events->isEmpty())
                            <div class="text-muted small py-3 text-center">No provider events received yet.</div>
                        @else
                            <ul class="list-unstyled mb-0">
                                @foreach($detail->events->sortByDesc('occurred_at') as $event)
                                    <li class="d-flex gap-2 mb-2 pb-2 border-bottom">
                                        <span class="badge bg-{{ $event->event_type->color() }} align-self-start">
                                            {{ $event->event_type->label() }}
                                        </span>
                                        <div class="flex-grow-1 small">
                                            <div>
                                                <strong>{{ $event->occurred_at?->format('Y-m-d H:i:s') }}</strong>
                                                @if($event->mapped_status)
                                                    &middot; status → {{ $event->mapped_status->label() }}
                                                @endif
                                            </div>
                                            @if($event->provider_event_id)
                                                <div class="text-muted">
                                                    <code>{{ $event->provider_event_id }}</code>
                                                </div>
                                            @endif
                                            @if(!empty($event->payload))
                                                <details class="mt-1">
                                                    <summary class="text-muted">payload</summary>
                                                    <pre class="bg-light p-2 rounded mt-1"
                                                         style="font-size: 0.75rem; max-height: 180px; overflow:auto;">{{ json_encode($event->payload, JSON_PRETTY_PRINT) }}</pre>
                                                </details>
                                            @endif
                                        </div>
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>

                    <div class="tab-pane fade" id="tab-placeholders">
                        @if(empty($detail->rendered_placeholders))
                            <div class="text-muted small py-3 text-center">No placeholders were resolved.</div>
                        @else
                            <table class="table table-sm small mb-0">
                                <thead>
                                    <tr><th>Token</th><th>Resolved value</th></tr>
                                </thead>
                                <tbody>
                                    @foreach($detail->rendered_placeholders as $token => $value)
                                        <tr>
                                            <td><code>{{ $token }}</code></td>
                                            <td>{{ $value !== '' ? $value : '(empty)' }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @endif
                    </div>

                    <div class="tab-pane fade" id="tab-payload">
                        @if(empty($detail->provider_payload))
                            <div class="text-muted small py-3 text-center">No provider payload stored.</div>
                        @else
                            <pre class="bg-light p-3 rounded mb-0"
                                 style="font-size: 0.8rem; max-height: 360px; overflow:auto;">{{ json_encode($detail->provider_payload, JSON_PRETTY_PRINT) }}</pre>
                        @endif
                    </div>

                </div>

                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-outline-secondary" wire:click="closeDetail">Close</button>
                    @canany(['communications.send.email', 'communications.send.sms'])
                        @if($detail->template && $detail->messageable)
                            <button class="btn btn-primary"
                                    wire:click="resend({{ $detail->id }})"
                                    wire:confirm="Resend this message to {{ $detail->recipient_email ?? $detail->recipient_phone }}?">
                                <i class="mdi mdi-send-outline me-1"></i>Resend
                            </button>
                        @endif
                    @endcanany
                </div>
            </div>
        </div>
        <div class="offcanvas-backdrop fade show" wire:click="closeDetail"></div>
    @endif
</div>
