<div class="card shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <h4 class="fw-bold mb-0">Documents</h4>

            <div class="d-flex gap-2">
                <select wire:model.live="filterType" class="form-select form-select-sm" style="width: 200px;">
                    <option value="">All Document Types</option>
                    @foreach($types as $type)
                        <option value="{{ $type->id }}">{{ $type->display_name }}</option>
                    @endforeach
                </select>

                @can('documents.upload')
                    <button class="btn btn-primary btn-sm" wire:click.prevent="openAddDoc">
                        <i class="mdi mdi-plus"></i>
                    </button>
                @endcan
            </div>
        </div>

        @can('documents.upload')
        @if($openAD)
            <div>
                <div class="offcanvas offcanvas-end show"  tabindex="-1" style="--bs-offcanvas-width: 600px;" role="dialog">
                    <div class="offcanvas-header">
                        <h5 id="offcanvasRightLabel">Add New Document</h5>
                        <button type="button" class="btn-close text-dark" wire:click.prevent="closeAddDoc"></button>
                    </div>

                    <div class="offcanvas-body  bg-light">
                        <form wire:submit="save">

                            <div wire:loading wire:target="doc">Uploading...</div>
                            @csrf


                            <x-ui.input name="display_name" label="Display Name"/>
                            <x-ui.select name="document_type_id" label="Document Type" :options="$docTypes"/>

                            <div
                                    x-data="{
        isDropping: false,
        uploading: false,
        progress: 0,
    }"
                                    x-on:livewire-upload-start="uploading = true"
                                    x-on:livewire-upload-finish="uploading = false; progress = 0"
                                    x-on:livewire-upload-error="uploading = false"
                                    x-on:livewire-upload-progress="progress = $event.detail.progress"
                            >

                                <!-- HIDDEN INPUT -->
                                <input
                                        type="file"
                                        wire:model.live="doc"
                                        class="mb-4"
                                >

                                <!-- PROGRESS BARRR OMG YESSS -->
                                <div x-show="uploading" class="mt-2">
                                    <progress max="100" x-bind:value="progress" class="w-100"></progress>
                                    <p class="mt-1 fw-bold">Uploading: <span x-text="progress"></span>%</p>
                                </div>

                                @error('doc')
                                <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>


                            @error('doc') <span class="error">{{ $message }}</span> @enderror

                            <button type="submit">Save</button>
                        </form>

                    </div>
                </div>
            </div>
        @endif
        @endcan

        @if($docs->count())
            <table class="table table-centered table-striped mb-0">
                <thead>
                <tr>
                    <th style="max-width: 150px;">Name</th>
                    <th>Type</th>
                    <th>User</th>
                    <th>Date</th>
                    @can('synapse.use')<th>Synapse</th>@endcan
                    <th></th>
                </tr>
                </thead>

                <tbody>
                @foreach($docs as $doc)
                    <tr>
                        <td style="max-width: 150px;">
                            {{ $doc->display_name }}
                            <br><small class="text-primary">{{ $doc->file_size }}</small>
                        </td>
                        <td>{{ $doc->type->display_name ?? '—' }}</td>
                        <td>{{ $doc->user ? ($doc->user->name_first . " " . $doc->user->name_last) : 'Unknown' }}</td>
                        <td>
                            {{ $doc->created_at->diffForHumans() }}
                            <br><small class="text-primary">{{ $doc->created_at->format('d/m/Y H:i') }}</small>
                        </td>
                        @can('synapse.use')
                        <td>
                            @if(in_array($doc->file_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp', 'image/gif']))
                                @php
                                    $run     = $latestRuns[$doc->id] ?? null;
                                    $outcome = $run?->result['outcome'] ?? null;
                                    $evStatus = $doc->evidence_status ?? null;
                                    $evCount  = $evidenceCounts[$doc->id] ?? 0;
                                @endphp
                                <div class="dropdown">
                                    <button class="btn btn-sm p-0 border-0 bg-transparent d-flex align-items-center gap-1"
                                            data-bs-toggle="dropdown" aria-expanded="false" style="line-height:1;">
                                        {{-- Review score / brain icon --}}
                                        @if($run)
                                            <span class="badge @switch($outcome)
                                                @case('ACCEPTABLE') bg-success @break
                                                @case('NEEDS_RESCAN') bg-warning text-dark @break
                                                @case('SUSPICIOUS') text-white @break
                                                @default bg-secondary @endswitch"
                                                style="font-size:.6rem;@if($outcome === 'SUSPICIOUS') background:#b45309; @endif">
                                                {{ $run->result['overall_score'] ?? '–' }}
                                            </span>
                                        @else
                                            <i class="mdi mdi-brain" style="color:#7c3aed;font-size:1.1rem;"></i>
                                        @endif

                                        {{-- Evidence status indicator --}}
                                        @if($evStatus === 'processing')
                                            <span class="spinner-border text-info"
                                                  style="width:.65rem;height:.65rem;border-width:.15em;"
                                                  title="Extracting evidence…"></span>
                                        @elseif($evStatus === 'completed' && $evCount > 0)
                                            <span class="badge bg-info-subtle text-info border border-info-subtle"
                                                  style="font-size:.55rem;" title="{{ $evCount }} evidence items">
                                                {{ $evCount }}<i class="mdi mdi-shield-check ms-1"></i>
                                            </span>
                                        @elseif($evStatus === 'failed')
                                            <i class="mdi mdi-alert-circle-outline text-danger"
                                               style="font-size:.8rem;" title="Evidence extraction failed"></i>
                                        @endif

                                        <i class="mdi mdi-chevron-down opacity-50" style="font-size:.7rem;"></i>
                                    </button>

                                    <ul class="dropdown-menu dropdown-menu-end shadow-sm" style="font-size:.82rem;min-width:170px;">
                                        <li>
                                            <button class="dropdown-item py-1" wire:click="openSynapse({{ $doc->id }}, 'review')">
                                                <i class="mdi mdi-file-check-outline me-2 text-muted"></i>Review Document
                                            </button>
                                        </li>
                                        <li>
                                            <button class="dropdown-item py-1" wire:click="openSynapse({{ $doc->id }}, 'extract')">
                                                <i class="mdi mdi-form-textbox me-2 text-muted"></i>Extract Data
                                            </button>
                                        </li>
                                        <li><hr class="dropdown-divider my-1"></li>
                                        <li>
                                            <button class="dropdown-item py-1" wire:click="openSynapse({{ $doc->id }}, 'evidence')">
                                                <i class="mdi mdi-shield-search me-2" style="color:#7c3aed;"></i>Extract Evidence
                                            </button>
                                        </li>
                                    </ul>
                                </div>
                            @endif
                        </td>
                        @endcan
                        <td class="text-end">
                            <a href="{{ route('documents.view', $doc) }}" type="button" class="btn btn-md" >
                                <i class="mdi mdi-search-web text-primary"></i>
                            </a>
                            @can('documents.print')
                                @if($doc->file_type == 'pdf')
                                    <a class="btn btn-md" wire:click="print({{ $doc->id }})">
                                        <i class="mdi mdi-printer text-primary"></i>
                                    </a>
                                @endif
                            @endcan
                            @can('documents.delete')
                                <span
                                        wire:confirm="Are you sure you want to delete this document?"
                                        wire:click="deleteDocument({{ $doc->id }})" class="btn btn-md">
                                    <i class="mdi mdi-delete text-danger text-lg"></i>
                                </span>
                            @endcan
                        </td>
                    </tr>
                @endforeach
                </tbody>
            </table>
            {{ $docs->links() }}

            @can('synapse.use')
            @if($synapseOpen)
                <div class="offcanvas offcanvas-end show" tabindex="-1" style="--bs-offcanvas-width: 520px;" role="dialog">

                    {{-- Header --}}
                    <div class="offcanvas-header border-bottom pb-2" style="border-top:3px solid #7c3aed;">
                        <div class="d-flex align-items-center gap-2">
                            <span class="badge text-white" style="background-color:#7c3aed;font-size:.65rem;">
                                <i class="mdi mdi-brain"></i> Synapse
                            </span>
                            <h6 class="mb-0 fw-semibold">Document Intelligence</h6>
                        </div>
                        <button type="button" class="btn-close" wire:click="closeSynapse"></button>
                    </div>

                    {{-- Tab nav --}}
                    <div class="border-bottom px-3 pt-2 pb-0">
                        <ul class="nav nav-tabs" style="font-size:.78rem;--bs-nav-tabs-border-width:2px;">
                            <li class="nav-item">
                                <button wire:click="$set('synapseTab','review')"
                                        class="nav-link py-1 px-2 @if($synapseTab==='review') active fw-semibold @endif">
                                    <i class="mdi mdi-file-check-outline me-1"></i>Review
                                </button>
                            </li>
                            <li class="nav-item">
                                <button wire:click="$set('synapseTab','extract')"
                                        class="nav-link py-1 px-2 @if($synapseTab==='extract') active fw-semibold @endif">
                                    <i class="mdi mdi-form-textbox me-1"></i>Data
                                </button>
                            </li>
                            <li class="nav-item">
                                <button wire:click="$set('synapseTab','evidence')"
                                        class="nav-link py-1 px-2 @if($synapseTab==='evidence') active fw-semibold @endif">
                                    <i class="mdi mdi-shield-search me-1"></i>Evidence
                                    @if($synapseEvidenceCount > 0)
                                        <span class="badge bg-info-subtle text-info ms-1" style="font-size:.55rem;">{{ $synapseEvidenceCount }}</span>
                                    @endif
                                </button>
                            </li>
                        </ul>
                    </div>

                    <div class="offcanvas-body bg-light d-flex flex-column gap-3">

                        {{-- ── Review tab ── --}}
                        @if($synapseTab === 'review')

                            @if($synapseRunning)
                                <div class="text-center py-5 text-muted">
                                    <div class="spinner-border mb-3" style="color:#7c3aed;"></div>
                                    <p class="small mb-0">Analysing document…</p>
                                </div>

                            @elseif($synapseError)
                                <div class="alert alert-danger py-2 px-3 small mb-0">
                                    <i class="mdi mdi-alert-circle-outline me-1"></i>{{ $synapseError }}
                                </div>
                                <button wire:click="runSynapseReview" wire:loading.attr="disabled"
                                        class="btn btn-sm text-white align-self-start" style="background-color:#7c3aed;">
                                    <i class="mdi mdi-refresh me-1"></i>Retry
                                </button>

                            @elseif($synapseRan && $synapseResult)
                                @php
                                    $outcome = $synapseResult['outcome'] ?? '';
                                    $outcomeClass = match($outcome) {
                                        'ACCEPTABLE'   => 'bg-success',
                                        'NEEDS_RESCAN' => 'bg-warning text-dark',
                                        'SUSPICIOUS'   => 'text-white',
                                        default        => 'bg-danger',
                                    };
                                    $sectionLabels = [
                                        'image_quality' => 'Image Quality',
                                        'data_fields'   => 'Visible Data Fields',
                                        'completeness'  => 'Completeness',
                                        'authenticity'  => 'Authenticity',
                                    ];
                                @endphp

                                <div class="rounded p-3 d-flex align-items-center justify-content-between" style="background:#f5f3ff;">
                                    <div>
                                        <div class="fw-bold lh-1" style="font-size:2.2rem;color:#7c3aed;">{{ $synapseResult['overall_score'] }}</div>
                                        <small class="text-muted">out of 100</small>
                                    </div>
                                    <span class="badge fs-6 px-3 py-2 {{ $outcomeClass }}"
                                          @if($outcome === 'SUSPICIOUS') style="background:#b45309;" @endif>
                                        {{ str_replace('_', ' ', $outcome) }}
                                    </span>
                                </div>

                                @foreach($synapseResult['sections'] as $key => $section)
                                    <div class="rounded p-3 bg-white border">
                                        <div class="d-flex justify-content-between mb-1">
                                            <small class="fw-semibold text-uppercase" style="font-size:.65rem;letter-spacing:.05em;color:#7c3aed;">
                                                {{ $sectionLabels[$key] ?? $key }}
                                            </small>
                                            <small class="fw-semibold">{{ $section['score'] }}/{{ $section['max'] }}</small>
                                        </div>
                                        <div class="progress mb-2" style="height:3px;background:#e9e3ff;">
                                            <div class="progress-bar" style="width:{{ $section['max'] > 0 ? round($section['score'] / $section['max'] * 100) : 0 }}%;background:#7c3aed;"></div>
                                        </div>
                                        <p class="mb-0 small text-muted">{{ $section['notes'] }}</p>
                                    </div>
                                @endforeach

                                <div class="rounded p-3 bg-white border">
                                    <small class="fw-semibold text-uppercase d-block mb-1" style="font-size:.65rem;letter-spacing:.05em;">Summary</small>
                                    <p class="mb-0 small">{{ $synapseResult['summary'] }}</p>
                                </div>

                                <div class="rounded p-3 bg-white border">
                                    <small class="fw-semibold text-uppercase d-block mb-1" style="font-size:.65rem;letter-spacing:.05em;">Recommended Actions</small>
                                    <p class="mb-0 small">{{ $synapseResult['recommended_actions'] }}</p>
                                </div>

                                <button wire:click="runSynapseReview" wire:loading.attr="disabled"
                                        class="btn btn-sm btn-outline-secondary align-self-start">
                                    <i class="mdi mdi-refresh me-1"></i>Re-run Review
                                </button>
                                <small class="text-muted" style="font-size:.65rem;">
                                    <i class="mdi mdi-information-outline me-1"></i>Output only — act manually.
                                </small>

                            @else
                                <p class="text-muted small mb-2">Assess this document's quality and authenticity.</p>
                                <button wire:click="runSynapseReview" wire:loading.attr="disabled"
                                        class="btn btn-sm text-white align-self-start" style="background-color:#7c3aed;">
                                    <i class="mdi mdi-file-check-outline me-1"></i>Run Review
                                </button>
                            @endif

                        {{-- ── Data Extraction tab ── --}}
                        @elseif($synapseTab === 'extract')

                            @if($synapseExtracting)
                                <div class="text-center py-5 text-muted">
                                    <div class="spinner-border spinner-border-sm mb-2" style="color:#7c3aed;"></div>
                                    <p class="small mb-0">Extracting fields…</p>
                                </div>

                            @elseif($synapseExtractError)
                                <div class="alert alert-danger py-2 px-3 small mb-0">
                                    <i class="mdi mdi-alert-circle-outline me-1"></i>{{ $synapseExtractError }}
                                </div>
                                <button wire:click="runSynapseExtract" wire:loading.attr="disabled"
                                        class="btn btn-sm text-white align-self-start" style="background-color:#7c3aed;">
                                    <i class="mdi mdi-refresh me-1"></i>Retry
                                </button>

                            @elseif($synapseExtracted && $synapseExtractResult)
                                @php
                                    $confidenceClass = match($synapseExtractResult['confidence'] ?? '') {
                                        'high'   => 'bg-success',
                                        'medium' => 'bg-warning text-dark',
                                        default  => 'bg-danger',
                                    };
                                    $fields = [
                                        'full_name'          => 'Full Name',
                                        'date_of_birth'      => 'Date of Birth',
                                        'issue_date'         => 'Issue Date',
                                        'expiry_date'        => 'Expiry Date',
                                        'address'            => 'Address',
                                        'document_reference' => 'Reference',
                                        'issuing_authority'  => 'Issuing Authority',
                                    ];
                                @endphp
                                <div class="rounded p-3 bg-white border">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <span class="fw-semibold small">{{ $synapseExtractResult['document_type'] ?? '—' }}</span>
                                        <span class="badge {{ $confidenceClass }}" style="font-size:.65rem;">
                                            {{ ucfirst($synapseExtractResult['confidence'] ?? '') }} confidence
                                        </span>
                                    </div>
                                    <table class="table table-sm mb-2" style="font-size:.8rem;">
                                        <tbody>
                                        @foreach($fields as $key => $label)
                                            @if(!is_null($synapseExtractResult[$key] ?? null))
                                            <tr>
                                                <td class="text-muted ps-0 border-0" style="width:40%;">{{ $label }}</td>
                                                <td class="fw-medium border-0">{{ $synapseExtractResult[$key] }}</td>
                                            </tr>
                                            @endif
                                        @endforeach
                                        <tr>
                                            <td class="text-muted ps-0 border-0">Signature</td>
                                            <td class="border-0">
                                                @if($synapseExtractResult['signature_present'] ?? false)
                                                    <span class="badge bg-success" style="font-size:.65rem;">Present</span>
                                                @else
                                                    <span class="badge bg-secondary" style="font-size:.65rem;">Not detected</span>
                                                @endif
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted ps-0 border-0">Photograph</td>
                                            <td class="border-0">
                                                @if($synapseExtractResult['photograph_present'] ?? false)
                                                    <span class="badge bg-success" style="font-size:.65rem;">Present</span>
                                                @else
                                                    <span class="badge bg-secondary" style="font-size:.65rem;">Not detected</span>
                                                @endif
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <button wire:click="runSynapseExtract" wire:loading.attr="disabled"
                                        class="btn btn-sm btn-outline-secondary align-self-start" style="font-size:.7rem;">
                                    <i class="mdi mdi-refresh me-1"></i>Re-extract
                                </button>

                            @else
                                <p class="text-muted small mb-2">Pull structured fields (name, DOB, reference, etc.) from this document.</p>
                                <button wire:click="runSynapseExtract" wire:loading.attr="disabled"
                                        class="btn btn-sm text-white align-self-start" style="background-color:#7c3aed;">
                                    <span wire:loading.remove wire:target="runSynapseExtract">
                                        <i class="mdi mdi-form-textbox me-1"></i>Extract Data
                                    </span>
                                    <span wire:loading wire:target="runSynapseExtract">
                                        <span class="spinner-border spinner-border-sm me-1"></span>Extracting…
                                    </span>
                                </button>
                            @endif

                        {{-- ── Evidence tab ── --}}
                        @elseif($synapseTab === 'evidence')

                            @if($synapseEvidenceStatus === 'processing')
                                <div class="text-center py-5 text-muted" wire:poll.3000ms="refreshEvidenceStatus">
                                    <div class="spinner-border mb-3" style="color:#7c3aed;"></div>
                                    <p class="small mb-0">Extracting evidence…</p>
                                    <p class="small text-muted mt-1" style="font-size:.7rem;">This runs in the background and may take a minute.</p>
                                </div>

                            @elseif($synapseEvidenceStatus === 'completed')
                                @if(count($synapseEvidenceItems) > 0)
                                    <div class="d-flex flex-column gap-2">
                                        @foreach($synapseEvidenceItems as $item)
                                            @php
                                                $colour = \App\Models\Dsar\DsarEvidenceItem::categoryColour($item['category']);
                                                $label  = \App\Models\Dsar\DsarEvidenceItem::categoryLabel($item['category']);
                                            @endphp
                                            <div class="card border-0 shadow-sm"
                                                 style="border-left:4px solid {{ $colour }} !important;{{ $item['dismissed_at'] ? 'opacity:.45;' : '' }}">
                                                <div class="card-body p-2">
                                                    <div class="d-flex align-items-center gap-1 flex-wrap mb-1">
                                                        <span class="badge rounded-pill"
                                                              style="background:{{ $colour }}20;color:{{ $colour }};border:1px solid {{ $colour }}50;font-size:.6rem;">
                                                            {{ $label }}
                                                        </span>
                                                        <span class="badge rounded-pill bg-{{ $item['severity'] === 'high' ? 'danger' : ($item['severity'] === 'medium' ? 'warning text-dark' : 'secondary') }}-subtle"
                                                              style="font-size:.6rem;">
                                                            {{ ucfirst($item['severity']) }}
                                                        </span>
                                                        @if($item['page'])
                                                            <span class="badge bg-light text-secondary border" style="font-size:.6rem;">p.{{ $item['page'] }}</span>
                                                        @endif
                                                        <span class="badge text-white" style="background:#7c3aed;font-size:.55rem;">
                                                            <i class="mdi mdi-brain me-1"></i>Synapse
                                                        </span>
                                                        @if($item['confirmed_at'])
                                                            <i class="mdi mdi-check-circle text-success ms-auto" title="Confirmed"></i>
                                                        @endif
                                                    </div>
                                                    @if($item['quote'])
                                                        <blockquote class="small fst-italic text-muted mb-1 ps-2 border-start"
                                                                    style="font-size:.72rem;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;">
                                                            {{ $item['quote'] }}
                                                        </blockquote>
                                                    @endif
                                                    <p class="small mb-2" style="font-size:.75rem;">{{ $item['comment'] }}</p>
                                                    <div class="d-flex gap-1">
                                                        @if(!$item['confirmed_at'])
                                                            <button wire:click="confirmEvidenceItem({{ $item['id'] }})"
                                                                    class="btn btn-xs btn-outline-success"
                                                                    style="font-size:.65rem;padding:.15rem .4rem;">
                                                                <i class="mdi mdi-check"></i> Confirm
                                                            </button>
                                                        @endif
                                                        @if(!$item['dismissed_at'])
                                                            <button wire:click="dismissEvidenceItem({{ $item['id'] }})"
                                                                    class="btn btn-xs btn-outline-secondary"
                                                                    style="font-size:.65rem;padding:.15rem .4rem;">
                                                                <i class="mdi mdi-close"></i> Dismiss
                                                            </button>
                                                        @endif
                                                        @if($item['confirmed_at'] || $item['dismissed_at'])
                                                            <button wire:click="confirmEvidenceItem({{ $item['id'] }})"
                                                                    class="btn btn-xs btn-outline-secondary"
                                                                    style="font-size:.65rem;padding:.15rem .4rem;"
                                                                    title="Undo">
                                                                <i class="mdi mdi-undo"></i>
                                                            </button>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                    <button wire:click="rescanEvidence"
                                            wire:confirm="Rescan this document? All AI-extracted evidence items will be deleted and re-extracted with the latest categories."
                                            wire:loading.attr="disabled"
                                            wire:target="rescanEvidence"
                                            class="btn btn-sm btn-outline-secondary align-self-start" style="font-size:.7rem;">
                                        <span wire:loading.remove wire:target="rescanEvidence">
                                            <i class="mdi mdi-refresh me-1"></i>Rescan
                                        </span>
                                        <span wire:loading wire:target="rescanEvidence">
                                            <span class="spinner-border spinner-border-sm me-1" style="width:.6rem;height:.6rem;"></span>Starting…
                                        </span>
                                    </button>
                                @else
                                    <div class="text-center py-4 text-muted">
                                        <i class="mdi mdi-shield-check-outline d-block mb-2 opacity-25" style="font-size:2.5rem;"></i>
                                        <p class="small mb-2">No evidence items found in this document.</p>
                                    </div>
                                    <button wire:click="rescanEvidence"
                                            wire:confirm="Rescan this document? All AI-extracted evidence items will be deleted and re-extracted with the latest categories."
                                            wire:loading.attr="disabled"
                                            wire:target="rescanEvidence"
                                            class="btn btn-sm btn-outline-secondary align-self-start" style="font-size:.7rem;">
                                        <span wire:loading.remove wire:target="rescanEvidence">
                                            <i class="mdi mdi-refresh me-1"></i>Rescan
                                        </span>
                                        <span wire:loading wire:target="rescanEvidence">
                                            <span class="spinner-border spinner-border-sm me-1" style="width:.6rem;height:.6rem;"></span>Starting…
                                        </span>
                                    </button>
                                @endif

                            @elseif($synapseEvidenceStatus === 'skipped')
                                <div class="alert alert-warning py-2 px-3 small mb-0">
                                    <i class="mdi mdi-information-outline me-1"></i>
                                    This document was not identified as a personal data record — evidence extraction was skipped.
                                </div>
                                <button wire:click="extractEvidence"
                                        class="btn btn-sm btn-outline-secondary align-self-start" style="font-size:.7rem;">
                                    <i class="mdi mdi-refresh me-1"></i>Run anyway
                                </button>

                            @elseif($synapseEvidenceStatus === 'failed')
                                <div class="alert alert-danger py-2 px-3 small mb-0">
                                    <i class="mdi mdi-alert-circle-outline me-1"></i>Evidence extraction failed. Please try again.
                                </div>
                                <button wire:click="extractEvidence"
                                        class="btn btn-sm text-white align-self-start" style="background:#7c3aed;">
                                    <i class="mdi mdi-refresh me-1"></i>Retry
                                </button>

                            @else
                                <p class="text-muted small mb-1">
                                    Extract evidence passages from this document using Synapse AI — the same pipeline used for DSAR attachments.
                                </p>
                                <button wire:click="extractEvidence" wire:loading.attr="disabled"
                                        class="btn btn-sm text-white align-self-start" style="background-color:#7c3aed;">
                                    <i class="mdi mdi-shield-search me-1"></i>Extract Evidence
                                </button>
                                <small class="text-muted" style="font-size:.65rem;">
                                    <i class="mdi mdi-information-outline me-1"></i>Runs in the background. Results appear here when complete.
                                </small>
                            @endif

                        @endif

                    </div>
                </div>
            @endif
            @endcan

        @else
            <div class="text-center p-5 text-muted">
                <i class="mdi mdi-file-document" style="font-size: 48px;"></i>
                <p class="mt-3 fw-bold">No documents have been added.</p>
            </div>
        @endif

    </div>

    {{-- ── DOCUMENT PREVIEW MODAL ─────────────────────────────────────── --}}
    @teleport('body')
    <div
        x-data="{
        open: false,
        url: '',
        download: '',
        filename: '',
        mime: '',
        docxHtml: null,
        docxLoading: false,
        docxError: false,
        isImage()  { return this.mime.startsWith('image/'); },
        isPdf()    { return this.mime === 'application/pdf'; },
        isDocx()   { return this.mime.includes('wordprocessingml'); },
        isAudio()  { return this.mime.startsWith('audio/'); },
        async loadDocx() {
            this.docxLoading = true;
            this.docxError   = false;
            try {
                const { default: mammoth } = await import('mammoth');
                const res    = await fetch(this.url);
                const buffer = await res.arrayBuffer();
                const result = await mammoth.convertToHtml({ arrayBuffer: buffer });
                this.docxHtml    = result.value;
                this.docxLoading = false;
            } catch (e) {
                this.docxError   = true;
                this.docxLoading = false;
            }
        },
    }"
    x-on:open-doc-preview.window="
        url      = $event.detail.url;
        download = $event.detail.download;
        filename = $event.detail.filename;
        mime     = $event.detail.mime;
        docxHtml = null; docxLoading = false; docxError = false;
        open = true;
        if (isDocx()) loadDocx();
    "
    x-on:keydown.escape.window="open = false"
    x-show="open"
    x-cloak
    style="position:fixed;inset:0;z-index:1060;"
>
    {{-- Centering wrapper (separate from x-show so display:flex is never clobbered) --}}
    <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;">

    {{-- Backdrop --}}
    <div
        x-on:click="open = false"
        x-transition:enter="transition-opacity duration-200"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        style="position:absolute;inset:0;background:rgba(0,0,0,.65);"
    ></div>

    {{-- Panel --}}
    <div class="bg-white rounded shadow-lg d-flex flex-column"
         style="position:relative;z-index:1;width:90vw;max-width:1100px;height:88vh;overflow:hidden;"
         x-transition:enter="transition-all duration-200"
         x-transition:enter-start="opacity-0 transform scale-95"
         x-transition:enter-end="opacity-100 transform scale-100"
         x-on:click.stop>

        {{-- Header --}}
        <div class="d-flex align-items-center gap-2 px-3 py-2 border-bottom flex-shrink-0">
            <i class="mdi mdi-file-document-outline text-muted"></i>
            <span class="fw-medium text-truncate flex-grow-1" x-text="filename" style="font-size:.9rem;"></span>
            <a :href="download"
               class="btn btn-sm btn-outline-secondary py-0 px-2"
               style="font-size:.78rem;"
               title="Download">
                <i class="mdi mdi-download me-1"></i>Download
            </a>
            <button type="button"
                    class="btn btn-sm btn-outline-secondary py-0 px-2"
                    x-on:click="open = false"
                    title="Close (Esc)">
                <i class="mdi mdi-close"></i>
            </button>
        </div>

        {{-- Body --}}
        <div class="flex-grow-1 overflow-hidden d-flex align-items-center justify-content-center bg-light" style="padding:0;">

            <template x-if="isImage()">
                <div class="w-100 h-100 d-flex align-items-center justify-content-center p-3">
                    <img :src="url" :alt="filename"
                         style="max-width:100%;max-height:100%;object-fit:contain;display:block;border-radius:.25rem;" />
                </div>
            </template>

            <template x-if="isPdf()">
                <iframe :src="url"
                        style="width:100%;height:100%;border:0;"></iframe>
            </template>

            <template x-if="isDocx()">
                <div class="w-100 h-100 overflow-auto p-4">
                    <template x-if="docxLoading">
                        <div class="d-flex align-items-center justify-content-center py-5 text-muted">
                            <div class="spinner-border spinner-border-sm me-2"></div>
                            Converting document…
                        </div>
                    </template>
                    <template x-if="docxError">
                        <div class="text-center text-muted py-5">
                            <i class="mdi mdi-alert-circle-outline fs-2 d-block mb-2"></i>
                            Preview unavailable — <a :href="download">download the file</a> to view it.
                        </div>
                    </template>
                    <template x-if="docxHtml !== null && !docxLoading && !docxError">
                        <div class="mx-auto" style="max-width:800px;" x-html="docxHtml"></div>
                    </template>
                </div>
            </template>

            <template x-if="isAudio()">
                <div class="d-flex flex-column align-items-center justify-content-center gap-3 p-4 w-100">
                    <i class="mdi mdi-music-note text-primary" style="font-size:3rem;"></i>
                    <p class="text-muted mb-0 fw-medium" x-text="filename"></p>
                    <audio :src="url" controls class="w-100" style="max-width:500px;"></audio>
                </div>
            </template>

            <template x-if="!isImage() && !isPdf() && !isDocx() && !isAudio()">
                <div class="text-center text-muted p-5">
                    <i class="mdi mdi-file-outline d-block mb-2" style="font-size:3rem;"></i>
                    Preview not available for this file type.
                    <br>
                    <a :href="download" class="btn btn-sm btn-outline-primary mt-3">
                        <i class="mdi mdi-download me-1"></i>Download to view
                    </a>
                </div>
            </template>

        </div>
    </div>
    </div>{{-- /centering wrapper --}}
    </div>
    @endteleport
</div>