<div wire:poll.3000ms>

    @php
    $statusBadge = [
        'available'      => 'bg-success',
        'busy'           => 'bg-danger',
        'wrap_up'        => 'bg-warning text-dark',
        'do_not_disturb' => 'bg-secondary',
        'offline'        => 'bg-light text-muted border',
    ];
    $statusIcon = [
        'available'      => 'mdi-account-check-outline',
        'busy'           => 'mdi-phone-in-talk',
        'wrap_up'        => 'mdi-clipboard-text-outline',
        'do_not_disturb' => 'mdi-minus-circle-outline',
        'offline'        => 'mdi-account-off-outline',
    ];
    @endphp

    {{-- ── Page header ── --}}
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="mb-0">Dialler Dashboard</h4>
            <p class="text-muted mb-0 small">
                <i class="mdi mdi-refresh me-1"></i>
                Live &mdash; updates every 10 seconds
            </p>
        </div>
        <span class="badge bg-soft-success text-success border border-success border-opacity-25 px-3 py-2">
            <span class="spinner-grow spinner-grow-sm me-1 align-middle" style="width:.45rem;height:.45rem"></span>
            Live
        </span>
    </div>

    {{-- ══════════════════════════════════════════════════════ --}}
    {{-- ROW 1 — STAT CARDS                                     --}}
    {{-- ══════════════════════════════════════════════════════ --}}
    <div class="row g-3 mb-4">

        {{-- Active Calls --}}
        <div class="col-6 col-md-3">
            <div class="card h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="avatar-sm rounded bg-soft-success d-flex align-items-center justify-content-center flex-shrink-0">
                        <i class="mdi mdi-phone-in-talk font-18 text-success"></i>
                    </div>
                    <div class="min-w-0">
                        <p class="text-muted mb-0 small text-nowrap">Active Calls</p>
                        <h3 class="mb-0 fw-bold">{{ $activeCalls->count() }}</h3>
                    </div>
                </div>
            </div>
        </div>

        {{-- Available Agents --}}
        <div class="col-6 col-md-3">
            <div class="card h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="avatar-sm rounded bg-soft-primary d-flex align-items-center justify-content-center flex-shrink-0">
                        <i class="mdi mdi-account-group-outline font-18 text-primary"></i>
                    </div>
                    <div class="min-w-0">
                        <p class="text-muted mb-0 small text-nowrap">Available Agents</p>
                        <h3 class="mb-0 fw-bold">
                            {{ $availableCount }}
                            <span class="text-muted fw-normal" style="font-size:.9rem">
                                / {{ $workspaceAgentCount }}
                            </span>
                        </h3>
                    </div>
                </div>
            </div>
        </div>

        {{-- Missed Today --}}
        <div class="col-6 col-md-3">
            <div class="card h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="avatar-sm rounded bg-soft-warning d-flex align-items-center justify-content-center flex-shrink-0">
                        <i class="mdi mdi-phone-missed font-18 text-warning"></i>
                    </div>
                    <div class="min-w-0">
                        <p class="text-muted mb-0 small text-nowrap">Missed Today</p>
                        <h3 class="mb-0 fw-bold">{{ $missedCalls->count() }}</h3>
                    </div>
                </div>
            </div>
        </div>

        {{-- Unlistened Voicemails --}}
        <div class="col-6 col-md-3">
            <div class="card h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="avatar-sm rounded bg-soft-danger d-flex align-items-center justify-content-center flex-shrink-0">
                        <i class="mdi mdi-voicemail font-18 text-danger"></i>
                    </div>
                    <div class="min-w-0">
                        <p class="text-muted mb-0 small text-nowrap">Voicemails</p>
                        <h3 class="mb-0 fw-bold">{{ $voicemails->count() }}</h3>
                    </div>
                </div>
            </div>
        </div>

    </div>

    {{-- ══════════════════════════════════════════════════════ --}}
    {{-- ROW 2 — AGENT AVAILABILITY + ACTIVE CALLS             --}}
    {{-- ══════════════════════════════════════════════════════ --}}
    <div class="row g-3 mb-3">

        {{-- Agent Availability + Call Log --}}
        <div class="col-md-5">
            <div class="d-flex flex-column gap-3">
            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-account-multiple-outline me-1 text-muted"></i>
                        Agent Availability
                    </h5>
                    <span class="badge bg-soft-secondary text-secondary">
                        {{ $agentStatuses->count() }} agents
                    </span>
                </div>
                <div class="card-body p-0">
                    @if($agentStatuses->isEmpty())
                        <div class="text-center text-muted py-5">
                            <i class="mdi mdi-account-off-outline d-block mb-2" style="font-size:2rem"></i>
                            No agents registered
                        </div>
                    @else
                        <div class="table-responsive" style="max-height:320px;overflow-y:auto">
                            <table class="table table-sm table-centered table-hover mb-0">
                                <thead class="table-light" style="position:sticky;top:0;z-index:1">
                                    <tr>
                                        <th>Agent</th>
                                        @if($canViewAllWorkspaces)
                                            <th>Workspace</th>
                                        @endif
                                        <th>Status</th>
                                        <th class="text-nowrap">Since</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($agentStatuses as $s)
                                        <tr>
                                            <td class="fw-medium">
                                                <i class="mdi {{ $statusIcon[$s->status] ?? 'mdi-account-outline' }} me-1 text-muted"></i>
                                                {{ $s->agent?->name_first }} {{ $s->agent?->name_last }}
                                            </td>
                                            @if($canViewAllWorkspaces)
                                                <td class="text-muted small text-nowrap">
                                                    {{ $s->solicitor?->name ?? '—' }}
                                                </td>
                                            @endif
                                            <td>
                                                <span class="badge {{ $statusBadge[$s->status] ?? 'bg-secondary' }}">
                                                    {{ str_replace('_', ' ', ucwords($s->status)) }}
                                                </span>
                                            </td>
                                            <td class="text-muted small text-nowrap">
                                                {{ $s->status_changed_at?->diffForHumans() ?? '—' }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>

            {{-- Call Log --}}
            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-phone-log me-1 text-primary"></i>
                        Call Log
                    </h5>
                    <span class="badge bg-soft-primary text-primary">{{ $callLogs->total() }} calls</span>
                </div>

                <div class="card-body border-bottom py-2">
                    <div class="row g-2">
                        <div class="col-12">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text"><i class="mdi mdi-magnify"></i></span>
                                <input type="search"
                                       wire:model.live.debounce.400ms="callSearch"
                                       class="form-control"
                                       placeholder="Search caller or number...">
                                <button type="button"
                                        wire:click="resetCallFilters"
                                        class="btn btn-outline-secondary"
                                        title="Reset filters">
                                    <i class="mdi mdi-filter-remove-outline"></i>
                                </button>
                            </div>
                        </div>

                        <div class="col-6">
                            <select wire:model.live="callDirection" class="form-select form-select-sm">
                                <option value="">All directions</option>
                                <option value="inbound">Inbound</option>
                                <option value="outbound">Outbound</option>
                            </select>
                        </div>

                        <div class="col-6">
                            <select wire:model.live="callerType" class="form-select form-select-sm">
                                <option value="">All callers</option>
                                <option value="known">Known clients</option>
                                <option value="unknown">Unknown callers</option>
                            </select>
                        </div>

                        <div class="col-12">
                            <select wire:model.live="callStatus" class="form-select form-select-sm">
                                <option value="">All statuses</option>
                                @foreach(\App\Enum\Communication\CommunicationStatus::cases() as $status)
                                    <option value="{{ $status->value }}">
                                        {{ str($status->value)->replace('_', ' ')->title() }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="col-6">
                            <input type="date"
                                   wire:model.live="callDateFrom"
                                   class="form-control form-control-sm"
                                   title="From date">
                        </div>
                        <div class="col-6">
                            <input type="date"
                                   wire:model.live="callDateTo"
                                   class="form-control form-control-sm"
                                   title="To date">
                        </div>
                    </div>
                </div>

                <div class="card-body p-0">
                    <div wire:loading.flex
                         wire:target="callSearch,callDirection,callerType,callStatus,callDateFrom,callDateTo,resetCallFilters"
                         class="align-items-center justify-content-center gap-2 text-muted py-2 border-bottom">
                        <span class="spinner-border spinner-border-sm"></span>
                        Loading calls...
                    </div>

                    @if($callLogs->isEmpty())
                        <div class="text-center text-muted py-4">
                            <i class="mdi mdi-phone-off-outline d-block mb-2" style="font-size:1.75rem"></i>
                            No calls match the selected filters
                        </div>
                    @else
                        <div class="table-responsive" style="max-height:700px;overflow-y:auto">
                            <table class="table table-sm table-centered table-hover mb-0">
                                <thead class="table-light" style="position:sticky;top:0;z-index:1">
                                    <tr>
                                        <th>Caller</th>
                                        <th>Status</th>
                                        <th class="text-nowrap">Time</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($callLogs as $communication)
                                        @php
                                            $call = $communication->call;
                                            $communicable = $communication->communicable;
                                            $externalNumber = $communication->direction === 'inbound'
                                                ? $call?->from_number
                                                : $call?->to_number;
                                            $callerLabel = $communicable && method_exists($communicable, 'getCallableLabel')
                                                ? $communicable->getCallableLabel()
                                                : ($call?->target_label ?: 'Unknown caller');
                                            $clientUrl = $communicable instanceof \App\Models\Client\Client
                                                ? route('clients.show', $communicable)
                                                : null;
                                            $callStatusClass = match($communication->status) {
                                                'completed' => 'bg-soft-success text-success',
                                                'in_progress', 'ringing' => 'bg-soft-primary text-primary',
                                                'missed' => 'bg-soft-warning text-warning',
                                                'voicemail', 'failed' => 'bg-soft-danger text-danger',
                                                default => 'bg-soft-secondary text-secondary',
                                            };
                                        @endphp
                                        <tr wire:key="call-log-{{ $communication->id }}">
                                            <td style="min-width:145px">
                                                <div class="d-flex align-items-center gap-2">
                                                    <span class="avatar-xs rounded-circle d-flex align-items-center justify-content-center {{ $communication->direction === 'inbound' ? 'bg-soft-primary text-primary' : 'bg-soft-secondary text-secondary' }}">
                                                        <i class="mdi {{ $communication->direction === 'inbound' ? 'mdi-phone-incoming' : 'mdi-phone-outgoing' }}"></i>
                                                    </span>
                                                    <div class="min-w-0">
                                                        <div class="fw-medium text-truncate" style="max-width:155px">
                                                            @if($clientUrl)
                                                                <a href="{{ $clientUrl }}" class="text-body text-decoration-none">{{ $callerLabel }}</a>
                                                            @else
                                                                {{ $callerLabel }}
                                                            @endif
                                                        </div>
                                                        <div class="text-muted small font-monospace text-truncate" style="max-width:155px">
                                                            {{ $externalNumber ?: '—' }}
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge {{ $callStatusClass }}">
                                                    {{ str($communication->status)->replace('_', ' ')->title() }}
                                                </span>
                                            </td>
                                            <td class="text-muted small text-nowrap">
                                                <div>{{ $communication->started_at?->format('H:i') ?? '—' }}</div>
                                                <div style="font-size:.65rem">{{ $communication->started_at?->format('d M') }}</div>
                                            </td>
                                          
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>

                @if($callLogs->hasPages())
                    <div class="card-footer py-2">
                        {{ $callLogs->onEachSide(0)->links() }}
                    </div>
                @endif
            </div>
            </div>
        </div>

        {{-- Active Calls --}}
        <div class="col-md-7">
            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-phone-in-talk me-1 text-success"></i>
                        Active Calls
                    </h5>
                    @if($activeCalls->isNotEmpty())
                        <span class="badge bg-soft-success text-success">
                            <span class="spinner-grow spinner-grow-sm align-middle me-1"
                                  style="width:.4rem;height:.4rem"></span>
                            {{ $activeCalls->count() }} live
                        </span>
                    @endif
                </div>
                <div class="card-body p-0">
                    @if($activeCalls->isEmpty())
                        <div class="text-center text-muted py-5">
                            <i class="mdi mdi-phone-off-outline d-block mb-2" style="font-size:2rem"></i>
                            No active calls
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-sm table-centered table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Caller</th>
                                        <th>Agent</th>
                                        <th>Dir</th>
                                        <th class="text-nowrap">Started</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($activeCalls as $comm)
                                        @php
                                            $callerLabel = $comm->communicable && method_exists($comm->communicable, 'getCallableLabel')
                                                ? $comm->communicable->getCallableLabel()
                                                : ($comm->call?->from_number ?? $comm->preview ?? '—');
                                        @endphp
                                        <tr>
                                            <td class="fw-medium">{{ $callerLabel }}</td>
                                            <td class="text-muted small">
                                                {{ $comm->agent?->name_first }} {{ $comm->agent?->name_last }}
                                            </td>
                                            <td>
                                                @if($comm->direction === 'inbound')
                                                    <span class="badge bg-soft-primary text-primary">
                                                        <i class="mdi mdi-phone-incoming me-1"></i>In
                                                    </span>
                                                @else
                                                    <span class="badge bg-soft-secondary text-secondary">
                                                        <i class="mdi mdi-phone-outgoing me-1"></i>Out
                                                    </span>
                                                @endif
                                            </td>
                                            <td class="text-muted small text-nowrap">
                                                {{ $comm->started_at?->diffForHumans() ?? '—' }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>

    </div>

    {{-- ══════════════════════════════════════════════════════ --}}
    {{-- ROW 3 — MISSED CALLS + VOICEMAILS                     --}}
    {{-- ══════════════════════════════════════════════════════ --}}
    <div class="row g-3">

        {{-- Missed Calls --}}
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-phone-missed me-1 text-warning"></i>
                        Missed Calls
                        <span class="text-muted fw-normal" style="font-size:.8rem">today</span>
                    </h5>
                    @if($missedCalls->isNotEmpty())
                        <span class="badge bg-soft-warning text-warning">
                            {{ $missedCalls->count() }}
                        </span>
                    @endif
                </div>
                <div class="card-body p-0">
                    @if($missedCalls->isEmpty())
                        <div class="text-center text-muted py-5">
                            <i class="mdi mdi-check-circle-outline d-block mb-2 text-success" style="font-size:2rem"></i>
                            No missed calls today
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-sm table-centered table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Caller</th>
                                        <th>Number</th>
                                        <th class="text-nowrap">Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($missedCalls as $comm)
                                        @php
                                            $callerLabel = $comm->communicable && method_exists($comm->communicable, 'getCallableLabel')
                                                ? $comm->communicable->getCallableLabel()
                                                : '—';
                                        @endphp
                                        <tr>
                                            <td class="fw-medium">{{ $callerLabel }}</td>
                                            <td class="text-muted small font-monospace">
                                                {{ $comm->call?->from_number ?? '—' }}
                                            </td>
                                            <td class="text-muted small text-nowrap">
                                                {{ $comm->started_at?->format('H:i') ?? '—' }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>

        {{-- Voicemails --}}
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-voicemail me-1 text-danger"></i>
                        Voicemails
                        <span class="text-muted fw-normal" style="font-size:.8rem">unlistened</span>
                    </h5>
                    @if($voicemails->isNotEmpty())
                        <span class="badge bg-soft-danger text-danger">
                            {{ $voicemails->count() }}
                        </span>
                    @endif
                </div>
                <div class="card-body p-0">
                    @if($voicemails->isEmpty())
                        <div class="text-center text-muted py-5">
                            <i class="mdi mdi-check-circle-outline d-block mb-2 text-success" style="font-size:2rem"></i>
                            No unlistened voicemails
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-sm table-centered table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width:30%">Caller</th>
                                        <th>Recording</th>
                                        <th style="width:1%"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($voicemails as $vm)
                                        @php
                                            $communicable = $vm->communication?->communicable;
                                            $callerLabel  = $communicable && method_exists($communicable, 'getCallableLabel')
                                                ? $communicable->getCallableLabel()
                                                : ($vm->from_number ?? '—');
                                            $clientUrl    = $communicable instanceof \App\Models\Client\Client
                                                ? route('clients.show', $communicable)
                                                : null;
                                            $streamUrl    = $vm->recording
                                                ? route('recordings.stream', $vm->recording)
                                                : null;
                                            $durLabel     = $vm->recording?->duration_label
                                                ?? ($vm->duration
                                                    ? sprintf('%02d:%02d', floor($vm->duration / 60), $vm->duration % 60)
                                                    : '00:00');
                                        @endphp
                                        <tr wire:key="vm-{{ $vm->id }}">
                                            <td>
                                                <div class="fw-medium">
                                                    @if($clientUrl)
                                                        <a href="{{ $clientUrl }}"
                                                           class="text-body text-decoration-none">
                                                            {{ $callerLabel }}
                                                            <i class="mdi mdi-open-in-new text-muted ms-1"
                                                               style="font-size:.7rem"></i>
                                                        </a>
                                                    @else
                                                        {{ $callerLabel }}
                                                    @endif
                                                </div>
                                                <div class="text-muted small text-nowrap">
                                                    {{ $vm->received_at?->diffForHumans() ?? '—' }}
                                                </div>
                                            </td>
                                            <td>
                                                @if($vm->recording?->hasStoredFile())
                                                    <div x-data="waveformPlayer('{{ $streamUrl }}')"
                                                         x-init="init()"
                                                         @destroy="cleanup()">
                                                        <div class="d-flex align-items-center gap-2 px-2 py-1 rounded"
                                                             style="background:#f1f5f9">
                                                            <button @click="toggle()" :disabled="error"
                                                                    type="button"
                                                                    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 : '{{ $durLabel }}'">{{ $durLabel }}</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif($vm->recording)
                                                    <span class="text-muted small"
                                                          title="Recording is downloading from Twilio…">
                                                        <span class="spinner-border spinner-border-sm me-1"
                                                              style="width:.65rem;height:.65rem"></span>
                                                        Processing recording…
                                                    </span>
                                                @else
                                                    <span class="text-muted small">No recording available</span>
                                                @endif
                                            </td>
                                            <td class="text-end">
                                                <button wire:click="markListened({{ $vm->id }})"
                                                        wire:loading.attr="disabled"
                                                        wire:target="markListened({{ $vm->id }})"
                                                        class="btn btn-sm btn-outline-secondary py-0"
                                                        title="Mark as listened"
                                                        style="font-size:.75rem">
                                                    <span wire:loading.remove wire:target="markListened({{ $vm->id }})">
                                                        <i class="mdi mdi-check"></i>
                                                    </span>
                                                    <span wire:loading wire:target="markListened({{ $vm->id }})">
                                                        <span class="spinner-border spinner-border-sm"
                                                              style="width:.65rem;height:.65rem"></span>
                                                    </span>
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>

    </div>

</div>