@php($diskUrl = fn (string $path) => \Illuminate\Support\Facades\Storage::url($path))
<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <h2 class="text-xl font-bold text-slate-900 leading-tight">
                    {{ $patient->name }}
                </h2>
                @if ($patient->clinical_code)
                    <p class="mt-1 font-mono text-sm font-semibold text-teal-700">{{ __('Expediente paciente') }}: {{ $patient->clinical_code }}</p>
                @endif
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <a href="{{ route('clients.show', $client) }}" class="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-teal-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
                    {{ __('Volver al titular') }}
                </a>
                @can('clients.manage')
                    <a href="{{ route('clients.patients.edit', [$client, $patient]) }}"
                       class="inline-flex items-center gap-1.5 rounded-xl bg-teal-600 px-3 py-2 text-sm font-bold text-white shadow-md hover:bg-teal-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                        {{ __('Editar ficha') }}
                    </a>
                @endcan
            </div>
        </div>
    </x-slot>

    <div class="py-8">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6" x-data="filePreviewModal()" @keydown.escape.window="closePreview()">
            {{-- Representante --}}
            <div class="poskn-card overflow-hidden p-6">
                <h3 class="text-xs font-bold uppercase tracking-widest text-violet-700 mb-3">{{ __('Representante / titular') }}</h3>
                <div class="flex flex-col gap-4 sm:flex-row sm:items-start">
                    <div class="shrink-0">
                        @if ($client->photo_path)
                            <img src="{{ \Illuminate\Support\Facades\Storage::url($client->photo_path) }}" alt="" class="h-20 w-20 rounded-xl object-cover border border-slate-200" />
                        @else
                            <div class="h-20 w-20 rounded-xl bg-violet-100 flex items-center justify-center text-2xl font-bold text-violet-500">
                                {{ mb_strtoupper(mb_substr($client->name, 0, 1)) }}
                            </div>
                        @endif
                    </div>
                    <div class="flex-1 text-sm text-slate-700 space-y-1">
                        <p><span class="font-semibold text-slate-900">{{ __('Nombre') }}:</span>
                            <a href="{{ route('clients.show', $client) }}" class="text-violet-700 hover:underline">{{ $client->name }}</a>
                        </p>
                        @if ($client->registration_code)
                            <p><span class="font-semibold text-slate-900">{{ __('Código titular') }}:</span>
                                <span class="font-mono text-teal-800">{{ $client->registration_code }}</span></p>
                        @endif
                        @if ($client->phone)
                            <p><span class="font-semibold text-slate-900">{{ __('Teléfono') }}:</span> {{ $client->phone }}</p>
                        @endif
                        @if ($client->email)
                            <p><span class="font-semibold text-slate-900">{{ __('Correo') }}:</span> {{ $client->email }}</p>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Datos del paciente --}}
            <div class="poskn-card overflow-hidden">
                <div class="border-b border-teal-100 bg-gradient-to-r from-teal-50 to-cyan-50 px-6 py-3">
                    <h3 class="text-sm font-bold uppercase tracking-wide text-teal-800">{{ __('Datos del paciente') }}</h3>
                </div>
                <div class="p-6 md:flex md:gap-8">
                    <div class="shrink-0 mb-4 md:mb-0">
                        @if ($patient->photo_path)
                            <img src="{{ \Illuminate\Support\Facades\Storage::url($patient->photo_path) }}" alt="" class="h-36 w-36 rounded-2xl object-cover border border-slate-200 shadow-sm" />
                        @else
                            <div class="h-36 w-36 rounded-2xl bg-gradient-to-br from-teal-100 to-cyan-100 flex items-center justify-center text-5xl font-bold text-teal-600">
                                {{ mb_strtoupper(mb_substr($patient->name, 0, 1)) }}
                            </div>
                        @endif
                    </div>
                    <div class="flex-1 grid gap-2 text-sm text-slate-700 sm:grid-cols-2">
                        @if ($patient->species || $patient->breed)
                            <p class="sm:col-span-2"><span class="font-semibold text-slate-900">{{ __('Especie / raza') }}:</span>
                                {{ collect([$patient->species, $patient->breed])->filter()->join(' · ') }}</p>
                        @endif
                        @if ($patient->sex)
                            <p><span class="font-semibold text-slate-900">{{ __('Sexo') }}:</span>
                                {{ match ($patient->sex) {
                                    'M' => __('Macho'),
                                    'F' => __('Hembra'),
                                    default => __('Desconocido'),
                                } }}</p>
                        @endif
                        @if ($patient->birth_date)
                            <p><span class="font-semibold text-slate-900">{{ __('Nacimiento') }}:</span>
                                {{ $patient->birth_date->translatedFormat('d M Y') }}</p>
                        @endif
                        @if ($patient->current_weight_kg)
                            <p><span class="font-semibold text-slate-900">{{ __('Peso actual') }}:</span> {{ $patient->current_weight_kg }} kg</p>
                        @endif
                        @if ($patient->color)
                            <p><span class="font-semibold text-slate-900">{{ __('Color') }}:</span> {{ $patient->color }}</p>
                        @endif
                        @if ($patient->microchip)
                            <p class="sm:col-span-2"><span class="font-semibold text-slate-900">{{ __('Microchip') }}:</span> {{ $patient->microchip }}</p>
                        @endif
                        <p><span class="font-semibold text-slate-900">{{ __('Estado') }}:</span>
                            {{ $patient->is_active ? __('Activo') : __('Inactivo') }}</p>
                        @if (! is_null($patient->sterilized))
                            <p><span class="font-semibold text-slate-900">{{ __('Esterilización') }}:</span>
                                {{ $patient->sterilized ? __('Sí') : __('No') }}</p>
                        @endif
                        @if ($patient->allergies)
                            <p class="sm:col-span-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-amber-950">
                                <span class="font-semibold">{{ __('Alergias') }}:</span> {{ $patient->allergies }}
                            </p>
                        @endif
                        @if ($patient->notes)
                            <p class="sm:col-span-2 pt-2 border-t border-slate-200">
                                <span class="font-semibold text-slate-900">{{ __('Notas') }}:</span><br>
                                {{ $patient->notes }}
                            </p>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Multimedia del expediente --}}
            @can('clients.view')
                <div class="poskn-card p-6">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-4">
                        <h3 class="text-lg font-semibold text-slate-900">{{ __('Multimedia del expediente') }}</h3>
                        <p class="text-xs text-slate-500">{{ __('Estudios, radiografías, documentos generales del paciente') }}</p>
                    </div>
                    @can('medical_records.edit')
                        <form method="post" action="{{ route('clients.patients.media.store', [$client, $patient]) }}" enctype="multipart/form-data" class="mb-6 rounded-xl border border-dashed border-teal-300 bg-teal-50/40 p-4 space-y-3">
                            @csrf
                            <div>
                                <x-input-label for="pm_title" :value="__('Título (opcional, aplica a todos los archivos)')" />
                                <x-text-input id="pm_title" class="block mt-1 w-full" type="text" name="title" />
                            </div>
                            <div>
                                <x-input-label for="pm_files" :value="__('Archivos (imagen, PDF o video)')" />
                                <input id="pm_files" name="files[]" type="file" multiple required
                                       accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.mp4,.webm,.mov,image/*,application/pdf,video/*"
                                       class="mt-1 block w-full text-sm text-slate-600 file:mr-4 file:rounded-lg file:border-0 file:bg-teal-600 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-white" />
                                <x-input-error :messages="$errors->get('files')" class="mt-2" />
                                <x-input-error :messages="$errors->get('files.*')" class="mt-2" />
                            </div>
                            <x-primary-button type="submit">{{ __('Subir archivos') }}</x-primary-button>
                        </form>
                    @endcan
                    @if ($patient->mediaFiles->isEmpty())
                        <p class="text-sm text-slate-500">{{ __('No hay archivos en el expediente todavía.') }}</p>
                    @else
                        <ul class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                            @foreach ($patient->mediaFiles as $file)
                                @php($u = $diskUrl($file->path))
                                <li class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50/80 shadow-sm dark:border-slate-600 dark:bg-slate-900/40">
                                    <div class="relative h-32 w-full overflow-hidden bg-slate-200 dark:bg-slate-700">
                                        @if ($file->isImage())
                                            <img src="{{ $u }}" alt="" class="h-full w-full object-cover" loading="lazy" />
                                        @elseif ($file->isPdf())
                                            <div class="flex h-full flex-col items-center justify-center gap-1 text-red-600">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12" fill="currentColor" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6zm-1 2l5 5h-5V4z"/></svg>
                                                <span class="text-xs font-bold">PDF</span>
                                            </div>
                                        @elseif ($file->isVideo())
                                            <div class="flex h-full items-center justify-center text-violet-600">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-14 w-14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                            </div>
                                        @else
                                            <div class="flex h-full items-center justify-center text-slate-500">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="p-3">
                                        <p class="truncate text-xs font-medium text-slate-800 dark:text-slate-200" title="{{ $file->original_name }}">{{ $file->title ?: $file->original_name }}</p>
                                        <p class="text-xs text-slate-500">{{ $file->created_at->translatedFormat('d M Y H:i') }}</p>
                                        <div class="mt-3 flex flex-wrap gap-2">
                                            <button type="button"
                                                    class="inline-flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-teal-600 px-3 py-2 text-xs font-semibold text-white hover:bg-teal-700 sm:flex-initial"
                                                    @click="openPreview({{ \Illuminate\Support\Js::from(['url' => str_replace('\\', '/', $u), 'title' => $file->original_name, 'mime' => $file->mime]) }})">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                                                {{ __('Ver') }}
                                            </button>
                                            <a href="{{ $u }}" download="{{ $file->original_name }}"
                                               class="inline-flex flex-1 items-center justify-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200 sm:flex-initial">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                                                {{ __('Descargar') }}
                                            </a>
                                            @can('medical_records.edit')
                                                <form method="post" action="{{ route('clients.patients.media.destroy', [$client, $patient, $file]) }}" class="inline"
                                                      onsubmit="return confirm(@js(__('¿Eliminar este archivo?')));">
                                                    @csrf
                                                    @method('delete')
                                                    <button type="submit" class="inline-flex items-center gap-1 rounded-lg px-2 py-2 text-xs font-semibold text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30" title="{{ __('Eliminar') }}">
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                                    </button>
                                                </form>
                                            @endcan
                                        </div>
                                    </div>
                                </li>
                            @endforeach
                        </ul>
                    @endif
                </div>
            @endcan

            {{-- Historia clínica --}}
            <div class="poskn-card p-6">
                <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-4">
                    <h3 class="text-lg font-semibold text-slate-900">{{ __('Historia clínica') }}</h3>
                    <div class="flex flex-wrap items-center gap-2">
                        @can('medical_records.view')
                            <a href="{{ route('clients.patients.medical-records.index', [$client, $patient]) }}"
                               class="inline-flex items-center gap-1.5 rounded-lg border border-teal-200 bg-teal-50 px-3 py-2 text-sm font-semibold text-teal-800 hover:bg-teal-100">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
                                {{ __('Ver historial completo') }}
                            </a>
                        @endcan
                        @can('medical_records.edit')
                            <a href="{{ route('clients.patients.medical-records.create', [$client, $patient]) }}"
                               class="inline-flex items-center gap-2 rounded-xl bg-violet-600 px-4 py-2.5 text-sm font-bold !text-white shadow-lg shadow-violet-600/30 ring-2 ring-violet-800/20 hover:bg-violet-700 hover:!text-white focus:outline-none focus:ring-2 focus:ring-violet-500 focus:ring-offset-2">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 shrink-0 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
                                <span class="text-white">{{ __('Nueva consulta') }}</span>
                            </a>
                        @endcan
                    </div>
                </div>
                @can('medical_records.view')
                    @if ($patient->medicalRecords->isEmpty())
                        <p class="text-sm text-slate-500">{{ __('Sin consultas registradas.') }}</p>
                    @else
                        <ul class="divide-y divide-slate-200 text-sm">
                            @foreach ($patient->medicalRecords as $record)
                                <li class="py-3 flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                                    <div class="min-w-0 flex-1">
                                        <p class="font-semibold text-slate-900">{{ $record->title ?: __('Consulta') }}</p>
                                        <p class="text-slate-500">
                                            {{ $record->recorded_at->translatedFormat('d M Y H:i') }}
                                            @if ($record->author)
                                                · {{ $record->author->name }}
                                            @endif
                                            @if (($record->attachments_count ?? 0) > 0)
                                                · {{ $record->attachments_count }} {{ $record->attachments_count === 1 ? __('adjunto') : __('adjuntos') }}
                                            @endif
                                        </p>
                                    </div>
                                    <div class="flex shrink-0 flex-wrap items-center gap-2">
                                        <a href="{{ route('clients.patients.medical-records.show', [$client, $patient, $record]) }}"
                                           class="inline-flex items-center gap-1 rounded-lg bg-teal-600 px-3 py-1.5 text-xs font-semibold text-white shadow-sm hover:bg-teal-700">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                                            {{ __('Ver') }}
                                        </a>
                                        <a href="{{ route('clients.patients.medical-records.print', [$client, $patient, $record]) }}"
                                           target="_blank" rel="noopener"
                                           class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 shadow-sm hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
                                            {{ __('Imprimir') }}
                                        </a>
                                    </div>
                                </li>
                            @endforeach
                        </ul>
                        @if ($patient->medical_records_count > $patient->medicalRecords->count())
                            <p class="mt-3 text-sm text-slate-500">
                                <a href="{{ route('clients.patients.medical-records.index', [$client, $patient]) }}" class="text-teal-700 hover:underline">
                                    {{ __('Ver las :total entradas', ['total' => $patient->medical_records_count]) }}
                                </a>
                            </p>
                        @endif
                    @endif
                @else
                    <p class="text-sm text-slate-500">{{ __('No tiene permiso para ver el historial clínico.') }}</p>
                @endcan
            </div>

            @can('reservations.view')
                <div class="poskn-card p-6">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-4">
                        <h3 class="text-lg font-semibold text-slate-900">{{ __('Reservas de farmacia (caja)') }}</h3>
                        <div class="flex flex-wrap gap-2">
                            <a href="{{ route('clients.patients.product-reservations.index', [$client, $patient]) }}"
                               class="text-sm text-teal-700 hover:underline">{{ __('Ver reservas') }}</a>
                            @can('reservations.manage')
                                <a href="{{ route('clients.patients.product-reservations.create', [$client, $patient]) }}"
                                   class="inline-flex items-center rounded-xl bg-violet-600 px-3 py-2 text-sm font-medium text-white hover:bg-violet-500">
                                    {{ __('Nueva reserva para caja') }}
                                </a>
                            @endcan
                            @can('appointments.manage')
                                <a href="{{ route('clinica.appointments.create', ['patient_id' => $patient->id]) }}"
                                   class="inline-flex items-center rounded-xl bg-slate-700 px-3 py-2 text-sm font-medium text-white hover:bg-slate-600">
                                    {{ __('Nueva cita') }}
                                </a>
                            @endcan
                        </div>
                    </div>
                    <p class="text-sm text-slate-500">
                        {{ __('El médico indica productos de farmacia clínica; en el POS se cargan y cobran cuando el cliente paga.') }}
                    </p>
                </div>
            @endcan

            @can('clients.manage')
                <form method="post" action="{{ route('clients.patients.destroy', [$client, $patient]) }}" class="text-right"
                      onsubmit="return confirm(@js(__('¿Eliminar este paciente?')));">
                    @csrf
                    @method('delete')
                    <button type="submit" class="text-sm text-red-600 hover:underline">
                        {{ __('Eliminar paciente') }}
                    </button>
                </form>
            @endcan

            @include('partials.file-preview-modal')
        </div>
    </div>
</x-app-layout>
