<div>
    @if (session()->has('message'))
        <div class="mb-4 p-3 bg-green-100 text-green-800 rounded-lg text-sm">{{ session('message') }}</div>
    @endif

    <div class="flex items-center justify-between mb-4">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Expediente Digital — Procesos</h1>
            <p class="text-sm text-gray-500 mt-1">Gestión de procesos jurídicos de cobranza</p>
        </div>
    </div>

    {{-- ════════ B5.3: KPIs Listado ════════ --}}
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
        {{-- KPI 1: Total Procesos --}}
        <div class="bg-white shadow-sm rounded-lg p-4 border-l-4 border-indigo-500">
            <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">Total Procesos</div>
            <div class="text-3xl font-bold text-gray-900 mt-1">{{ number_format($totalProcesos) }}</div>
            <div class="text-xs text-gray-400 mt-1">Filtrados según criterios</div>
        </div>
        {{-- KPI 2: Total Deuda en Proceso --}}
        <div class="bg-white shadow-sm rounded-lg p-4 border-l-4 border-emerald-500">
            <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">Total Deuda en Proceso</div>
            {{-- B5.3-fix: Formato Compacto Deuda --}}
            @php
                $deudaFormatted = $totalDeuda >= 1000000000
                    ? '$' . number_format($totalDeuda / 1000000000, 1, ',', '.') . ' MM'
                    : ($totalDeuda >= 1000000
                        ? '$' . number_format($totalDeuda / 1000000, 1, ',', '.') . ' M'
                        : '$' . number_format($totalDeuda, 0, ',', '.'));
                $deudaExacta = '$' . number_format($totalDeuda, 0, ',', '.');
            @endphp
            <div class="text-2xl font-bold text-gray-900 mt-1 cursor-help" title="Valor exacto: {{ $deudaExacta }}">{{ $deudaFormatted }}</div>
            <div class="text-xs text-gray-400 mt-1">Suma de cuantías filtradas</div>
        </div>
        {{-- KPI 3: En esta página --}}
        <div class="bg-white shadow-sm rounded-lg p-4 border-l-4 border-amber-500">
            <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">En esta página</div>
            <div class="text-3xl font-bold text-gray-900 mt-1">{{ $procesos->count() }} <span class="text-base font-normal text-gray-500">procesos</span></div>
            <div class="text-xs text-gray-400 mt-1">De {{ number_format($procesos->total()) }} totales</div>
        </div>
    </div>
    {{-- ════════ FIN B5.3 ════════ --}}
    {{-- FILTROS --}}
    <div class="bg-white shadow-sm rounded-lg p-4 mb-4">
        <div class="grid grid-cols-1 md:grid-cols-5 gap-3">
            <div>
                <input type="text" wire:model.live.debounce.300ms="search" placeholder="Buscar radicado, CC, nombre..."
                    class="w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
            </div>
            <div>
                <select wire:model.live="filterEstado" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                    <option value="">Todos los estados</option>
                    @foreach($estados as $key => $label)
                        <option value="{{ $key }}">{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <select wire:model.live="filterCliente" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                    <option value="">Todas las entidades</option>
                    @foreach($clientes as $c)
                        <option value="{{ $c->id }}">{{ $c->nombre }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <select wire:model.live="filterPrioridad" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                    <option value="">Toda prioridad</option>
                    @foreach($prioridades as $key => $label)
                        <option value="{{ $key }}">{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <div class="flex gap-2 mr-2">
                    <button wire:click="exportarExcel" class="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">📥 Exportar CSV</button>
                    <button wire:click="exportarBloqueados" class="px-3 py-2 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100">🔒 Bloqueados</button>
                </div>
                @can('procesos.create')
                <button wire:click="create"
                    class="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 text-sm font-medium">
                    + Nuevo Proceso
                </button>
                @endcan
            </div>
        </div>
    </div>

    {{-- TABLA --}}
    <div class="bg-white shadow-sm rounded-lg overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">SLA</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Radicado</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Entidad</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Deudor</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cuantía</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Etapa Procesal</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Fecha Demanda</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Estado</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Días</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Asignado</th>
                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase">Acciones</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                @forelse($procesos as $p)
                <tr class="hover:bg-gray-50">
                    <td class="px-3 py-2 text-center text-lg">{{ $p->semaforo_icon }}</td>
                    <td class="px-3 py-2">
                        <a href="{{ route('procesos.show', $p) }}" class="text-indigo-600 hover:text-indigo-800 font-mono text-sm font-semibold">
                            {{ $p->radicado_interno }}
                        </a>
                        @if($p->radicado_juzgado)
                        <div class="text-xs text-gray-400">{{ $p->radicado_juzgado }}</div>
                        @endif
                    </td>
                    <td class="px-3 py-2 text-sm">{{ $p->cliente->nombre ?? '—' }}</td>
                    <td class="px-3 py-2">
                        <div class="text-sm font-medium">{{ $p->deudor->nombre_completo ?? '—' }}</div>
                        <div class="text-xs text-gray-400">{{ $p->deudor->documento_completo ?? '' }}</div>
                    </td>
                    <td class="px-3 py-2 text-sm font-mono">${{ number_format($p->cuantia_total, 0, ',', '.') }}</td>
                    {{-- B4: Etapa Procesal con badge de color (mapeo P2) --}}
                    <td class="px-3 py-2">
                        @php
                            $eBD = $p->etapa_procesal ?? 'na';
                            $eMap = [
                                'na'                 => ['lbl' => 'Sin etapa',         'cls' => 'bg-gray-100 text-gray-600'],
                                'calificacion'       => ['lbl' => 'Calificación',      'cls' => 'bg-blue-100 text-blue-700'],
                                'mandamiento'        => ['lbl' => 'Mandamiento',       'cls' => 'bg-indigo-100 text-indigo-700'],
                                'notificacion'       => ['lbl' => 'Notificación',      'cls' => 'bg-cyan-100 text-cyan-700'],
                                'audiencia'          => ['lbl' => 'Audiencia',         'cls' => 'bg-purple-100 text-purple-700'],
                                'medidas_cautelares' => ['lbl' => 'Medidas Cautelar.', 'cls' => 'bg-orange-100 text-orange-700'],
                                'sentencia'          => ['lbl' => 'Sentencia',         'cls' => 'bg-emerald-100 text-emerald-700'],
                                'liquidacion'        => ['lbl' => 'Liquidación',       'cls' => 'bg-green-100 text-green-700'],
                            ];
                            $e = $eMap[$eBD] ?? ['lbl' => ucfirst($eBD), 'cls' => 'bg-gray-100 text-gray-600'];
                        @endphp
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium {{ $e['cls'] }}">
                            {{ $e['lbl'] }}
                        </span>
                    </td>
                    {{-- B4: Fecha Demanda (mapeada a fecha_ingreso) --}}
                    <td class="px-3 py-2 text-xs text-gray-600 font-mono">
                        {{ $p->fecha_ingreso ? $p->fecha_ingreso->format('d/m/Y') : '—' }}
                    </td>
                    <td class="px-3 py-2">
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium
                            {{ match($p->estado_color) {
                                'gray' => 'bg-gray-100 text-gray-800',
                                'blue' => 'bg-blue-100 text-blue-800',
                                'yellow' => 'bg-yellow-100 text-yellow-800',
                                'purple' => 'bg-purple-100 text-purple-800',
                                'indigo' => 'bg-indigo-100 text-indigo-800',
                                'cyan' => 'bg-cyan-100 text-cyan-800',
                                'orange' => 'bg-orange-100 text-orange-800',
                                'emerald' => 'bg-emerald-100 text-emerald-800',
                                'green' => 'bg-green-100 text-green-800',
                                default => 'bg-gray-100 text-gray-800',
                            } }}">
                            {{ $p->estado_label }}
                        </span>
                    </td>
                    <td class="px-3 py-2 text-sm text-center">{{ $p->dias_en_proceso }}d</td>
                    <td class="px-3 py-2 text-xs text-gray-500">
                        @foreach($p->asignacionesActivas as $a)
                            <div>{{ $a->usuario->name ?? '?' }} <span class="text-gray-400">({{ $a->rol_asignado }})</span></div>
                        @endforeach
                    </td>
                    <td class="px-3 py-2 text-sm space-x-1">
                        <a href="{{ route('procesos.show', $p) }}" class="text-blue-600 hover:text-blue-800" title="Ver">👁</a>
                        @can('procesos.edit')
                        <button wire:click="edit({{ $p->id }})" class="text-yellow-600 hover:text-yellow-800" title="Editar">✏️</button>
                        @endcan
                        @can('procesos.delete')
                        <button wire:click="confirmDelete({{ $p->id }})" class="text-red-600 hover:text-red-800" title="Eliminar">🗑</button>
                        @endcan
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="11" class="px-4 py-8 text-center text-gray-500">No hay procesos registrados.</td>
                </tr>
                @endforelse
            </tbody>
        </table>
        <div class="px-4 py-3">{{ $procesos->links() }}</div>
    </div>

    {{-- MODAL CREAR/EDITAR --}}
    @if($showModal)
    <div class="fixed inset-0 z-50 overflow-y-auto" aria-modal="true">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75" wire:click="$set('showModal', false)"></div>
            <div class="relative bg-white rounded-lg shadow-xl w-full max-w-2xl p-6">
                <h3 class="text-lg font-semibold mb-4">{{ $editingId ? 'Editar Proceso' : 'Nuevo Proceso' }}</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {{-- Cliente --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Entidad Corporativa *</label>
                        <select wire:model="cliente_corporativo_id" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                            <option value="">Seleccionar...</option>
                            @foreach($clientes as $c)
                                <option value="{{ $c->id }}">{{ $c->nombre }}</option>
                            @endforeach
                        </select>
                        @error('cliente_corporativo_id') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                    </div>

                    {{-- Deudor (búsqueda) --}}
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Deudor *</label>
                        <input type="text" wire:model.live.debounce.300ms="deudorSearch" placeholder="Buscar por CC o nombre..."
                            class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                        @if(count($deudorResults) > 0)
                        <div class="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-40 overflow-y-auto">
                            @foreach($deudorResults as $d)
                            <button type="button" wire:click="selectDeudor({{ $d['id'] }})"
                                class="w-full text-left px-3 py-2 text-sm hover:bg-indigo-50 border-b">
                                {{ $d['label'] }}
                            </button>
                            @endforeach
                        </div>
                        @endif
                        @error('deudor_id') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                    </div>

                    {{-- Nro Obligación --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">N° Obligación</label>
                        <input type="text" wire:model="numero_obligacion" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                    </div>

                    {{-- Cuantía --}}
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3 col-span-full">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Saldo Capital <span class="text-red-500">*</span></label>
                            <input type="number" wire:model.live="saldo_capital" step="0.01" min="0" placeholder="0.00" class="w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Intereses</label>
                            <input type="number" wire:model.live="saldo_intereses" step="0.01" min="0" placeholder="0.00" class="w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Total Deuda</label>
                            <input type="number" wire:model="saldo_total" readonly placeholder="0.00" class="w-full text-sm border-gray-300 rounded-md shadow-sm bg-indigo-50 font-semibold text-indigo-700">
                        </div>
                    </div>

                    {{-- Fecha ingreso --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Ingreso *</label>
                        <input type="date" wire:model="fecha_ingreso" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                        @error('fecha_ingreso') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                    </div>

                    {{-- Fecha vencimiento --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Vencimiento Términos</label>
                        <input type="date" wire:model="fecha_vencimiento_terminos" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                    </div>

                    {{-- Prioridad --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
                        <select wire:model="prioridad" class="w-full text-sm border-gray-300 rounded-md shadow-sm">
                            @foreach($prioridades as $key => $label)
                                <option value="{{ $key }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Checkboxes FO-SG-025 --}}
                    <div class="flex items-center gap-4 pt-6">
                        <label class="flex items-center gap-1 text-sm">
                            <input type="checkbox" wire:model="tiene_deceval" class="rounded border-gray-300 text-indigo-600"> Deceval
                        </label>
                        <label class="flex items-center gap-1 text-sm">
                            <input type="checkbox" wire:model="pagare_virtual" class="rounded border-gray-300 text-indigo-600"> Pagaré Virtual
                        </label>
                        <label class="flex items-center gap-1 text-sm">
                            <input type="checkbox" wire:model="con_escritura" class="rounded border-gray-300 text-indigo-600"> Escritura
                        </label>
                    </div>
                </div>

                {{-- Observaciones --}}
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Observaciones</label>
                    <textarea wire:model="observaciones" rows="2" class="w-full text-sm border-gray-300 rounded-md shadow-sm"></textarea>
                </div>

                <div class="flex justify-end gap-3 mt-6">
                    <button wire:click="$set('showModal', false)" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm">Cancelar</button>
                    <button wire:click="save" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 text-sm font-medium">
                        {{ $editingId ? 'Actualizar' : 'Crear Proceso' }}
                    </button>
                </div>
            </div>
        </div>
    </div>
    @endif

    {{-- MODAL ELIMINAR --}}
    @if($showDeleteModal)
    <div class="fixed inset-0 z-50 overflow-y-auto" aria-modal="true">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75"></div>
            <div class="relative bg-white rounded-lg shadow-xl p-6 max-w-md">
                <h3 class="text-lg font-semibold text-red-600 mb-2">¿Eliminar proceso?</h3>
                <p class="text-sm text-gray-600 mb-4">Esta acción es irreversible. El proceso y sus actuaciones serán eliminados.</p>
                <div class="flex justify-end gap-3">
                    <button wire:click="$set('showDeleteModal', false)" class="px-4 py-2 bg-gray-200 rounded-md text-sm">Cancelar</button>
                    <button wire:click="delete" class="px-4 py-2 bg-red-600 text-white rounded-md text-sm">Eliminar</button>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>
