@php use App\Enum\Dsar\DsarStatus; @endphp
{{-- Shared evidence-review body: filter bar + recipient → DSAR → document grouping.
     Rendered by both the client Evidence tab (ClientEvidence) and the standalone
     workbench (EvidenceWorkbench); all wire: directives resolve to the host,
     which pulls in App\Trait\ManagesEvidenceReview for the backing behaviour.

     Terminology is fixed everywhere: Total · Confirmed · To review · Dismissed. --}}

{{-- ── Filter bar ──────────────────────────────────────────────────────────── --}}
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2 d-flex align-items-center flex-wrap gap-2">
        <label class="visually-hidden" for="ev-filter-category">Category</label>
        <select id="ev-filter-category" wire:model.live="filterCategory" class="form-select form-select-sm" style="width:auto;">
            <option value="">All categories</option>
            @foreach($categories as $value => $label)
                <option value="{{ $value }}">{{ $label }}</option>
            @endforeach
        </select>

        <label class="visually-hidden" for="ev-filter-severity">Severity</label>
        <select id="ev-filter-severity" wire:model.live="filterSeverity" class="form-select form-select-sm" style="width:auto;">
            <option value="">Any severity</option>
            <option value="high">High</option>
            <option value="medium">Medium</option>
            <option value="low">Low</option>
        </select>

        <label class="visually-hidden" for="ev-filter-review">Review state</label>
        <select id="ev-filter-review" wire:model.live="filterReview" class="form-select form-select-sm" style="width:auto;">
            <option value="">Any review state</option>
            <option value="unreviewed">To review</option>
            <option value="confirmed">Confirmed</option>
            <option value="dismissed">Dismissed</option>
        </select>

        {{-- Show-excluded sits beside the review-state filter — both scope the corpus. --}}
        <div class="form-check form-switch mb-0 ms-1">
            <input class="form-check-input" type="checkbox" id="showExcluded" wire:model.live="showExcluded">
            <label class="form-check-label small" for="showExcluded">
                Show excluded @if($excludedCount > 0)<span class="badge bg-secondary-subtle text-secondary">{{ $excludedCount }}</span>@endif
            </label>
        </div>

        @if($hasProcessing)
            <span class="ms-auto small text-primary d-flex align-items-center gap-1"
                  title="Extraction / OCR in progress — this page refreshes automatically">
                <span class="spinner-border spinner-border-sm" style="width:.7rem;height:.7rem;"></span>
                Processing… auto-refreshing
            </span>
        @endif
    </div>
</div>

