<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>Score</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(isset($latestRuns[$doc->id]))
                                @php $run = $latestRuns[$doc->id]; $outcome = $run->result['outcome'] ?? ''; @endphp
                                <button wire:click="openSynapse({{ $doc->id }})" class="btn btn-sm p-0 border-0 bg-transparent text-start">
                                    <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-danger @endswitch"
                                        @if($outcome === 'SUSPICIOUS') style="background:#b45309;" @endif>
                                        {{ str_replace('_', ' ', $outcome) }}
                                    </span>
                                    <small class="d-block text-muted">{{ $run->result['overall_score'] }}/100</small>
                                </button>
                            @elseif(in_array($doc->file_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp', 'image/gif']))
                                <button wire:click="openSynapse({{ $doc->id }})" class="btn btn-sm p-0 border-0 bg-transparent" title="Run Synapse review">
                                    <i class="mdi mdi-brain" style="color:#7c3aed;font-size:1.1rem;"></i>
                                </button>
                            @endif
                        </td>
                        @endcan
                        <td class="text-end">
                            <a wire:navigate href="{{ \Illuminate\Support\Facades\Storage::url($doc->owner->getDocumentStoragePath() . $doc->file_name) }}" class="btn btn-md" target="_blank">
                                <i class="mdi mdi-search-web text-primary"></i>
                            </a>
                            @can('documents.print')
                                @if($doc->file_type == 'application/pdf')
                                    <a wire:navigate 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">
                    <div class="offcanvas-header border-bottom" 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 Review</h6>
                        </div>
                        <button type="button" class="btn-close text-dark" wire:click="closeSynapse"></button>
                    </div>

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

                        @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

                            {{-- Score header --}}
                            <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>

                            {{-- Section scores --}}
                            @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

                            {{-- Summary --}}
                            <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>

                            {{-- Recommended actions --}}
                            <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">Run Synapse to 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 ── --}}
                        <hr class="my-1">
                        <div class="d-flex align-items-center justify-content-between">
                            <small class="fw-semibold text-uppercase" style="font-size:.65rem;letter-spacing:.05em;color:#7c3aed;">
                                <i class="mdi mdi-form-textbox me-1"></i>Data Extraction
                            </small>
                            @if($synapseExtracted)
                                <button wire:click="runSynapseExtract" wire:loading.attr="disabled"
                                        class="btn btn-sm btn-outline-secondary py-0 px-2" style="font-size:.7rem;">
                                    <span wire:loading.remove wire:target="runSynapseExtract"><i class="mdi mdi-refresh"></i> Re-extract</span>
                                    <span wire:loading wire:target="runSynapseExtract"><span class="spinner-border spinner-border-sm"></span></span>
                                </button>
                            @endif
                        </div>

                        @if($synapseExtracting)
                            <div class="text-center py-3 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>

                        @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>

                        @else
                            <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

                    </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>
</div>