<x-layouts.tenant pageTitle="Nueva evolución — {{ $patient->fullName() }}">
    <x-page-header :title="'Nueva evolución: '.$patient->fullName()"
                   subtitle="Registro de consulta / atención clínica">
        <x-btn :href="route('tenant.patients.show', $patient)" variant="secondary">Cancelar</x-btn>
    </x-page-header>

    <form method="POST" action="{{ route('tenant.evolutions.store', $patient) }}" class="space-y-6">
        @csrf

        {{-- Alerta si hay antecedentes importantes --}}
        @php $h = $patient->clinicalHistory; @endphp
        @if($h && ($h->allergies || $h->contraindications))
            <div class="bg-red-50 border border-red-200 rounded-xl p-4">
                <p class="text-sm font-bold text-red-800 mb-1">⚠ Alertas del paciente</p>
                @if($h->allergies)<p class="text-xs text-red-700"><strong>Alergias:</strong> {{ $h->allergies }}</p>@endif
                @if($h->contraindications)<p class="text-xs text-red-700 mt-1"><strong>Contraindicaciones:</strong> {{ $h->contraindications }}</p>@endif
            </div>
        @endif

        <x-card title="Datos de la consulta">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Profesional</span>
                    <select name="employee_id" class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <option value="">Sin asignar</option>
                        @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" @selected(old('employee_id') == $emp->id)>{{ $emp->user?->name ?? 'Empleado '.$emp->id }}</option>
                        @endforeach
                    </select>
                </label>
            </div>

            <div class="mt-4">
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Motivo de consulta <span class="text-red-500">*</span></span>
                    <textarea name="consultation_reason" rows="3" required
                              class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500 @error('consultation_reason') border-red-400 @enderror"
                              placeholder="¿Por qué consulta el paciente hoy?">{{ old('consultation_reason') }}</textarea>
                    @error('consultation_reason')<p class="text-xs text-red-500 mt-1">{{ $message }}</p>@enderror
                </label>
            </div>

            <div class="mt-4">
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Enfermedad actual / Anamnesis</span>
                    <textarea name="current_illness" rows="4"
                              class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500"
                              placeholder="Descripción detallada del estado actual del paciente…">{{ old('current_illness') }}</textarea>
                </label>
            </div>
        </x-card>

        {{-- Signos Vitales --}}
        <x-card title="Signos vitales">
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                @foreach([
                    'weight'         => 'Peso (kg)',
                    'height'         => 'Talla (cm)',
                    'bmi'            => 'IMC',
                    'temperature'    => 'Temperatura (°C)',
                    'systolic_bp'    => 'P.A. Sistólica',
                    'diastolic_bp'   => 'P.A. Diastólica',
                    'heart_rate'     => 'Frec. cardíaca (lpm)',
                    'respiratory_rate'=> 'Frec. respiratoria',
                    'oxygen_sat'     => 'Sat. O₂ (%)',
                ] as $key => $label)
                    <label class="block">
                        <span class="text-xs font-medium text-gray-600">{{ $label }}</span>
                        <input type="text" name="vital_signs[{{ $key }}]"
                               value="{{ old('vital_signs.'.$key) }}"
                               class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </label>
                @endforeach
            </div>
            <label class="block mt-4">
                <span class="text-xs font-medium text-gray-600">Observaciones de signos vitales</span>
                <input type="text" name="vital_signs[observations]" value="{{ old('vital_signs.observations') }}"
                       class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
            </label>
        </x-card>

        {{-- Examen físico --}}
        <x-card title="Examen físico">
            <textarea name="physical_exam" rows="5"
                      class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500"
                      placeholder="Hallazgos del examen físico…">{{ old('physical_exam') }}</textarea>
        </x-card>

        {{-- Diagnósticos --}}
        <x-card title="Diagnósticos">
            <div x-data="{ diagnoses: [{ name: '', cie10_code: '', type: 'primary' }] }">
                <template x-for="(diag, i) in diagnoses" :key="i">
                    <div class="flex gap-3 items-start mb-3 p-3 bg-gray-50 rounded-lg">
                        <div class="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                            <div class="md:col-span-2">
                                <input type="text" :name="'diagnoses['+i+'][name]'" x-model="diag.name"
                                       placeholder="Nombre del diagnóstico *"
                                       class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                            <input type="text" :name="'diagnoses['+i+'][cie10_code]'" x-model="diag.cie10_code"
                                   placeholder="Código CIE-10"
                                   class="rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <select :name="'diagnoses['+i+'][type]'" x-model="diag.type"
                                    class="rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <option value="primary">Principal</option>
                                <option value="secondary">Secundario</option>
                                <option value="impression">Impresión diagnóstica</option>
                            </select>
                        </div>
                        <button type="button" @click="diagnoses.splice(i, 1)"
                                class="mt-1 text-red-400 hover:text-red-600 text-lg font-bold">×</button>
                    </div>
                </template>
                <button type="button" @click="diagnoses.push({ name: '', cie10_code: '', type: 'primary' })"
                        class="text-xs text-indigo-600 hover:underline mt-1">+ Agregar diagnóstico</button>
            </div>
        </x-card>

        {{-- Valoración y plan --}}
        <x-card title="Valoración clínica y plan de tratamiento">
            <div class="space-y-4">
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Notas de diagnóstico</span>
                    <textarea name="diagnosis_notes" rows="3"
                              class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">{{ old('diagnosis_notes') }}</textarea>
                </label>
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Plan de tratamiento</span>
                    <textarea name="treatment_plan" rows="4"
                              class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">{{ old('treatment_plan') }}</textarea>
                </label>
                <label class="block">
                    <span class="text-sm font-medium text-gray-700">Recomendaciones</span>
                    <textarea name="recommendations" rows="3"
                              class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">{{ old('recommendations') }}</textarea>
                </label>
                <label class="block md:w-1/3">
                    <span class="text-sm font-medium text-gray-700">Fecha próximo control</span>
                    <input type="date" name="next_control_date" value="{{ old('next_control_date') }}"
                           class="mt-1 w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                </label>
            </div>
        </x-card>

        <div class="flex justify-end gap-3">
            <x-btn :href="route('tenant.patients.show', $patient)" variant="secondary">Cancelar</x-btn>
            <x-btn type="submit" variant="primary">Guardar evolución</x-btn>
        </div>
    </form>
</x-layouts.tenant>
