<div>
    {{-- ═══ STATS RÁPIDOS ═══ --}}
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <p class="text-xs font-medium text-gray-500 uppercase">Total registros</p>
            <p class="mt-1 text-xl font-bold text-gray-900">{{ number_format($stats['total']) }}</p>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <p class="text-xs font-medium text-gray-500 uppercase">Hoy</p>
            <p class="mt-1 text-xl font-bold text-blue-600">{{ $stats['hoy'] }}</p>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <p class="text-xs font-medium text-gray-500 uppercase">Última semana</p>
            <p class="mt-1 text-xl font-bold text-indigo-600">{{ $stats['semana'] }}</p>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <p class="text-xs font-medium text-gray-500 uppercase">Usuarios activos</p>
            <p class="mt-1 text-xl font-bold text-emerald-600">{{ $stats['usuarios_activos'] }}</p>
        </div>
    </div>

    {{-- ═══ FILTROS ═══ --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6">
        <div class="flex flex-wrap items-end gap-3">
            <div class="flex-1 min-w-[200px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Buscar</label>
                <input wire:model.live.debounce.300ms="search" type="text" placeholder="Descripción, usuario..."
                    class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
            </div>
            <div class="min-w-[130px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Evento</label>
                <select wire:model.live="filterEvent" class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                    <option value="">Todos</option>
                    @foreach($events as $ev)
                        <option value="{{ $ev }}">{{ ucfirst($ev) }}</option>
                    @endforeach
                </select>
            </div>
            <div class="min-w-[150px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Usuario</label>
                <select wire:model.live="filterUser" class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                    <option value="">Todos</option>
                    @foreach($users as $u)
                        <option value="{{ $u->id }}">{{ $u->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="min-w-[140px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Módulo</label>
                <select wire:model.live="filterModule" class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
                    <option value="">Todos</option>
                    @foreach($modules as $m)
                        <option value="{{ $m['value'] }}">{{ $m['label'] }}</option>
                    @endforeach
                </select>
            </div>
            <div class="min-w-[130px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Desde</label>
                <input wire:model.live="filterDateFrom" type="date" class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
            </div>
            <div class="min-w-[130px]">
                <label class="block text-xs font-medium text-gray-500 uppercase mb-1">Hasta</label>
                <input wire:model.live="filterDateTo" type="date" class="w-full rounded-lg border-gray-300 text-sm focus:border-indigo-500 focus:ring-indigo-500">
            </div>
            <div class="flex gap-2">
                <button wire:click="limpiarFiltros" class="px-3 py-2 text-sm text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition" title="Limpiar">
                    <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                </button>
                <button wire:click="exportarCsv" class="px-3 py-2 text-sm text-white bg-emerald-600 rounded-lg hover:bg-emerald-700 transition" title="Exportar CSV">
                    <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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                </button>
                <button wire:click="$set('viewMode', '{{ $viewMode === 'table' ? 'timeline' : 'table' }}')"
                    class="px-3 py-2 text-sm text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
                    title="{{ $viewMode === 'table' ? 'Ver timeline' : 'Ver tabla' }}">
                    @if($viewMode === 'table')
                        <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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    @else
                        <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="M3 10h18M3 14h18m-9-4v8m-7 0h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                    @endif
                </button>
            </div>
        </div>
    </div>

    {{-- ═══ VISTA TABLA ═══ --}}
    @if($viewMode === 'table')
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Fecha</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Usuario</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Evento</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Módulo</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Descripción</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Detalle</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    @forelse($activities as $a)
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-xs text-gray-900">{{ $a->created_at->format('d/m/Y') }}</div>
                            <div class="text-xs text-gray-400">{{ $a->created_at->format('H:i:s') }}</div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="flex items-center gap-2">
                                <div class="w-6 h-6 bg-indigo-100 rounded-full flex items-center justify-center">
                                    <span class="text-xs font-semibold text-indigo-700">{{ strtoupper(substr($a->causer?->name ?? 'S', 0, 1)) }}</span>
                                </div>
                                <span class="text-sm text-gray-700">{{ $a->causer?->name ?? 'Sistema' }}</span>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            @php
                                $eventColors = [
                                    'created' => 'bg-green-100 text-green-800',
                                    'updated' => 'bg-blue-100 text-blue-800',
                                    'deleted' => 'bg-red-100 text-red-800',
                                ];
                                $eventIcons = [
                                    'created' => '✚',
                                    'updated' => '✎',
                                    'deleted' => '✕',
                                ];
                            @endphp
                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium {{ $eventColors[$a->event] ?? 'bg-gray-100 text-gray-700' }}">
                                {{ $eventIcons[$a->event] ?? '•' }} {{ ucfirst($a->event ?? 'acción') }}
                            </span>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-xs text-gray-600">
                            @php
                                $moduleMap = [
                                    'App\\Models\\Proceso' => ['📄', 'Proceso'],
                                    'App\\Models\\Deudor' => ['👤', 'Deudor'],
                                    'App\\Models\\ClienteCorporativo' => ['🏢', 'Cliente'],
                                    'App\\Models\\User' => ['👥', 'Usuario'],
                                    'App\\Models\\Actuacion' => ['⚡', 'Actuación'],
                                    'App\\Models\\Asignacion' => ['🔗', 'Asignación'],
                                    'App\\Models\\Alerta' => ['🔔', 'Alerta'],
                                ];
                                $mod = $moduleMap[$a->subject_type] ?? ['📌', class_basename($a->subject_type ?? 'General')];
                            @endphp
                            <span>{{ $mod[0] }} {{ $mod[1] }}</span>
                            @if($a->subject_id)
                                <span class="text-gray-400">#{{ $a->subject_id }}</span>
                            @endif
                        </td>
                        <td class="px-4 py-3 text-sm text-gray-700 max-w-xs truncate" title="{{ $a->description }}">
                            {{ \Illuminate\Support\Str::limit($a->description, 60) }}
                        </td>
                        <td class="px-4 py-3 text-center">
                            @if($a->properties && ($a->properties->has('old') || $a->properties->has('attributes')))
                            <button wire:click="verDetalle({{ $a->id }})" class="text-indigo-600 hover:text-indigo-800 transition" title="Ver cambios">
                                <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                            </button>
                            @else
                                <span class="text-gray-300">—</span>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-4 py-12 text-center text-sm text-gray-400">
                            No se encontraron registros de auditoría.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <div class="px-4 py-3 border-t border-gray-200">{{ $activities->links() }}</div>
    </div>
    @endif

    {{-- ═══ VISTA TIMELINE ═══ --}}
    @if($viewMode === 'timeline')
    <div class="space-y-1">
        @php $lastDate = null; @endphp
        @forelse($activities as $a)
            @php $currentDate = $a->created_at->format('d/m/Y'); @endphp
            @if($currentDate !== $lastDate)
                <div class="py-2 px-4">
                    <span class="text-xs font-bold text-gray-400 uppercase tracking-wider">{{ $a->created_at->translatedFormat('l, d M Y') }}</span>
                </div>
                @php $lastDate = $currentDate; @endphp
            @endif
            <div class="flex gap-4 px-4">
                {{-- Línea temporal --}}
                <div class="flex flex-col items-center">
                    <div class="w-3 h-3 rounded-full {{ $a->event === 'created' ? 'bg-green-500' : ($a->event === 'deleted' ? 'bg-red-500' : 'bg-blue-500') }}"></div>
                    @if(!$loop->last)
                    <div class="w-0.5 flex-1 bg-gray-200"></div>
                    @endif
                </div>
                {{-- Contenido --}}
                <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-3 mb-2 flex-1 hover:shadow-md transition-shadow">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2">
                            <span class="text-xs text-gray-400">{{ $a->created_at->format('H:i') }}</span>
                            <span class="text-sm font-medium text-gray-800">{{ $a->causer?->name ?? 'Sistema' }}</span>
                            <span class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium {{ $a->event === 'created' ? 'bg-green-100 text-green-700' : ($a->event === 'deleted' ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700') }}">
                                {{ ucfirst($a->event ?? 'acción') }}
                            </span>
                        </div>
                        @if($a->properties && ($a->properties->has('old') || $a->properties->has('attributes')))
                        <button wire:click="verDetalle({{ $a->id }})" class="text-xs text-indigo-600 hover:underline">ver cambios</button>
                        @endif
                    </div>
                    <p class="mt-1 text-sm text-gray-600">{{ $a->description }}</p>
                </div>
            </div>
        @empty
            <div class="text-center py-12 text-gray-400">No se encontraron registros.</div>
        @endforelse
    </div>
    <div class="mt-4">{{ $activities->links() }}</div>
    @endif

    {{-- ═══ MODAL DETALLE DIFF ═══ --}}
    @if($showDetail && !empty($detailData))
    <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/75" wire:click="cerrarDetalle"></div>
            <div class="relative z-[60] bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[85vh] overflow-y-auto">
                {{-- Header --}}
                <div class="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between rounded-t-xl">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">Detalle de Auditoría</h3>
                        <p class="text-xs text-gray-500">{{ $detailData['fecha'] }} — {{ $detailData['usuario'] }}</p>
                    </div>
                    <button wire:click="cerrarDetalle" class="text-gray-400 hover:text-gray-600">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>

                <div class="px-6 py-4 space-y-5">
                    {{-- Info general --}}
                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div>
                            <span class="text-gray-500">Evento:</span>
                            <span class="ml-1 font-medium">{{ ucfirst($detailData['evento'] ?? '') }}</span>
                        </div>
                        <div>
                            <span class="text-gray-500">Módulo:</span>
                            <span class="ml-1 font-medium">{{ $detailData['modulo'] }} #{{ $detailData['subject_id'] }}</span>
                        </div>
                    </div>

                    <div class="text-sm">
                        <span class="text-gray-500">Descripción:</span>
                        <p class="mt-1 text-gray-800">{{ $detailData['descripcion'] }}</p>
                    </div>

                    {{-- Diff antes/después --}}
                    @if(!empty($detailData['diff']))
                    <div>
                        <h4 class="text-sm font-semibold text-gray-800 mb-2">Cambios realizados</h4>
                        <div class="border border-gray-200 rounded-lg overflow-hidden">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Campo</th>
                                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Antes</th>
                                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Después</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-100">
                                    @foreach($detailData['diff'] as $d)
                                    <tr>
                                        <td class="px-4 py-2 text-xs font-mono text-gray-700 font-medium">{{ $d['campo'] }}</td>
                                        <td class="px-4 py-2 text-xs text-red-700 bg-red-50">{{ $d['antes'] }}</td>
                                        <td class="px-4 py-2 text-xs text-green-700 bg-green-50">{{ $d['despues'] }}</td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                    @else
                    <p class="text-sm text-gray-400 italic">No hay diff disponible para este registro.</p>
                    @endif
                </div>

                <div class="border-t border-gray-200 px-6 py-3 flex justify-end">
                    <button wire:click="cerrarDetalle" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg text-sm hover:bg-gray-300 transition">Cerrar</button>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>
