<div>
    <div class="row mb-4 align-items-center">
        <div class="col">
            <h2 class="fw-bold mb-0">
                <i class="bi bi-bar-chart-line text-primary me-2"></i>DSAR Report
            </h2>
            <p class="text-muted mt-1 mb-0">Overview of all Data Subject Access Requests</p>
        </div>
    </div>

    {{-- Stat Cards --}}
    <div class="row g-3 mb-4">
        <div class="col-sm-6 col-xl-3">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Total Sent (All Time)</p>
                    <h3 class="fw-bold mb-0">{{ number_format($totalAll) }}</h3>
                    <small class="text-muted">{{ $totalMonth }} this month</small>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Completed</p>
                    <h3 class="fw-bold mb-0 text-success">{{ number_format($completedCount) }}</h3>
                    @if($totalAll > 0)
                        <small class="text-muted">{{ round(($completedCount / $totalAll) * 100, 1) }}% completion rate</small>
                    @endif
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Flagged</p>
                    <h3 class="fw-bold mb-0 {{ $flaggedCount > 0 ? 'text-danger' : 'text-muted' }}">
                        {{ number_format($flaggedCount) }}
                    </h3>
                    <small class="text-muted">Require attention</small>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Avg Response Time</p>
                    <h3 class="fw-bold mb-0">
                        {{ $avgResponseDays ? round($avgResponseDays, 1) . ' days' : '—' }}
                    </h3>
                    <small class="text-muted">From send to full response</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        {{-- Status Breakdown --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-pie-chart me-2 text-primary"></i>Status Breakdown
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Status</th>
                                <th class="text-end">Count</th>
                                <th class="text-end">%</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach(['completed','sent','needs posting','approved','draft','failed'] as $status)
                                @php $count = $byStatus->get($status, 0); @endphp
                                <tr>
                                    <td>
                                        <span class="badge
                                            @if(in_array($status, ['completed','sent'])) bg-success
                                            @elseif($status === 'approved') bg-primary
                                            @elseif($status === 'needs posting') bg-warning text-dark
                                            @elseif($status === 'failed') bg-danger
                                            @else bg-secondary
                                            @endif">
                                            {{ ucwords($status) }}
                                        </span>
                                    </td>
                                    <td class="text-end">{{ $count }}</td>
                                    <td class="text-end text-muted small">
                                        {{ $totalAll > 0 ? round(($count / $totalAll) * 100, 1) : 0 }}%
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {{-- Response Type Breakdown --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-reply-all me-2 text-primary"></i>Response Types
                </div>
                <div class="card-body">
                    @if($totalResponses > 0)
                        @foreach(['full' => ['Full Response','bg-success'], 'partial' => ['Partial','bg-warning'], 'pushback' => ['Pushback','bg-danger'], 'wrong_recipient' => ['Wrong Recipient','bg-secondary'], 'unknown_client' => ['Unknown Client','bg-dark']] as $type => [$label, $cls])
                            @php $count = $responseBreakdown->get($type, 0); $pct = round(($count / $totalResponses) * 100); @endphp
                            <div class="mb-2">
                                <div class="d-flex justify-content-between small mb-1">
                                    <span>{{ $label }}</span>
                                    <span class="fw-semibold">{{ $count }} ({{ $pct }}%)</span>
                                </div>
                                <div class="progress" style="height:8px;">
                                    <div class="progress-bar {{ $cls }}" style="width:{{ $pct }}%"></div>
                                </div>
                            </div>
                        @endforeach
                    @else
                        <p class="text-muted small mb-0">No responses logged yet.</p>
                    @endif
                </div>
            </div>
        </div>

        {{-- Month Comparison --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-calendar3 me-2 text-primary"></i>Monthly Comparison
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <p class="label-upper mb-1">This Month</p>
                        <h4 class="fw-bold mb-0">{{ $totalMonth }}</h4>
                    </div>
                    <div>
                        <p class="label-upper mb-1">Last Month</p>
                        <h4 class="fw-bold mb-0">{{ $totalLastMonth }}</h4>
                    </div>
                    @if($totalLastMonth > 0)
                        @php $change = round((($totalMonth - $totalLastMonth) / $totalLastMonth) * 100, 1); @endphp
                        <div class="mt-3">
                            <span class="badge {{ $change >= 0 ? 'bg-success' : 'bg-danger' }}">
                                {{ $change >= 0 ? '+' : '' }}{{ $change }}% vs last month
                            </span>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    {{-- DSARs by Target --}}
    <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-bullseye me-2 text-primary"></i>DSARs by Target
            </span>

            <select class="form-select form-select-sm w-auto" wire:model.live="sort">
                <option value="outstanding">Sort: Outstanding</option>
                <option value="oldest">Sort: Oldest Outstanding</option>
                <option value="backlog">Sort: Stated Backlog</option>
                <option value="avg">Sort: Avg Response Days</option>
                <option value="sent">Sort: Total Sent</option>
            </select>

            <input type="text"
                   class="form-control form-control-sm w-auto"
                   style="min-width: 220px"
                   wire:model.live.debounce.300ms="targetSearch"
                   placeholder="Search institution…">
        </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>Institution</th>
                            <th class="text-end" title="DSARs sent but not yet completed">Outstanding</th>
                            <th class="text-end" title="Days since oldest outstanding DSAR was created">Oldest (days)</th>
                            <th class="text-end" title="Average days from send to first full response (our data)">Avg Response</th>
                            <th class="text-end" title="Backlog the institution has publicly stated">Stated Backlog</th>
                            <th class="text-end">Sent</th>
                            <th class="text-end">Completed</th>
                            <th class="text-end">Completion %</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($byTarget as $row)
                            @php
                                $highBacklog  = $row->stated_backlog !== null && $row->stated_backlog >= 100;
                                $agedOutstand = $row->oldest_age_days !== null && $row->oldest_age_days >= 60;
                            @endphp
                            <tr class="{{ $row->outstanding > 0 && ($highBacklog || $agedOutstand) ? 'table-warning' : '' }}">
                                <td>
                                    @if($row->institution)
                                        <a wire:navigate href="{{ route('institutions.show', $row->institution) }}"
                                           class="fw-semibold">
                                            {{ $row->display_name }}
                                        </a>
                                    @else
                                        <span class="text-muted fst-italic">{{ $row->display_name }}</span>
                                    @endif
                                </td>
                                <td class="text-end">
                                    @if($row->outstanding > 0)
                                        <span class="badge bg-warning text-dark">{{ $row->outstanding }}</span>
                                        @if($row->institution)
                                            <a href="{{ route('dsars.report.institution', $row->institution) }}"
                                               class="btn btn-outline-secondary btn-sm py-0 ms-1"
                                               title="Drill-down">
                                                <i class="bi bi-zoom-in"></i>
                                            </a>
                                        @endif
                                    @else
                                        <span class="text-muted">0</span>
                                    @endif
                                </td>
                                <td class="text-end {{ $agedOutstand ? 'text-danger fw-semibold' : '' }}">
                                    {{ $row->oldest_age_days !== null ? (int) $row->oldest_age_days : '—' }}
                                </td>
                                <td class="text-end">
                                    {{ $row->avg_response_days !== null ? $row->avg_response_days . ' d' : '—' }}
                                </td>
                                <td class="text-end">
                                    @if($row->stated_backlog !== null)
                                        <span class="fw-semibold {{ $highBacklog ? 'text-danger' : '' }}">
                                            {{ number_format($row->stated_backlog) }}
                                        </span>
                                        @if($row->backlog_updated_at)
                                            <div class="text-muted small" title="{{ $row->backlog_updated_at }}">
                                                as of {{ $row->backlog_updated_at->format('d M Y') }}
                                            </div>
                                        @endif
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td class="text-end">{{ $row->total_sent }}</td>
                                <td class="text-end">{{ $row->total_completed }}</td>
                                <td class="text-end">
                                    <div class="d-flex align-items-center justify-content-end gap-2">
                                        <div class="progress flex-grow-1" style="height:6px;max-width:80px;">
                                            <div class="progress-bar bg-success" style="width:{{ $row->completion_rate }}%"></div>
                                        </div>
                                        <small>{{ $row->completion_rate }}%</small>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="8" class="text-muted text-center py-3">No DSARs found.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer bg-light small text-muted">
            Rows shaded amber have outstanding DSARs at a target with either a large stated backlog (≥100) or an oldest outstanding DSAR 60+ days old.
            Set each institution's <strong>Stated SAR Backlog</strong> on its edit page to sharpen response-time predictions.
        </div>
    </div>
</div>
