<div>

    {{-- Header --}}
    <div class="row mb-4 align-items-center">
        <div class="col">
            <h2 class="fw-bold mb-0">
                <i class="bi bi-people text-primary me-2"></i>DSAR Report by Client
            </h2>
            <p class="text-muted mt-1 mb-0">Which clients have had all their DSARs returned and can be progressed onwards</p>
        </div>
    </div>

    {{-- Stat Cards --}}
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Clients with DSARs</p>
                    <h3 class="fw-bold mb-0">{{ number_format($statTotal) }}</h3>
                    <small class="text-muted">Have at least one sent DSAR</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Ready to Progress</p>
                    <h3 class="fw-bold mb-0 {{ $statReady > 0 ? 'text-success' : 'text-muted' }}">
                        {{ number_format($statReady) }}
                    </h3>
                    <small class="text-muted">All DSARs returned</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">With Outstanding</p>
                    <h3 class="fw-bold mb-0 {{ $statOutstanding > 0 ? 'text-warning' : 'text-muted' }}">
                        {{ number_format($statOutstanding) }}
                    </h3>
                    <small class="text-muted">Still awaiting responses</small>
                </div>
            </div>
        </div>
    </div>

    {{-- Clients Table --}}
    <div class="card">
        <div class="card-header bg-white d-flex flex-wrap gap-2 align-items-center">
            <span class="fw-semibold me-auto">
                <i class="bi bi-people me-2 text-primary"></i>Clients
            </span>

            <div class="form-check form-switch me-2">
                <input class="form-check-input" type="checkbox" id="readyOnly" wire:model.live="readyOnly">
                <label class="form-check-label small" for="readyOnly">Ready to progress only</label>
            </div>

            <select class="form-select form-select-sm w-auto" wire:model.live="sort">
                <option value="ready">Sort: Ready first</option>
                <option value="outstanding">Sort: Most outstanding</option>
                <option value="progress">Sort: Progress %</option>
                <option value="oldest">Sort: Oldest outstanding</option>
                <option value="name">Sort: Client name</option>
            </select>

            <input type="text"
                   class="form-control form-control-sm w-auto"
                   style="min-width: 220px"
                   wire:model.live.debounce.300ms="search"
                   placeholder="Search client…">
        </div>

        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Client</th>
                            <th style="min-width: 170px;">Returned</th>
                            <th class="text-end">Outstanding</th>
                            <th class="text-end" title="Outstanding DSARs the institution has acknowledged">Acknowledged</th>
                            <th class="text-end" title="Days since oldest outstanding DSAR was created">Oldest (days)</th>
                            <th>Status</th>
                            <th class="text-end"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($rows as $row)
                            <tr class="{{ $row->ready ? 'table-success' : ($row->failed > 0 ? 'table-warning' : '') }}">
                                <td>
                                    <a wire:navigate href="{{ route('clients.show', $row->client) }}"
                                       class="fw-semibold text-decoration-none">
                                        {{ $row->client->fullName }}
                                    </a>
                                    @if($row->client->reference)
                                        <div class="text-muted small font-monospace">{{ $row->client->reference }}</div>
                                    @endif
                                </td>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="progress flex-grow-1" style="height:6px;max-width:90px;">
                                            <div class="progress-bar bg-success" style="width:{{ $row->pct }}%"></div>
                                        </div>
                                        <small class="text-nowrap">{{ $row->returned }} / {{ $row->total }}</small>
                                    </div>
                                </td>
                                <td class="text-end">
                                    @if($row->outstanding > 0)
                                        <span class="badge bg-warning text-dark">{{ $row->outstanding }}</span>
                                    @else
                                        <span class="text-muted">0</span>
                                    @endif
                                </td>
                                <td class="text-end">
                                    @if($row->acknowledged > 0)
                                        <span class="badge bg-info">{{ $row->acknowledged }}</span>
                                    @else
                                        <span class="text-muted">0</span>
                                    @endif
                                </td>
                                <td class="text-end {{ $row->oldest_age !== null && $row->oldest_age >= 60 ? 'text-danger fw-semibold' : '' }}">
                                    {{ $row->oldest_age !== null ? $row->oldest_age : '—' }}
                                </td>
                                <td>
                                    @if($row->ready)
                                        <span class="badge bg-success">
                                            <i class="mdi mdi-check-circle me-1"></i>Ready to progress
                                        </span>
                                    @else
                                        <span class="text-muted small">
                                            {{ $row->outstanding }} outstanding
                                        </span>
                                        @if($row->failed > 0)
                                            <span class="badge bg-danger ms-1">{{ $row->failed }} failed</span>
                                        @endif
                                    @endif
                                </td>
                                <td class="text-end">
                                    <button wire:click="showBreakdown({{ $row->claim_id }})"
                                            class="btn btn-sm btn-outline-secondary"
                                            title="View DSAR breakdown">
                                        <i class="mdi mdi-format-list-bulleted"></i>
                                    </button>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="7" class="text-muted text-center py-3">No clients with DSARs found.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card-footer bg-white">
            @if($rows->hasPages())
                <div class="mb-2">{{ $rows->links() }}</div>
            @endif
            <small class="text-muted">Counts DSARs that have been sent — drafts and approved (not yet sent) are excluded.</small>
        </div>
    </div>

    {{-- Offcanvas: per-client DSAR breakdown --}}
    <div wire:ignore.self
         class="offcanvas offcanvas-end"
         tabindex="-1"
         style="--bs-offcanvas-width: 520px;"
         id="dsarClientOffcanvas">
        <div class="offcanvas-header border-bottom">
            <div>
                <h5 class="offcanvas-title fw-bold mb-0">
                    {{ $selectedClient?->fullName ?? 'DSAR Breakdown' }}
                </h5>
                @if($selectedClient && $selectedClient->reference)
                    <div class="text-muted small font-monospace">{{ $selectedClient->reference }}</div>
                @endif
            </div>
            <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas"></button>
        </div>

        <div class="offcanvas-body">
            @if($selectedClient)
                @php
                    $returnedCount    = $selectedDsars->whereIn('status', \App\Enum\Dsar\DsarStatus::terminal())->count();
                    $outstandingCount  = $selectedDsars->whereIn('status', \App\Enum\Dsar\DsarStatus::outstanding())->count();
                    $acknowledgedCount = $selectedDsars->where('status', 'acknowledged')->count();
                    $failedCount       = $selectedDsars->where('status', 'failed')->count();
                    $allReturned      = $selectedDsars->count() > 0 && $returnedCount === $selectedDsars->count();
                @endphp

                @if($allReturned)
                    <div class="alert alert-success d-flex align-items-center py-2">
                        <i class="mdi mdi-check-circle me-2"></i>
                        All DSARs returned — this client can be progressed onwards.
                    </div>
                @endif

                <div class="d-flex flex-wrap gap-2 mb-3 align-items-center">
                    <span class="badge bg-success">{{ $returnedCount }} returned</span>
                    <span class="badge bg-warning text-dark">{{ $outstandingCount }} outstanding</span>
                    @if($acknowledgedCount > 0)
                        <span class="badge bg-info">{{ $acknowledgedCount }} acknowledged</span>
                    @endif
                    @if($failedCount > 0)
                        <span class="badge bg-danger">{{ $failedCount }} failed</span>
                    @endif

                    <a wire:navigate href="{{ route('clients.show', $selectedClient) }}"
                       class="btn btn-sm btn-outline-primary ms-auto">
                        <i class="mdi mdi-account-arrow-right me-1"></i>Open client
                    </a>
                </div>

                @php $canViewDsar = auth()->user()?->can('dsars.view'); @endphp
                <div class="list-group">
                    @forelse($selectedDsars as $dsar)
                        @php
                            $isOverdue = $dsar->expected_at
                                && $dsar->expected_at->isPast()
                                && !in_array($dsar->status, \App\Enum\Dsar\DsarStatus::terminal());
                        @endphp
                        <div class="list-group-item {{ $canViewDsar ? 'list-group-item-action' : '' }} position-relative">
                            <div class="d-flex justify-content-between align-items-start gap-2">
                                <div style="min-width:0;">
                                    <div class="fw-semibold text-truncate">{{ $dsar->institution->display_name ?? 'Unknown' }}</div>
                                    <div class="text-muted small">{{ $dsar->institution->dsarType->display_name ?? 'N/A' }}</div>
                                </div>
                                <span class="badge {{ \App\Enum\Dsar\DsarStatus::badgeFor($dsar->status) }} flex-shrink-0">
                                    {{ \App\Enum\Dsar\DsarStatus::label($dsar->status) }}
                                </span>
                            </div>
                            <div class="d-flex flex-wrap gap-3 mt-2 small text-muted">
                                <span><i class="mdi mdi-send-outline me-1"></i>Sent {{ $dsar->created_at->format('d M Y') }}</span>
                                @if($dsar->expected_at)
                                    <span class="{{ $isOverdue ? 'text-danger fw-semibold' : '' }}">
                                        <i class="mdi mdi-calendar-clock me-1"></i>Due {{ $dsar->expected_at->format('d M Y') }}
                                    </span>
                                @endif
                                @if($dsar->reference)
                                    <span class="font-monospace"><i class="mdi mdi-pound me-1"></i>{{ $dsar->reference }}</span>
                                @endif
                            </div>
                            @if($canViewDsar)
                                <a wire:navigate href="{{ route('dsars.view', $dsar) }}" class="stretched-link" title="Open DSAR"></a>
                            @endif
                        </div>
                    @empty
                        <div class="text-center text-muted py-4">
                            <i class="mdi mdi-file-account" style="font-size: 32px;"></i>
                            <p class="mt-2 mb-0">No DSARs recorded.</p>
                        </div>
                    @endforelse
                </div>
            @else
                <p class="text-muted">Select a client to view their DSAR breakdown.</p>
            @endif
        </div>
    </div>

    @script
    <script>
        // Open the breakdown panel when the server fires the event (after the
        // DSARs for the selected client have rendered into the offcanvas body).
        Livewire.on('open-dsar-breakdown', () => {
            const el = document.getElementById('dsarClientOffcanvas');
            if (el && window.bootstrap) {
                window.bootstrap.Offcanvas.getOrCreateInstance(el).show();
            }
        });
    </script>
    @endscript
</div>