{{-- ── By DSAR recipient & DSAR ─────────────────────────────────────────────── --}}
@forelse($recipientGroups as $group)
    <div class="card border-0 shadow-sm mb-3 ev-recipient" wire:key="recipient-{{ $loop->index }}">

        {{-- Recipient header --}}
        <div class="card-header bg-white d-flex align-items-center gap-2 flex-wrap py-2">
            <i class="mdi mdi-office-building-outline text-muted fs-5"></i>
            <div class="me-2">
                <div class="fw-semibold {{ $group['is_unassigned'] ? 'text-muted' : '' }}">{{ $group['label'] }}</div>
                <div class="text-muted" style="font-size:.72rem;">
                    {{ $group['dsar_count'] }} DSAR{{ $group['dsar_count'] === 1 ? '' : 's' }}
                    · {{ $group['files'] }} document{{ $group['files'] === 1 ? '' : 's' }}
                    @if($group['items'] > 0) · {{ $group['items'] }} finding{{ $group['items'] === 1 ? '' : 's' }} @endif
                    @if($group['local_authority']) · {{ $group['local_authority'] }} @endif
                </div>
            </div>
            {{-- Single roll-up status; detailed counts live on the document rows. --}}
            <span class="ms-auto d-flex gap-1 flex-wrap align-items-center">
                @if($group['items'] > 0)
                    @if($group['unreviewed'] === 0)
                        <span class="ev-chip ev-chip-done"><i class="mdi mdi-check-all"></i> Reviewed</span>
                    @else
                        <span class="ev-chip ev-chip-review">{{ $group['unreviewed'] }} to review</span>
                    @endif
                @endif
            </span>
        </div>

        {{-- DSAR sub-groups --}}
        @foreach($group['dsars'] as $sub)
            <div wire:key="dsar-{{ $sub['dsar']->id }}-{{ $loop->parent->index }}" class="ev-dsar">
                {{-- DSAR band --}}
                <div class="px-3 py-2 d-flex align-items-center gap-2 flex-wrap border-top ev-dsar-band">
                    <i class="mdi mdi-file-send-outline text-muted"></i>
                    <a href="{{ route('dsars.view', $sub['dsar']) }}" class="fw-medium small text-decoration-none">
                        {{ $sub['reference'] }}
                    </a>
                    @if($sub['status'])
                        <span class="badge {{ DsarStatus::badgeFor($sub['status']) }}" style="font-size:.6rem;">{{ DsarStatus::label($sub['status']) }}</span>
                    @endif
                    @if($sub['posted_at'])
                        <span class="text-muted" style="font-size:.68rem;"><i class="mdi mdi-send me-1"></i>Sent {{ $sub['posted_at']->format('d M Y') }}</span>
                    @endif
                    @if($sub['received_at'])
                        <span class="text-muted" style="font-size:.68rem;"><i class="mdi mdi-inbox-arrow-down me-1"></i>Received {{ $sub['received_at']->format('d M Y') }}</span>
                    @endif

                    <span class="ms-auto d-flex gap-1 flex-wrap align-items-center">
                        <span class="text-muted" style="font-size:.68rem;">{{ $sub['files'] }} document{{ $sub['files'] === 1 ? '' : 's' }}</span>
                        @if($sub['items'] > 0)
                            @if($sub['unreviewed'] === 0)
                                <span class="ev-chip ev-chip-done"><i class="mdi mdi-check-all"></i> Reviewed</span>
                            @else
                                <span class="ev-chip ev-chip-review">{{ $sub['unreviewed'] }} to review</span>
                            @endif
                        @endif
                    </span>
                </div>

                {{-- Documents in this DSAR --}}
                <div class="list-group list-group-flush">
                    @foreach($sub['rows'] as $row)
                        @php
                            // Labelled document-row summary (no bare numbers, no tiny bar).
                            $n = $row['count'];
                            $noun = \Illuminate\Support\Str::plural('finding', $n);
                            if ($n === 0) {
                                $rowSummary = null;
                            } elseif ($row['unreviewed'] === 0 && $row['dismissed'] === 0) {
                                $rowSummary = "{$n} {$noun} · All reviewed";
                            } elseif ($row['unreviewed'] === 0) {
                                $rowSummary = "{$n} {$noun} · {$row['confirmed']} confirmed · {$row['dismissed']} dismissed";
                            } else {
                                $bits = [];
                                if ($row['confirmed'] > 0)  $bits[] = "{$row['confirmed']} confirmed";
                                $bits[] = "{$row['unreviewed']} to review";
                                if ($row['dismissed'] > 0)  $bits[] = "{$row['dismissed']} dismissed";
                                $rowSummary = "{$n} {$noun} · " . implode(' · ', $bits);
                            }
                        @endphp
                        <div class="list-group-item ev-doc-row {{ $row['excluded'] ? 'bg-light opacity-75' : '' }}"
                             wire:key="row-{{ $row['type'] }}-{{ $row['id'] }}">
                            <div class="d-flex align-items-start gap-3 flex-wrap">

                                {{-- Preview / doctype tile --}}
                                <div class="flex-shrink-0 position-relative rounded border bg-white d-flex align-items-center justify-content-center overflow-hidden"
                                     style="width:48px;height:60px;">
                                    <div class="text-center" style="line-height:1;">
                                        <i class="mdi mdi-{{ $row['doc_icon'] }}" style="font-size:1.4rem;color:{{ $row['doc_color'] }};"></i>
                                        <div class="text-muted fw-semibold mt-1" style="font-size:.5rem;letter-spacing:.03em;">{{ $row['file_ext'] }}</div>
                                    </div>
                                    @if($row['is_image'] && $row['preview_url'])
                                        <img src="{{ $row['preview_url'] }}" alt=""
                                             class="position-absolute top-0 start-0 w-100 h-100"
                                             style="object-fit:cover;" loading="lazy" onerror="this.remove()">
                                    @endif
                                </div>

                                {{-- Filename (prominent) + metadata (de-emphasised) + counts --}}
                                <div class="flex-grow-1" style="min-width:180px;">
                                    <div class="d-flex align-items-center gap-2 flex-wrap">
                                        <span class="fw-semibold text-truncate" style="max-width:320px;">{{ $row['name'] }}</span>
                                        @include('components.client.partials.evidence-status', ['status' => $row['status'], 'excluded' => $row['excluded']])
                                    </div>
                                    <div class="text-muted d-flex align-items-center gap-1 mt-1" style="font-size:.68rem;">
                                        <i class="mdi mdi-{{ $row['origin_icon'] }}"></i>{{ $row['origin'] }}
                                        <span>· {{ $row['meta'] }}</span>
                                    </div>

                                    @if($rowSummary)
                                        <div class="small mt-1 {{ $row['unreviewed'] > 0 ? '' : 'text-success' }}">
                                            {{ $rowSummary }}
                                        </div>
                                    @endif
                                </div>

                                {{-- Labelled actions --}}
                                <div class="d-flex gap-1 flex-wrap ms-auto align-items-start">
                                    @if($row['view_url'])
                                        @if($row['unreviewed'] > 0)
                                            <a href="{{ $row['view_url'].'?start=review' }}" class="btn btn-sm btn-primary">
                                                <i class="mdi mdi-clipboard-text-search-outline me-1"></i>Review findings
                                            </a>
                                        @else
                                            <a href="{{ $row['view_url'] }}" class="btn btn-sm btn-outline-primary">
                                                <i class="mdi mdi-file-eye-outline me-1"></i>View findings
                                            </a>
                                        @endif
                                    @endif

                                    @can('synapse.use')
                                        @php $extractFn = $row['type'] === 'attachment'
                                                ? "runAttachmentExtraction({$row['id']}, {$row['dsar']->id})"
                                                : "runDocumentExtraction({$row['id']})"; @endphp
                                        @if(!in_array($row['status'], ['processing', 'completed']))
                                            <button wire:click="{{ $extractFn }}"
                                                    class="btn btn-sm text-white" style="background:#7c3aed;"
                                                    title="Extract evidence findings with Synapse AI">
                                                <i class="mdi mdi-brain me-1"></i>Extract
                                            </button>
                                        @elseif($row['status'] === 'completed')
                                            <button wire:click="{{ $extractFn }}"
                                                    wire:confirm="Re-run extraction? Adds new findings alongside existing ones."
                                                    class="btn btn-sm btn-outline-secondary" title="Re-run AI extraction on this document">
                                                <i class="mdi mdi-refresh me-1"></i>Re-extract
                                            </button>
                                        @endif
                                    @endcan

                                    @if(in_array($row['status'], ['processing', 'failed']))
                                        <button wire:click="resetStatus('{{ $row['type'] }}', {{ $row['id'] }})"
                                                wire:confirm="Reset this document's status so it can be extracted again?"
                                                class="btn btn-sm btn-outline-warning" title="Clear a stuck extraction status">
                                            <i class="mdi mdi-restart me-1"></i>Reset
                                        </button>
                                    @endif

                                    @if($row['excluded'])
                                        <button wire:click="restoreFile('{{ $row['type'] }}', {{ $row['id'] }})"
                                                class="btn btn-sm btn-outline-success" title="Restore this document to the evidence review">
                                            <i class="mdi mdi-restore me-1"></i>Restore
                                        </button>
                                    @else
                                        <button wire:click="excludeFile('{{ $row['type'] }}', {{ $row['id'] }})"
                                                wire:confirm="Exclude this document from the evidence review? It will be hidden unless you show excluded documents."
                                                class="btn btn-sm btn-outline-secondary" title="Exclude this document from the evidence review">
                                            <i class="mdi mdi-close-box-outline me-1"></i>Exclude
                                        </button>
                                    @endif
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        @endforeach
    </div>
@empty
    <div class="text-center py-5 text-muted">
        <i class="mdi mdi-file-search-outline fs-1 d-block mb-2 opacity-25"></i>
        <p class="mb-0 small">No evidence documents match the current filters.</p>
    </div>
@endforelse

<style>
    /* One consistent count-chip system across every evidence surface. */
    .ev-chip {
        display:inline-flex; align-items:center; gap:.2rem;
        font-size:.68rem; font-weight:600; line-height:1;
        padding:.25rem .5rem; border-radius:1rem; border:1px solid transparent;
    }
    .ev-chip-confirmed { background:#dcfce7; color:#15803d; border-color:#bbf7d0; }
    .ev-chip-review    { background:#fef3c7; color:#b45309; border-color:#fde68a; }
    .ev-chip-done      { background:#f1f5f9; color:#475569; border-color:#e2e8f0; }

    /* Nested-structure cues: each level steps in and shifts background. */
    .ev-dsar-band  { background:#f5f7fb; }
    .ev-doc-row    { padding-left:1.5rem; border-left:3px solid transparent; transition:border-color .1s, background .1s; }
    .ev-doc-row:hover { background:#f8fafc; border-left-color:#c7d2fe; }
</style>
