<div>
    {{-- Mensajes --}}
    @if(session('mensaje_temporal'))
        <div class="bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-md mb-4">
            ✓ {{ session('mensaje_temporal') }}
        </div>
    @endif
    @if(session('error'))
        <div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-md mb-4">
            ⚠ {{ session('error') }}
        </div>
    @endif

    {{-- Encabezado --}}
    <div class="flex items-start justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">Nuevo caso prejurídico</h1>
            <p class="text-sm text-gray-500 mt-1">El radicado se genera automáticamente al guardar.</p>
        </div>
        <a href="{{ route('casos-prejuridicos.index') }}" wire:navigate class="text-sm text-gray-500 hover:text-gray-700">
            ← Volver al listado
        </a>
    </div>

    <form wire:submit.prevent="guardar" class="space-y-6">

        {{-- ═══════════ SECCIÓN 1: DEUDOR ═══════════ --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">1. Deudor</h2>

            @if($deudorId)
                {{-- Deudor seleccionado --}}
                <div class="bg-green-50 border border-green-200 rounded-md p-3 flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <span class="text-green-600 text-lg">✓</span>
                        <div>
                            <div class="text-sm font-semibold text-gray-800">{{ $busquedaDeudor }}</div>
                            <div class="text-xs text-gray-500">Deudor seleccionado</div>
                        </div>
                    </div>
                    <button type="button" wire:click="limpiarDeudor"
                        class="text-sm text-red-600 hover:text-red-800 font-medium">
                        Cambiar
                    </button>
                </div>
            @else
                <div class="space-y-3">
                    <div class="relative">
                        <label class="block text-sm font-semibold text-gray-700 mb-1">
                            Buscar deudor existente <span class="text-red-500">*</span>
                        </label>
                        <input type="text"
                            wire:model.live.debounce.300ms="busquedaDeudor"
                            placeholder="Escribe cédula o nombre (mínimo 2 caracteres)..."
                            class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('deudorId') border-red-500 @enderror">

                        {{-- Dropdown de resultados --}}
                        @if(count($deudoresFiltrados) > 0)
                            <div class="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-md shadow-lg max-h-60 overflow-auto">
                                @foreach($deudoresFiltrados as $d)
                                    <button type="button"
                                        wire:click="seleccionarDeudor({{ $d->id }})"
                                        class="w-full text-left px-3 py-2 hover:bg-blue-50 border-b last:border-b-0">
                                        <div class="text-sm font-semibold text-gray-800">{{ $d->nombre_completo }}</div>
                                        <div class="text-xs text-gray-500">{{ $d->tipo_documento }} {{ $d->numero_documento }} · {{ $d->ciudad ?? 'Sin ciudad' }}</div>
                                    </button>
                                @endforeach
                            </div>
                        @elseif(strlen($busquedaDeudor) >= 2)
                            <div class="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-md shadow-lg p-3">
                                <p class="text-sm text-gray-500">Sin resultados. Puedes crear un deudor nuevo abajo.</p>
                            </div>
                        @endif

                        @error('deudorId')
                            <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="text-center">
                        <span class="text-xs text-gray-400">— o —</span>
                    </div>

                    <div class="text-center">
                        <button type="button" wire:click="abrirCrearDeudor"
                            class="inline-flex items-center gap-2 px-4 py-2 border border-blue-600 text-blue-600 hover:bg-blue-50 text-sm font-semibold rounded-md transition">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                            </svg>
                            Crear deudor nuevo
                        </button>
                    </div>
                </div>
            @endif
        </div>

        {{-- ═══════════ SECCIÓN 2: DATOS DEL CASO ═══════════ --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">2. Datos del caso</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                {{-- Entidad cliente --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Entidad cliente <span class="text-red-500">*</span>
                    </label>
                    <select wire:model="clienteCorporativoId"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('clienteCorporativoId') border-red-500 @enderror">
                        <option value="">Seleccione...</option>
                        @foreach($entidades as $e)
                            <option value="{{ $e->id }}">{{ $e->nombre }}</option>
                        @endforeach
                    </select>
                    @error('clienteCorporativoId')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Producto --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Producto <span class="text-red-500">*</span>
                    </label>
                    <select wire:model="producto"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('producto') border-red-500 @enderror">
                        <option value="">Seleccione...</option>
                        @foreach($productos as $value => $label)
                            <option value="{{ $value }}">{{ $label }}</option>
                        @endforeach
                    </select>
                    @error('producto')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Asesor responsable --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Asesor responsable <span class="text-red-500">*</span>
                    </label>
                    <select wire:model="responsableId"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('responsableId') border-red-500 @enderror">
                        <option value="">Seleccione...</option>
                        @foreach($usuarios as $u)
                            <option value="{{ $u->id }}">{{ $u->name }}</option>
                        @endforeach
                    </select>
                    @error('responsableId')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Fecha de recepción --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Fecha de recepción <span class="text-red-500">*</span>
                    </label>
                    <input type="date" wire:model="fechaRecepcion"
                        max="{{ now()->toDateString() }}"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('fechaRecepcion') border-red-500 @enderror">
                    @error('fechaRecepcion')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Etapa inicial --}}
                <div class="md:col-span-2">
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Etapa inicial <span class="text-red-500">*</span>
                    </label>
                    <select wire:model="etapa"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('etapa') border-red-500 @enderror">
                        @foreach($etapas as $value => $label)
                            <option value="{{ $value }}">{{ $label }}</option>
                        @endforeach
                    </select>
                    <p class="text-xs text-gray-500 mt-1">La mayoría de casos arrancan en "Recepción".</p>
                    @error('etapa')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>
        </div>

        {{-- ═══════════ SECCIÓN 3: DATOS FINANCIEROS ═══════════ --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">3. Datos financieros</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                {{-- Saldo capital --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">
                        Saldo capital <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">$</span>
                        <input type="number" step="0.01" min="0" wire:model="saldoCapital"
                            placeholder="0"
                            class="w-full pl-7 border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('saldoCapital') border-red-500 @enderror">
                    </div>
                    @error('saldoCapital')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Intereses --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Intereses</label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">$</span>
                        <input type="number" step="0.01" min="0" wire:model="intereses"
                            placeholder="0"
                            class="w-full pl-7 border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('intereses') border-red-500 @enderror">
                    </div>
                    @error('intereses')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Días en mora --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Días en mora</label>
                    <input type="number" min="0" wire:model="diasMora"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('diasMora') border-red-500 @enderror">
                    @error('diasMora')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div></div>

                {{-- Nro. Obligación --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Nro. Obligación</label>
                    <input type="text" wire:model="numeroObligacion" maxlength="100"
                        placeholder="Opcional"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('numeroObligacion') border-red-500 @enderror">
                    @error('numeroObligacion')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Nro. Pagaré --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Nro. Pagaré</label>
                    <input type="text" wire:model="numeroPagare" maxlength="100"
                        placeholder="Opcional"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('numeroPagare') border-red-500 @enderror">
                    @error('numeroPagare')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>
        </div>

        {{-- ═══════════ SECCIÓN 4: OBSERVACIONES ═══════════ --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">4. Observaciones</h2>
            <textarea wire:model="observaciones" rows="3" maxlength="2000"
                placeholder="Notas iniciales del caso (opcional)..."
                class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('observaciones') border-red-500 @enderror"></textarea>
            <div class="flex justify-between items-center mt-1">
                @error('observaciones')
                    <p class="text-xs text-red-600">{{ $message }}</p>
                @else
                    <p class="text-xs text-gray-500">Opcional. Máx. 2000 caracteres.</p>
                @enderror
                <p class="text-xs text-gray-400">{{ strlen($observaciones) }}/2000</p>
            </div>
        </div>

        {{-- Botones de acción --}}
        <div class="flex justify-end gap-3">
            <a href="{{ route('casos-prejuridicos.index') }}" wire:navigate
                class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 text-sm font-semibold rounded-md transition">
                Cancelar
            </a>
            <button type="submit"
                wire:loading.attr="disabled"
                wire:target="guardar"
                class="px-5 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white text-sm font-semibold rounded-md transition">
                <span wire:loading.remove wire:target="guardar">Guardar caso</span>
                <span wire:loading wire:target="guardar">Guardando...</span>
            </button>
        </div>
    </form>

    {{-- ═══════════ MODAL: CREAR DEUDOR NUEVO ═══════════ --}}
    @if($showCrearDeudorModal)
        <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4 overflow-y-auto" wire:key="modal-crear-deudor">
            <div class="bg-white rounded-lg shadow-xl max-w-lg w-full p-6 my-8">
                <h3 class="text-xl font-bold text-gray-800 mb-4">+ Crear deudor nuevo</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1">Tipo doc <span class="text-red-500">*</span></label>
                        <select wire:model="nuevoTipoDocumento"
                            class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="CC">CC - Cédula</option>
                            <option value="NIT">NIT</option>
                            <option value="CE">CE - Cédula extranjería</option>
                            <option value="PP">PP - Pasaporte</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1">Nro. documento <span class="text-red-500">*</span></label>
                        <input type="text" wire:model="nuevoNumeroDocumento" maxlength="30"
                            class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('nuevoNumeroDocumento') border-red-500 @enderror">
                        @error('nuevoNumeroDocumento')
                            <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Nombre completo <span class="text-red-500">*</span></label>
                    <input type="text" wire:model="nuevoNombreCompleto" maxlength="255"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('nuevoNombreCompleto') border-red-500 @enderror">
                    @error('nuevoNombreCompleto')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1">Teléfono</label>
                        <input type="text" wire:model="nuevoTelefono" maxlength="30"
                            class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1">Ciudad</label>
                        <input type="text" wire:model="nuevaCiudad" maxlength="100"
                            class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-semibold text-gray-700 mb-1">Email</label>
                    <input type="email" wire:model="nuevoEmail" maxlength="255"
                        class="w-full border-gray-300 rounded-md text-sm focus:ring-blue-500 focus:border-blue-500 @error('nuevoEmail') border-red-500 @enderror">
                    @error('nuevoEmail')
                        <p class="text-xs text-red-600 mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="flex justify-end gap-2">
                    <button type="button" wire:click="cerrarCrearDeudor"
                        class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 text-sm font-semibold rounded-md transition">
                        Cancelar
                    </button>
                    <button type="button" wire:click="crearDeudor"
                        wire:loading.attr="disabled"
                        wire:target="crearDeudor"
                        class="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white text-sm font-semibold rounded-md transition">
                        <span wire:loading.remove wire:target="crearDeudor">Crear deudor</span>
                        <span wire:loading wire:target="crearDeudor">Creando...</span>
                    </button>
                </div>
            </div>
        </div>
    @endif
</div>
