@php
    use App\Models\Dsar\DsarEvidenceItem;
    $reviewed = $confirmedCount + $dismissedCount;
    $pct      = $totalCount > 0 ? round($reviewed / $totalCount * 100) : 0;
@endphp
<div
        x-data="evidenceViewer({
            autoReview:        @js($autoReview),
            firstUnreviewedId: @js($firstUnreviewedId),
            openPagesInit:     @js($itemsByPage->keys()->map(fn ($k) => (int) $k)->values()),
        })"
        x-init="init()"
        @keydown.window="onKey($event)"
        @evidence-toast.window="showToast($event.detail)"
        class="ev-viewer d-flex flex-column flex-grow-1"
        style="min-height:0;"
>
    {{-- ══ Compact review header (replaces the global navigation) ══════════════ --}}
    <header class="ev-topbar d-flex align-items-center gap-3 px-3 py-2">
        <a href="{{ $backUrl ?: url()->previous() }}" class="btn btn-sm btn-outline-secondary flex-shrink-0"
           @click="if (hasUnsaved() && ! confirm('You have unsaved changes. Leave anyway?')) $event.preventDefault()">
            <i class="mdi mdi-arrow-left me-1"></i>Back
        </a>

        <div class="flex-shrink-0" style="min-width:0;">
            @if($contextLabel)
                <div class="text-muted text-truncate" style="font-size:.72rem;max-width:260px;">{{ $contextLabel }}</div>
            @endif
            <div class="fw-semibold text-truncate" style="max-width:340px;" title="{{ $fileName }}">
                <i class="mdi mdi-file-document-outline me-1 text-muted"></i>{{ $fileName ?: 'Document' }}
            </div>
        </div>

        {{-- Progress --}}
        <div class="d-none d-md-flex align-items-center gap-2 ms-3" style="min-width:200px;max-width:320px;flex:1 1 220px;">
            <div class="progress flex-grow-1" style="height:9px;" role="progressbar"
                 aria-valuenow="{{ $reviewed }}" aria-valuemin="0" aria-valuemax="{{ $totalCount }}" aria-label="Review progress">
                <div class="progress-bar bg-success" style="width:{{ $pct }}%;"></div>
            </div>
            <span class="small text-muted text-nowrap">{{ $reviewed }} of {{ $totalCount }} reviewed</span>
        </div>

        <div class="ms-auto d-flex align-items-center gap-2 flex-shrink-0">
            {{-- Save state --}}
            <span class="small d-flex align-items-center gap-1" :class="saved ? 'text-success' : 'text-muted'">
                <i class="mdi" :class="saved ? 'mdi-check-circle' : 'mdi-cloud-check-outline'"></i>
                <span x-text="saved ? 'Saved' : 'Changes saved automatically'" class="d-none d-lg-inline"></span>
            </span>

            {{-- Keyboard shortcuts --}}
            <div class="position-relative">
                <button class="btn btn-sm btn-outline-secondary" @click="showShortcuts = !showShortcuts"
                        aria-label="Keyboard shortcuts" title="Keyboard shortcuts (?)">
                    <i class="mdi mdi-keyboard-outline"></i>
                </button>
                <div x-show="showShortcuts" x-cloak @click.outside="showShortcuts = false"
                     class="card shadow position-absolute end-0 mt-1 p-2" style="z-index:1000;width:240px;">
                    <div class="fw-semibold small mb-1">Keyboard shortcuts</div>
                    <table class="table table-sm mb-0" style="font-size:.74rem;">
                        <tbody>
                            <tr><td><kbd>C</kbd></td><td>Confirm finding</td></tr>
                            <tr><td><kbd>D</kbd></td><td>Dismiss finding</td></tr>
                            <tr><td><kbd>E</kbd></td><td>Edit interpretation</td></tr>
                            <tr><td><kbd>J</kbd> / <kbd>↓</kbd></td><td>Next finding</td></tr>
                            <tr><td><kbd>K</kbd> / <kbd>↑</kbd></td><td>Previous finding</td></tr>
                            <tr><td><kbd>L</kbd></td><td>Locate in document</td></tr>
                            <tr><td><kbd>Esc</kbd></td><td>Cancel drawing / edit</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </header>

    {{-- ══ Toolbar ════════════════════════════════════════════════════════════ --}}
    <div class="ev-toolbar d-flex align-items-center gap-2 flex-wrap px-3 py-2">

        {{-- Filters --}}
        <div class="d-flex align-items-center gap-2 flex-wrap">
            <label class="visually-hidden" for="v-state">Review state</label>
            <select id="v-state" wire:model.live="filterState" 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>
            <label class="visually-hidden" for="v-cat">Category</label>
            <select id="v-cat" 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="v-sev">Severity</label>
            <select id="v-sev" 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="v-src">Extraction source</label>
            <select id="v-src" wire:model.live="filterSource" class="form-select form-select-sm" style="width:auto;">
                <option value="">Any source</option>
                <option value="ai">Synapse (AI)</option>
                <option value="human">Human</option>
            </select>
            <label class="visually-hidden" for="v-loc">Page location</label>
            <select id="v-loc" wire:model.live="filterLocation" class="form-select form-select-sm" style="width:auto;">
                <option value="">Any location</option>
                <option value="located">Located on page</option>
                <option value="unlocated">Unlocated</option>
            </select>
        </div>

        <div class="ms-auto d-flex align-items-center gap-2 flex-wrap">
            {{-- Page nav (symmetrical) --}}
            <div class="d-flex align-items-center gap-1">
                <button @click="prevPage()" :disabled="currentPage <= 1" class="btn btn-sm btn-outline-secondary"
                        aria-label="Previous page" title="Previous page"><i class="mdi mdi-chevron-left"></i></button>
                <span class="small text-muted">Page</span>
                <input type="number" min="1" :max="totalPages" :value="currentPage"
                       @change="goToPage($event.target.value)" @keydown.enter="goToPage($event.target.value)"
                       class="form-control form-control-sm text-center" style="width:3.6rem;" aria-label="Page number">
                <span class="small text-muted">of <span x-text="totalPages"></span></span>
                <button @click="nextPage()" :disabled="currentPage >= totalPages" class="btn btn-sm btn-outline-secondary"
                        aria-label="Next page" title="Next page"><i class="mdi mdi-chevron-right"></i></button>
            </div>

            {{-- Zoom --}}
            <div class="d-flex align-items-center gap-1 border-start ps-2">
                <button @click="zoomOut()" class="btn btn-sm btn-outline-secondary" aria-label="Zoom out" title="Zoom out"><i class="mdi mdi-minus"></i></button>
                <span class="small" x-text="Math.round(scale * 100) + '%'" style="min-width:3rem;text-align:center;"></span>
                <button @click="zoomIn()" class="btn btn-sm btn-outline-secondary" aria-label="Zoom in" title="Zoom in"><i class="mdi mdi-plus"></i></button>
                <button @click="fitWidth()" class="btn btn-sm btn-outline-secondary" title="Fit page width">Fit width</button>
                <button @click="fitPage()" class="btn btn-sm btn-outline-secondary" title="Fit whole page">Fit page</button>
            </div>

            {{-- Finding scan --}}
            <div class="d-flex align-items-center gap-1 border-start ps-2">
                <span class="small text-muted text-nowrap"
                      x-text="activeItemIdx >= 0
                               ? ('Finding ' + (activeItemIdx + 1) + ' of ' + ($wire.itemsData||[]).length)
                               : 'No finding selected'"></span>
                <button @click="prevItem()" :disabled="activeItemIdx <= 0" class="btn btn-sm btn-outline-secondary"
                        aria-label="Previous finding" title="Previous finding (K)"><i class="mdi mdi-arrow-up"></i></button>
                <button @click="nextItem()" :disabled="activeItemIdx < 0 || activeItemIdx >= ($wire.itemsData||[]).length - 1"
                        class="btn btn-sm btn-outline-secondary" aria-label="Next finding" title="Next finding (J)"><i class="mdi mdi-arrow-down"></i></button>
            </div>

            {{-- Mark evidence area --}}
            <button @click="toggleDrawMode()" :class="drawMode && ! locatingId ? 'btn-warning' : 'btn-outline-secondary'"
                    class="btn btn-sm border-start-0" title="Draw a box on the page to mark a new evidence area">
                <i class="mdi mdi-vector-square me-1"></i><span x-text="drawMode && ! locatingId ? 'Marking…' : 'Mark evidence area'"></span>
            </button>
        </div>
    </div>

    {{-- Locate / mark banner --}}
    <div x-show="drawMode || proposed" x-cloak class="ev-draw-banner d-flex align-items-center gap-2 px-3 py-2">
        <i class="mdi" :class="proposed ? 'mdi-map-marker-check-outline' : 'mdi-cursor-default-click-outline'"></i>
        <span class="small flex-grow-1" x-text="bannerText()"></span>
        <button x-show="proposed" @click="saveLocation()" class="btn btn-sm btn-primary">
            <i class="mdi mdi-content-save-outline me-1"></i>Save location
        </button>
        <button @click="cancelDraw()" class="btn btn-sm btn-outline-secondary">Cancel</button>
    </div>

    {{-- ══ Split: PDF (left) + findings (right) ═══════════════════════════════ --}}
    <div class="ev-split d-flex flex-grow-1" style="min-height:0;" x-ref="split">

        {{-- PDF viewer — wire:ignore keeps Livewire's morphdom away; Alpine/PDF.js own it. --}}
        <div wire:ignore class="ev-pdf flex-grow-1 position-relative overflow-auto" style="min-width:0;" x-ref="pdfContainer">
            <div class="d-flex justify-content-center align-items-start p-3" style="min-height:100%;">
                <div class="position-relative flex-shrink-0" x-ref="pageWrapper">
                    <canvas x-ref="pdfCanvas" style="display:block;box-shadow:0 4px 20px rgba(0,0,0,.35);background:#fff;"></canvas>

                    <div x-ref="textLayer" class="position-absolute top-0 start-0 w-100 h-100"
                         style="overflow:hidden;line-height:1.0;opacity:0;pointer-events:none;"></div>

                    <div class="position-absolute top-0 start-0 w-100 h-100" style="pointer-events:none;">
                        {{-- Saved highlights --}}
                        <template x-for="item in currentPageItems()" :key="item.id">
                            <div x-show="item.bbox || textBboxes[item.id]"
                                 :style="highlightStyle(item)"
                                 class="position-absolute synapse-highlight"
                                 style="pointer-events:auto;cursor:pointer;border-radius:2px;"
                                 @click="setActiveById(item.id)"
                                 :title="item.comment"></div>
                        </template>
                        {{-- Proposed (unsaved) location --}}
                        <div x-show="proposed && proposed.page === currentPage" x-cloak :style="proposedStyle()" class="position-absolute ev-proposed-box"></div>
                        {{-- Live draw ghost --}}
                        <div x-show="drawMode && drawing" :style="ghostStyle()" class="position-absolute"></div>
                    </div>

                    <div x-show="drawMode" class="position-absolute top-0 start-0 w-100 h-100" style="cursor:crosshair;"
                         @mousedown="onDrawStart($event)" @mousemove="onDrawMove($event)" @mouseup="onDrawEnd($event)"></div>
                </div>
            </div>

            <div x-show="loading" class="position-absolute top-50 start-50 translate-middle text-white">
                <span class="spinner-border"></span>
            </div>
        </div>

        {{-- Resizer --}}
        <div class="ev-resizer" @mousedown="startResize($event)" @mousemove.window="onResize($event)"
             @mouseup.window="stopResize()" role="separator" aria-label="Resize findings panel" title="Drag to resize"></div>

        {{-- Findings panel --}}
        <div class="ev-findings d-flex flex-column bg-white" :style="`width:${sidebarWidth}px;`">

            {{-- Status strip --}}
            <div class="d-flex align-items-center gap-3 px-3 py-2 border-bottom flex-wrap" style="font-size:.74rem;">
                <span class="d-inline-flex align-items-center gap-1"><span class="ev-dot" style="background:#94a3b8;"></span><strong>{{ $totalCount }}</strong> Total</span>
                <span class="d-inline-flex align-items-center gap-1"><span class="ev-dot" style="background:#16a34a;"></span><strong class="text-success">{{ $confirmedCount }}</strong> Confirmed</span>
                <span class="d-inline-flex align-items-center gap-1"><span class="ev-dot" style="background:#d97706;"></span><strong style="color:#b45309;">{{ $toReviewCount }}</strong> To review</span>
                <span class="d-inline-flex align-items-center gap-1"><span class="ev-dot" style="background:#64748b;"></span><strong class="text-secondary">{{ $dismissedCount }}</strong> Dismissed</span>
            </div>

            {{-- Bulk action bar --}}
            @if(count($selected) > 0)
                <div class="d-flex align-items-center gap-2 px-3 py-2 border-bottom bg-light">
                    <span class="small fw-semibold">{{ count($selected) }} selected</span>
                    <button wire:click="confirmSelected" class="btn btn-sm btn-outline-success" style="font-size:.72rem;">
                        <i class="mdi mdi-check"></i> Confirm selected
                    </button>
                    <button wire:click="dismissSelected" class="btn btn-sm btn-outline-secondary" style="font-size:.72rem;">
                        <i class="mdi mdi-close"></i> Dismiss selected
                    </button>
                    <button wire:click="clearSelection" class="btn btn-sm btn-link text-decoration-none ms-auto" style="font-size:.72rem;">Clear</button>
                </div>
            @endif

            {{-- Add / annotate form (from "Mark evidence area") --}}
            @if($showAddForm)
                <div class="border-bottom p-3" style="border-top:3px solid #7c3aed;">
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <span class="ev-chip ev-src-ai"><i class="mdi mdi-brain"></i> New evidence</span>
                        @if($addPage)<span class="ev-chip ev-chip-done">Page {{ $addPage }}</span>@endif
                        <button wire:click="cancelAdd" class="btn-close ms-auto" style="font-size:.6rem;" aria-label="Cancel"></button>
                    </div>
                    <div class="mb-2">
                        <label class="form-label small mb-1">Category</label>
                        <select wire:model="addCategory" class="form-select form-select-sm">
                            @foreach($categories as $value => $label)<option value="{{ $value }}">{{ $label }}</option>@endforeach
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label small mb-1">Severity</label>
                        <select wire:model="addSeverity" class="form-select form-select-sm">
                            <option value="high">High</option><option value="medium">Medium</option><option value="low">Low</option>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label small mb-1">Interpretation</label>
                        <textarea wire:model="addComment" class="form-control form-control-sm" rows="2" placeholder="Why is this significant?"></textarea>
                        @error('addComment')<div class="text-danger" style="font-size:.72rem;">{{ $message }}</div>@enderror
                    </div>
                    <button wire:click="saveEvidence" class="btn btn-sm text-white w-100" style="background:#7c3aed;">
                        <i class="mdi mdi-check me-1"></i>Save evidence
                    </button>
                </div>
            @endif

            {{-- Findings list --}}
            <div class="overflow-auto flex-grow-1" x-ref="sidebar">
                @forelse($itemsByPage as $pageNum => $pageItems)
                    @php
                        $pgToReview  = $pageItems->filter->isUnreviewed()->count();
                        $pgConfirmed = $pageItems->filter->isConfirmed()->count();
                        $pgDismissed = $pageItems->filter->isDismissed()->count();
                        $pgTotal     = $pageItems->count();
                        $pageKey     = (int) ($pageNum ?: 0);
                        $unlocated   = $pageKey === 0;

                        // Labelled group summary — never bare adjacent numbers.
                        if ($pgToReview === 0) {
                            $pgSummary = $pgTotal . ' ' . \Illuminate\Support\Str::plural('finding', $pgTotal) . ' · Reviewed';
                        } elseif ($pgConfirmed === 0 && $pgDismissed === 0) {
                            $pgSummary = $pgTotal . ' ' . \Illuminate\Support\Str::plural('finding', $pgTotal) . ' · ' . $pgToReview . ' to review';
                        } else {
                            $parts = [];
                            if ($pgConfirmed > 0) $parts[] = $pgConfirmed . ' confirmed';
                            if ($pgToReview > 0)  $parts[] = $pgToReview . ' to review';
                            if ($pgDismissed > 0) $parts[] = $pgDismissed . ' dismissed';
                            $pgSummary = $pgTotal . ' ' . \Illuminate\Support\Str::plural('finding', $pgTotal) . ' · ' . implode(' · ', $parts);
                        }
                    @endphp
                    <div class="border-bottom" wire:key="pg-{{ $pageKey }}">
                        <button class="btn btn-link text-decoration-none w-100 text-start d-flex align-items-center gap-2 py-2 px-3"
                                style="font-size:.82rem;color:inherit;"
                                @click="togglePage({{ $pageKey }}); if({{ $pageKey }} > 0) scrollPdfToPage({{ $pageKey }})">
                            <i class="mdi mdi-chevron-right flex-shrink-0" style="transition:transform .15s;"
                               :style="openPages.includes({{ $pageKey }}) ? 'transform:rotate(90deg)' : ''"></i>
                            <span class="fw-semibold">{{ $unlocated ? 'Unlocated findings' : 'Page ' . $pageNum }}</span>
                            <span class="ms-auto text-muted" style="font-size:.72rem;">{{ $pgSummary }}</span>
                        </button>

                        <div x-show="openPages.includes({{ $pageKey }})" x-cloak>
                            @if($unlocated)
                                <div class="px-3 pb-2 text-muted" style="font-size:.74rem;">
                                    These findings were extracted from document text but could not be linked to an exact page location. Use <strong>Locate</strong> to mark where each one appears.
                                </div>
                            @endif
                            <div class="d-flex flex-column gap-2 px-2 pb-2">
                                @foreach($pageItems as $item)
                                    @php
                                        $colour     = DsarEvidenceItem::categoryColour($item->category);
                                        $label      = DsarEvidenceItem::categoryLabel($item->category);
                                        $stateClass = $item->isConfirmed() ? 'confirmed' : ($item->isDismissed() ? 'dismissed' : 'unreviewed');
                                        $isEditing  = $editingId === $item->id;
                                        $quoteLong  = mb_strlen((string) $item->quote) > 240;
                                        $commentLong= mb_strlen((string) $item->comment) > 240;
                                        $isReviewed = $item->isConfirmed() || $item->isDismissed();
                                    @endphp
                                    <div class="card border-0 shadow-sm evidence-card evidence-{{ $stateClass }}"
                                         id="evidence-item-{{ $item->id }}"
                                         wire:key="item-{{ $item->id }}"
                                         x-data="{ expandQuote:false, expandComment:false, menuOpen:false }"
                                         style="border-left:4px solid {{ $colour }} !important;{{ $item->isDismissed() ? 'opacity:.6;' : '' }}"
                                         :class="{ 'active-item': isActive({{ $item->id }}) }"
                                         @click="setActiveById({{ $item->id }})">
                                        <div class="card-body p-3">

                                            {{-- Header: current label · category · severity · source · select --}}
                                            <div class="d-flex align-items-center gap-1 flex-wrap mb-2">
                                                <span x-show="isActive({{ $item->id }})" x-cloak class="ev-chip ev-current"><i class="mdi mdi-target"></i> Current</span>
                                                <span class="ev-chip" style="background:{{ $colour }}1a;color:{{ $colour }};border-color:{{ $colour }}55;">{{ $label }}</span>
                                                <span class="ev-chip ev-sev-{{ $item->severity }}">{{ ucfirst($item->severity) }}</span>
                                                @if($item->source === 'human')
                                                    <span class="ev-chip ev-src-human">Human</span>
                                                @else
                                                    <span class="ev-chip ev-src-ai"><i class="mdi mdi-brain"></i> Synapse</span>
                                                @endif
                                                <span class="ms-auto" @click.stop>
                                                    <input class="form-check-input mt-0" type="checkbox" wire:model.live="selected" value="{{ $item->id }}"
                                                           aria-label="Select finding for bulk action" title="Select for bulk action">
                                                </span>
                                            </div>

                                            {{-- Location --}}
                                            <div class="text-muted mb-2" style="font-size:.72rem;">
                                                @if($item->page)
                                                    <i class="mdi mdi-map-marker-outline"></i> Page {{ $item->page }}
                                                @else
                                                    <i class="mdi mdi-map-marker-off-outline"></i> Unlocated
                                                @endif
                                            </div>

                                            {{-- Source text --}}
                                            @if($item->quote)
                                                <div class="mb-3">
                                                    <div class="ev-field-label">Source text <span class="text-muted fw-normal">· from the document</span></div>
                                                    <blockquote class="ev-source-quote mb-1" :class="expandQuote ? '' : 'ev-clamp'">"{{ $item->quote }}"</blockquote>
                                                    @if($quoteLong)
                                                        <button class="btn btn-link p-0 text-decoration-none" style="font-size:.74rem;" @click.stop="expandQuote = !expandQuote"
                                                                x-text="expandQuote ? 'Show less' : 'Show more'"></button>
                                                    @endif
                                                </div>
                                            @endif

                                            {{-- AI interpretation (editable) --}}
                                            <div class="mb-2">
                                                <div class="ev-field-label d-flex align-items-center gap-1">
                                                    <i class="mdi mdi-brain" style="color:#7c3aed;"></i>
                                                    {{ $item->source === 'human' ? 'Interpretation' : 'AI interpretation' }}
                                                    @if($item->source !== 'human')<span class="text-muted fw-normal">· generated, not verbatim</span>@endif
                                                </div>
                                                @if($isEditing)
                                                    <div @click.stop>
                                                        <textarea wire:model="editingComment" x-init="$el.focus()" rows="3"
                                                                  class="form-control form-control-sm" style="font-size:.85rem;"></textarea>
                                                        @error('editingComment')<div class="text-danger" style="font-size:.72rem;">{{ $message }}</div>@enderror
                                                        <div class="d-flex gap-1 mt-1">
                                                            <button wire:click="saveEdit" class="btn btn-sm btn-success ev-action"><i class="mdi mdi-check"></i> Save</button>
                                                            <button wire:click="cancelEdit" class="btn btn-sm btn-outline-secondary ev-action">Cancel</button>
                                                        </div>
                                                    </div>
                                                @else
                                                    <p class="ev-interp mb-1" :class="expandComment ? '' : 'ev-clamp'">{{ $item->comment ?: '—' }}</p>
                                                    @if($commentLong)
                                                        <button class="btn btn-link p-0 text-decoration-none" style="font-size:.74rem;" @click.stop="expandComment = !expandComment"
                                                                x-text="expandComment ? 'Show less' : 'Show more'"></button>
                                                    @endif
                                                @endif
                                            </div>

                                            @if($item->human_notes)
                                                <p class="text-info mb-2" style="font-size:.76rem;"><i class="mdi mdi-note-outline me-1"></i>{{ $item->human_notes }}</p>
                                            @endif

                                            {{-- Care setting --}}
                                            @if(count($careSettings) > 0)
                                                <div class="mb-2" @click.stop>
                                                    <div class="d-flex align-items-center gap-1 mb-1">
                                                        <label class="ev-field-label mb-0"><i class="mdi mdi-home-city-outline me-1"></i>Care setting</label>
                                                        @if($item->care_setting_id && $item->care_setting_is_suggested)
                                                            <span class="ev-chip ev-src-ai" title="AI suggestion — accept to confirm"><i class="mdi mdi-brain"></i> Suggested</span>
                                                            <button wire:click="acceptCareSetting({{ $item->id }})" class="btn btn-sm btn-outline-success ms-auto ev-action" style="min-height:32px;">
                                                                <i class="mdi mdi-check"></i> Accept
                                                            </button>
                                                        @endif
                                                    </div>
                                                    <select class="form-select form-select-sm" style="font-size:.78rem;{{ ($item->care_setting_id && $item->care_setting_is_suggested) ? 'border:1px dashed #7c3aed;' : '' }}"
                                                            wire:change="setCareSetting({{ $item->id }}, $event.target.value)">
                                                        <option value="">— Select care setting —</option>
                                                        @foreach($careSettings as $csId => $csLabel)
                                                            <option value="{{ $csId }}" @selected($item->care_setting_id == $csId)>{{ $csLabel }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            @endif

                                            {{-- Actions --}}
                                            @if(!$isEditing)
                                                <div class="d-flex gap-2 flex-wrap align-items-center pt-1" @click.stop>
                                                    @if($isReviewed)
                                                        <span class="small text-muted">Status:</span>
                                                        <span class="ev-chip {{ $item->isConfirmed() ? 'ev-chip-confirmed' : 'ev-chip-done' }}">
                                                            <i class="mdi {{ $item->isConfirmed() ? 'mdi-check-circle' : 'mdi-close-circle' }}"></i>
                                                            {{ $item->isConfirmed() ? 'Confirmed' : 'Dismissed' }}
                                                        </span>
                                                        <div class="position-relative" x-data="{ open:false }" @click.outside="open = false">
                                                            <button @click="open = !open" class="btn btn-sm btn-outline-secondary ev-action">
                                                                Change status <i class="mdi mdi-chevron-down"></i>
                                                            </button>
                                                            <div x-show="open" x-cloak class="card shadow position-absolute mt-1 p-1" style="z-index:30;min-width:190px;">
                                                                <button wire:click="unreview({{ $item->id }})" class="btn btn-sm btn-link text-start text-decoration-none w-100" style="color:inherit;">
                                                                    <i class="mdi mdi-undo me-1"></i>Return to review
                                                                </button>
                                                                @if($item->isConfirmed())
                                                                    <button wire:click="dismiss({{ $item->id }})" class="btn btn-sm btn-link text-start text-decoration-none w-100" style="color:inherit;">
                                                                        <i class="mdi mdi-close-circle-outline me-1"></i>Mark as dismissed
                                                                    </button>
                                                                @else
                                                                    <button wire:click="confirm({{ $item->id }})" class="btn btn-sm btn-link text-start text-decoration-none w-100" style="color:inherit;">
                                                                        <i class="mdi mdi-check-circle-outline me-1"></i>Mark as confirmed
                                                                    </button>
                                                                @endif
                                                            </div>
                                                        </div>
                                                        <button wire:click="startEdit({{ $item->id }})" class="btn btn-sm btn-outline-secondary ev-action" title="Edit the interpretation">
                                                            <i class="mdi mdi-pencil-outline"></i> Edit
                                                        </button>
                                                        @if(!$item->page)
                                                            <button @click="startLocate({{ $item->id }}, @js($item->quote))" class="btn btn-sm btn-outline-primary ev-action" title="Locate this finding in the document (L)">
                                                                <i class="mdi mdi-map-marker-plus-outline"></i> Locate
                                                            </button>
                                                        @endif
                                                    @else
                                                        <button wire:click="confirm({{ $item->id }})" class="btn btn-sm btn-success ev-action">
                                                            <i class="mdi mdi-check"></i> Confirm
                                                        </button>
                                                        <button wire:click="dismiss({{ $item->id }})" class="btn btn-sm btn-outline-secondary ev-action">
                                                            <i class="mdi mdi-close"></i> Dismiss
                                                        </button>
                                                        <button wire:click="startEdit({{ $item->id }})" class="btn btn-sm btn-outline-secondary ev-action" title="Edit the interpretation">
                                                            <i class="mdi mdi-pencil-outline"></i> Edit
                                                        </button>
                                                        @if(!$item->page)
                                                            <button @click="startLocate({{ $item->id }}, @js($item->quote))" class="btn btn-sm btn-outline-primary ev-action" title="Locate this finding in the document (L)">
                                                                <i class="mdi mdi-map-marker-plus-outline"></i> Locate
                                                            </button>
                                                        @endif
                                                    @endif
                                                    @if($item->source === 'human')
                                                        <button wire:click="deleteItem({{ $item->id }})" wire:confirm="Delete this evidence item?"
                                                                class="btn btn-sm btn-outline-danger ev-action ms-auto" title="Delete this human-added finding">
                                                            <i class="mdi mdi-trash-can-outline"></i>
                                                        </button>
                                                    @endif
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                @empty
                    <div class="text-center text-muted py-5 px-3">
                        <i class="mdi mdi-magnify-scan d-block mb-2 opacity-25" style="font-size:2rem;"></i>
                        <p class="small mb-0">No findings match the current filters.</p>
                    </div>
                @endforelse

                {{-- All-reviewed completion state --}}
                <div x-show="reviewComplete" x-cloak class="text-center text-success py-4 px-3 border-top">
                    <i class="mdi mdi-check-all d-block mb-1" style="font-size:1.8rem;"></i>
                    <div class="fw-semibold small">Review complete</div>
                    <a href="{{ $backUrl ?: url()->previous() }}" class="btn btn-sm btn-outline-primary mt-2">Back to evidence overview</a>
                </div>
            </div>
        </div>
    </div>

    {{-- Toast --}}
    <div x-show="toast.visible" x-cloak class="ev-toast card shadow d-flex flex-row align-items-center gap-2 px-3 py-2">
        <i class="mdi mdi-information-outline text-primary"></i>
        <span class="small" x-text="toast.message"></span>
        <button x-show="toast.undoAction" @click="undoToast()" class="btn btn-sm btn-link p-0 text-decoration-none">Undo</button>
        <button @click="toast.visible = false" class="btn-close ms-1" style="font-size:.55rem;" aria-label="Dismiss"></button>
    </div>
</div>

@push('scripts')
    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

        function evidenceViewer(config) {
            let _pdfDoc = null;
            let _renderTask = null;

            return {
                autoReview:        config.autoReview,
                firstUnreviewedId: config.firstUnreviewedId,

                loading:      true,
                currentPage:  1,
                totalPages:   1,
                scale:        1.4,
                canvasW:      1,
                canvasH:      1,
                pageBaseW:    0,
                pageBaseH:    0,
                textBboxes:   {},

                activeItemIdx: -1,
                openPages:     config.openPagesInit || [],
                saved:         false,
                showShortcuts: false,
                reviewComplete:false,
                toast:         { visible:false, message:'', undoId:null, undoAction:null },
                _savedT:       null,
                _toastT:       null,

                // draw / locate
                drawMode:      false,
                drawing:       false,
                drawStart:     null,
                drawCurrent:   null,
                locatingId:    null,
                locatingQuote: '',
                proposed:      null,   // { page, bbox } — an unsaved location

                // resize
                sidebarWidth: 440,
                resizing:     false,
                _rx: 0, _rw: 0,

                async init() {
                    const savedScale = parseFloat(localStorage.getItem('evScale'));
                    if (!isNaN(savedScale)) this.scale = Math.min(Math.max(savedScale, 0.4), 4);
                    const savedW = parseInt(localStorage.getItem('evSidebarW'));
                    if (!isNaN(savedW)) this.sidebarWidth = Math.min(Math.max(savedW, 360), 720);

                    window.addEventListener('beforeunload', (e) => {
                        if (this.hasUnsaved()) { e.preventDefault(); e.returnValue = ''; }
                    });

                    await this.loadPdf();

                    if (this.autoReview && this.firstUnreviewedId) {
                        await this.setActiveById(this.firstUnreviewedId);
                    }
                },

                hasUnsaved() { return this.$wire.editingId != null || this.drawing || this.proposed != null; },
                isActive(id) { return this.activeItemIdx >= 0 && (this.$wire.itemsData || [])[this.activeItemIdx]?.id === id; },

                // ── PDF ────────────────────────────────────────────────────────────
                async loadPdf() {
                    this.loading = true;
                    try {
                        const url = @js($attachment?->id
                            ? route('inbox.attachment.preview', $attachment->id)
                            : route('documents.raw', $document->id));
                        _pdfDoc = await pdfjsLib.getDocument(url).promise;
                        this.totalPages = _pdfDoc.numPages;
                        await this.renderPage(this.currentPage);
                    } catch (e) {
                        console.error('PDF load error', e);
                        this.loading = false;
                    }
                },

                async renderPage(pageNum) {
                    if (_renderTask) _renderTask.cancel();
                    this.loading = true;
                    try {
                        const page = await _pdfDoc.getPage(pageNum);
                        const base = page.getViewport({ scale: 1 });
                        this.pageBaseW = base.width; this.pageBaseH = base.height;
                        const vp = page.getViewport({ scale: this.scale });
                        const canvas = this.$refs.pdfCanvas;
                        const ctx = canvas.getContext('2d');
                        canvas.width = vp.width; canvas.height = vp.height;
                        this.canvasW = vp.width; this.canvasH = vp.height;

                        _renderTask = page.render({ canvasContext: ctx, viewport: vp });
                        try { await _renderTask.promise; }
                        catch (e) { if (e.name !== 'RenderingCancelledException') throw e; }

                        const tl = this.$refs.textLayer;
                        tl.innerHTML = '';
                        const content = await page.getTextContent();
                        pdfjsLib.renderTextLayer({ textContentSource: content, container: tl, viewport: vp, textDivs: [] });
                        this.computeTextHighlights(content, vp, pageNum);
                    } finally { this.loading = false; }
                },

                // ── Navigation / zoom (zoom preserved across page changes) ──────────
                async prevPage() { if (this.currentPage > 1) { this.currentPage--; await this.renderPage(this.currentPage); } },
                async nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; await this.renderPage(this.currentPage); } },
                async goToPage(v) {
                    let p = parseInt(v);
                    if (isNaN(p)) p = this.currentPage;
                    p = Math.max(1, Math.min(this.totalPages, p));
                    this.currentPage = p; await this.renderPage(p);
                },
                saveScale() { localStorage.setItem('evScale', String(this.scale)); },
                async zoomIn()  { this.scale = Math.min(this.scale + 0.2, 4); this.saveScale(); await this.renderPage(this.currentPage); },
                async zoomOut() { this.scale = Math.max(this.scale - 0.2, 0.4); this.saveScale(); await this.renderPage(this.currentPage); },
                async fitWidth() {
                    if (!this.pageBaseW) return;
                    this.scale = Math.min(Math.max((this.$refs.pdfContainer.clientWidth - 56) / this.pageBaseW, 0.4), 4);
                    this.saveScale(); await this.renderPage(this.currentPage);
                },
                async fitPage() {
                    if (!this.pageBaseW) return;
                    const c = this.$refs.pdfContainer;
                    const s = Math.min((c.clientWidth - 56) / this.pageBaseW, (c.clientHeight - 56) / this.pageBaseH);
                    this.scale = Math.min(Math.max(s, 0.4), 4); this.saveScale(); await this.renderPage(this.currentPage);
                },
                async scrollPdfToPage(page) {
                    if (!page || page === this.currentPage) return;
                    this.currentPage = page; await this.renderPage(page);
                },

                togglePage(page) {
                    const idx = this.openPages.indexOf(page);
                    if (idx >= 0) this.openPages.splice(idx, 1); else this.openPages.push(page);
                },

                // ── Finding navigation ─────────────────────────────────────────────
                active() { return (this.$wire.itemsData || [])[this.activeItemIdx]; },
                async nextItem() {
                    const all = this.$wire.itemsData || []; if (!all.length) return;
                    this.activeItemIdx = this.activeItemIdx < 0 ? 0 : Math.min(this.activeItemIdx + 1, all.length - 1);
                    await this.focusItem(this.activeItemIdx);
                },
                async prevItem() {
                    const all = this.$wire.itemsData || []; if (!all.length || this.activeItemIdx < 0) return;
                    this.activeItemIdx = Math.max(this.activeItemIdx - 1, 0);
                    await this.focusItem(this.activeItemIdx);
                },
                async setActiveById(id) {
                    const idx = (this.$wire.itemsData || []).findIndex(i => i.id === id);
                    if (idx < 0) return;
                    this.activeItemIdx = idx; await this.focusItem(idx);
                },
                async focusItem(idx) {
                    const item = (this.$wire.itemsData || [])[idx];
                    if (!item) return;
                    if (item.page && item.page !== this.currentPage) { this.currentPage = item.page; await this.renderPage(item.page); }
                    const pg = item.page || 0;
                    if (!this.openPages.includes(pg)) this.openPages.push(pg);
                    await this.$nextTick();
                    this.scrollSidebarToItem(item.id);
                },
                scrollSidebarToItem(id) {
                    const el = document.getElementById('evidence-item-' + id);
                    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                },

                // ── Review actions (keyboard fast-path with auto-advance) ──────────
                async confirmActive() { await this.reviewActive('confirm'); },
                async dismissActive() { await this.reviewActive('dismiss'); },
                async reviewActive(method) {
                    const it = this.active(); if (!it) return;
                    const idx = this.activeItemIdx;
                    await this.$wire[method](it.id);
                    this.flashSaved(); this.advance(idx);
                },
                advance(prevIdx) {
                    const list = this.$wire.itemsData || [];
                    if (!list.length) { this.activeItemIdx = -1; this.reviewComplete = true; return; }
                    let start = Math.min(prevIdx, list.length - 1); if (start < 0) start = 0;
                    let found = -1;
                    for (let i = 0; i < list.length; i++) {
                        const idx = (start + i) % list.length;
                        if (list[idx].state === 'unreviewed') { found = idx; break; }
                    }
                    if (found < 0) { this.reviewComplete = true; this.activeItemIdx = Math.min(start, list.length - 1); return; }
                    this.reviewComplete = false; this.activeItemIdx = found; this.focusItem(found);
                },
                editActive() { const it = this.active(); if (it) this.$wire.startEdit(it.id); },
                locateActive() { const it = this.active(); if (it) this.startLocate(it.id, it.quote || ''); },

                flashSaved() { this.saved = true; clearTimeout(this._savedT); this._savedT = setTimeout(() => this.saved = false, 1500); },

                // ── Toast (driven by backend evidence-toast events) ────────────────
                showToast(detail) {
                    this.toast = {
                        visible: true,
                        message: (detail && detail.message) || '',
                        undoId: (detail && detail.undoId != null) ? detail.undoId : null,
                        undoAction: (detail && detail.undoAction) || null,
                    };
                    clearTimeout(this._toastT);
                    this._toastT = setTimeout(() => this.toast.visible = false, 6000);
                },
                undoToast() {
                    if (this.toast.undoAction && this.toast.undoId != null) this.$wire[this.toast.undoAction](this.toast.undoId);
                    this.toast.visible = false;
                },

                // ── Keyboard ───────────────────────────────────────────────────────
                onKey(e) {
                    const tag = (e.target.tagName || '').toLowerCase();
                    const typing = tag === 'input' || tag === 'textarea' || tag === 'select' || e.target.isContentEditable;
                    if (e.key === 'Escape') {
                        if (this.drawMode || this.proposed) this.cancelDraw();
                        else if (this.$wire.editingId) this.$wire.cancelEdit();
                        this.showShortcuts = false;
                        return;
                    }
                    if (typing) return;
                    switch (e.key.toLowerCase()) {
                        case 'c': e.preventDefault(); this.confirmActive(); break;
                        case 'd': e.preventDefault(); this.dismissActive(); break;
                        case 'e': e.preventDefault(); this.editActive(); break;
                        case 'j': case 'arrowdown': e.preventDefault(); this.nextItem(); break;
                        case 'k': case 'arrowup': e.preventDefault(); this.prevItem(); break;
                        case 'l': e.preventDefault(); this.locateActive(); break;
                        case '?': this.showShortcuts = !this.showShortcuts; break;
                    }
                },

                // ── Resize ─────────────────────────────────────────────────────────
                startResize(e) { this.resizing = true; this._rx = e.clientX; this._rw = this.sidebarWidth; e.preventDefault(); },
                onResize(e) {
                    if (!this.resizing) return;
                    let w = this._rw + (this._rx - e.clientX);
                    this.sidebarWidth = Math.min(Math.max(w, 360), 720);
                },
                stopResize() { if (this.resizing) { this.resizing = false; localStorage.setItem('evSidebarW', String(this.sidebarWidth)); } },

                // ── Highlights ─────────────────────────────────────────────────────
                currentPageItems() { return (this.$wire.itemsData || []).filter(i => i.page === this.currentPage || i.page === null); },
                highlightStyle(item) {
                    const bbox = item.bbox || this.textBboxes[item.id];
                    if (!bbox) return 'display:none;';
                    const base = `left:${bbox.x*this.canvasW}px;top:${bbox.y*this.canvasH}px;width:${bbox.width*this.canvasW}px;height:${bbox.height*this.canvasH}px;`;
                    if (item.state === 'dismissed') return base + `background:${item.colour}20;border:1px dashed ${item.colour}80;`;
                    const isActive = item.id === (this.$wire.itemsData || [])[this.activeItemIdx]?.id;
                    if (isActive) return base + `background:${item.colour}90;border:3px solid ${item.colour};box-shadow:0 0 0 3px ${item.colour}50, 0 0 10px ${item.colour}80;`;
                    return base + `background:${item.colour}55;border:2px solid ${item.colour};box-shadow:0 0 0 1px ${item.colour}60;`;
                },
                proposedStyle() {
                    if (!this.proposed || this.proposed.page !== this.currentPage) return 'display:none;';
                    const b = this.proposed.bbox;
                    return `left:${b.x*this.canvasW}px;top:${b.y*this.canvasH}px;width:${b.width*this.canvasW}px;height:${b.height*this.canvasH}px;`;
                },
                computeTextHighlights(content, viewport, pageNum) {
                    const pending = (this.$wire.itemsData || []).filter(i => i.page === pageNum && i.quote && !i.bbox);
                    if (!pending.length) return;
                    const textItems = content.items.filter(i => i.str && i.str.trim().length > 0);
                    let normText = ''; const charToItem = [];
                    for (const ti of textItems) {
                        const norm = ti.str.toLowerCase().replace(/[^a-z0-9]/g, '');
                        for (let j = 0; j < norm.length; j++) charToItem.push(ti);
                        normText += norm;
                    }
                    const bboxes = { ...this.textBboxes };
                    for (const ev of pending) {
                        const normQuote = ev.quote.toLowerCase().replace(/[^a-z0-9]/g, '');
                        if (normQuote.length < 6) continue;
                        let startPos = -1;
                        for (let len = Math.min(normQuote.length, 20); len >= 6; len -= 3) {
                            startPos = normText.indexOf(normQuote.substring(0, len));
                            if (startPos >= 0) break;
                        }
                        if (startPos < 0 || startPos >= charToItem.length) continue;
                        const endPos = Math.min(startPos + normQuote.length - 1, charToItem.length - 1);
                        const startTi = charToItem[startPos]; const endTi = charToItem[endPos];
                        const [startVpX, startVpY] = viewport.convertToViewportPoint(startTi.transform[4], startTi.transform[5]);
                        const [, endVpY] = viewport.convertToViewportPoint(endTi.transform[4], endTi.transform[5]);
                        const fontH = Math.max(Math.abs(startTi.transform[3]) * viewport.scale, startTi.height * viewport.scale, 10);
                        const yTop = startVpY - fontH * 1.15; const yBottom = endVpY + fontH * 0.35;
                        bboxes[ev.id] = {
                            x: Math.max(0, (startVpX - 6) / viewport.width),
                            y: Math.max(0, yTop / viewport.height),
                            width: Math.min(0.97, (viewport.width * 0.92 - startVpX + 6) / viewport.width),
                            height: Math.max((yBottom - yTop) / viewport.height, fontH * 1.5 / viewport.height),
                        };
                    }
                    this.textBboxes = bboxes;
                },

                // ── Draw / locate ──────────────────────────────────────────────────
                bannerText() {
                    if (this.proposed) return 'Evidence location selected — save it to this finding, or cancel.';
                    if (this.locatingId) {
                        const q = (this.locatingQuote || '').length > 60 ? this.locatingQuote.slice(0, 60) + '…' : (this.locatingQuote || 'this finding');
                        return 'Selecting evidence location for: “' + q + '” — draw a box around the supporting text.';
                    }
                    return 'Marking a new evidence area — draw a box on the page.';
                },
                ghostStyle() {
                    if (!this.drawStart || !this.drawCurrent) return '';
                    return `left:${Math.min(this.drawStart.x,this.drawCurrent.x)}px;top:${Math.min(this.drawStart.y,this.drawCurrent.y)}px;`
                        + `width:${Math.abs(this.drawCurrent.x-this.drawStart.x)}px;height:${Math.abs(this.drawCurrent.y-this.drawStart.y)}px;`
                        + `border:2px dashed #7c3aed;background:rgba(124,58,237,.15);pointer-events:none;box-sizing:border-box;`;
                },
                toggleDrawMode() {
                    // Toggling "Mark evidence area" always starts a fresh, non-locate draw.
                    if (this.drawMode && !this.locatingId) { this.cancelDraw(); return; }
                    this.locatingId = null; this.locatingQuote = ''; this.proposed = null;
                    this.drawMode = true; this.drawing = false;
                },
                cancelDraw() { this.drawMode = false; this.drawing = false; this.locatingId = null; this.locatingQuote = ''; this.proposed = null; },
                startLocate(id, quote) { this.locatingId = id; this.locatingQuote = quote || ''; this.proposed = null; this.drawMode = true; this.drawing = false; },
                async saveLocation() {
                    if (!this.proposed || !this.locatingId) return;
                    const id = this.locatingId, p = this.proposed.page, b = this.proposed.bbox;
                    this.proposed = null; this.locatingId = null; this.locatingQuote = ''; this.drawMode = false;
                    await this.$wire.locateItem(id, p, b);
                    this.flashSaved();
                },
                relativePos(event) { const r = this.$refs.pageWrapper.getBoundingClientRect(); return { x: event.clientX - r.left, y: event.clientY - r.top }; },
                onDrawStart(event) { if (!this.drawMode) return; this.drawing = true; this.drawStart = this.relativePos(event); this.drawCurrent = { ...this.drawStart }; },
                onDrawMove(event) { if (this.drawing) this.drawCurrent = this.relativePos(event); },
                onDrawEnd(event) {
                    if (!this.drawing) return;
                    this.drawing = false;
                    const end = this.relativePos(event);
                    const x = Math.min(this.drawStart.x, end.x) / this.canvasW;
                    const y = Math.min(this.drawStart.y, end.y) / this.canvasH;
                    const w = Math.abs(end.x - this.drawStart.x) / this.canvasW;
                    const h = Math.abs(end.y - this.drawStart.y) / this.canvasH;
                    if (w < 0.01 || h < 0.01) { return; }
                    const bbox = { x, y, width: w, height: h };
                    if (this.locatingId) {
                        // Do NOT save yet — hold as a proposed location awaiting confirmation.
                        this.proposed = { page: this.currentPage, bbox };
                        this.drawMode = false;
                    } else {
                        this.drawMode = false;
                        this.$wire.openAddForm(this.currentPage, null, bbox);
                    }
                },
            };
        }
    </script>
    <style>
        [x-cloak] { display: none !important; }

        .ev-viewer { background:#eef1f6; }
        .ev-topbar { background:#fff; border-bottom:1px solid #e2e8f0; }
        .ev-toolbar { background:#f8fafc; border-bottom:1px solid #e2e8f0; row-gap:.5rem; }
        .ev-draw-banner { background:#fef3c7; color:#92400e; border-bottom:1px solid #fde68a; }

        /* ~40px targets for the primary toolbar / header controls. */
        .ev-toolbar .form-select, .ev-toolbar .btn, .ev-toolbar .form-control,
        .ev-topbar .btn { min-height:38px; }

        .ev-pdf { background:#64748b; }
        .ev-resizer { width:7px; cursor:col-resize; background:#e2e8f0; flex-shrink:0; }
        .ev-resizer:hover { background:#c7d2fe; }
        .ev-findings { min-width:360px; max-width:720px; border-left:1px solid #e2e8f0; }

        .ev-dot { display:inline-block; width:.6rem; height:.6rem; border-radius:50%; flex-shrink:0; }

        .ev-chip { display:inline-flex; align-items:center; gap:.25rem; font-size:.72rem; font-weight:600; line-height:1.1;
                   padding:.3rem .55rem; border-radius:1rem; border:1px solid transparent; white-space:nowrap; }
        .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; }
        .ev-current        { background:#dbeafe; color:#1d4ed8; border-color:#93c5fd; }
        .ev-sev-high   { background:#fee2e2; color:#b91c1c; border-color:#fecaca; }
        .ev-sev-medium { background:#fef3c7; color:#b45309; border-color:#fde68a; }
        .ev-sev-low    { background:#f1f5f9; color:#475569; border-color:#e2e8f0; }
        .ev-src-ai     { background:#ede9fe; color:#6d28d9; border-color:#ddd6fe; }
        .ev-src-human  { background:#dbeafe; color:#1d4ed8; border-color:#bfdbfe; }

        .ev-field-label { font-size:.72rem; font-weight:700; text-transform:uppercase; letter-spacing:.02em; color:#64748b; margin-bottom:.25rem; }
        .ev-source-quote { font-size:.88rem; line-height:1.55; font-style:italic; color:#334155; border-left:3px solid #cbd5e1; padding-left:.7rem; margin:0; }
        .ev-interp { font-size:.88rem; line-height:1.55; color:#1e293b; margin:0; }
        .ev-clamp { display:-webkit-box; -webkit-line-clamp:5; -webkit-box-orient:vertical; overflow:hidden; }

        .ev-action { font-size:.8rem; padding:.45rem .75rem; min-height:40px; display:inline-flex; align-items:center; gap:.3rem; }

        .evidence-card { transition: box-shadow .12s, outline .1s; cursor:pointer; }
        .evidence-card:hover { box-shadow:0 2px 8px rgba(0,0,0,.12) !important; }
        .evidence-card.active-item {
            outline:3px solid #2563eb; outline-offset:0;
            border:1px solid #2563eb !important;
            background:#eff6ff !important;
            opacity:1 !important;
            box-shadow:0 0 0 4px rgba(37,99,235,.15) !important;
        }

        .synapse-highlight { transition: background .12s; }
        .synapse-highlight:hover { filter: brightness(0.85); z-index:10; }
        /* Proposed (unsaved) evidence location — visually distinct from saved highlights. */
        .ev-proposed-box { border:2px dashed #ea580c; background:rgba(234,88,12,.18); border-radius:2px; box-shadow:0 0 0 2px rgba(234,88,12,.25); }

        .ev-toast { position:fixed; bottom:1.25rem; left:50%; transform:translateX(-50%); z-index:1080; }

        .ev-viewer .btn:focus-visible, .ev-viewer .form-select:focus-visible,
        .ev-viewer .form-control:focus-visible, .ev-viewer .form-check-input:focus-visible {
            outline:2px solid #2563eb; outline-offset:1px;
        }

        @media (max-width: 992px) {
            .ev-findings { max-width:none; }
        }
    </style>
@endpush
