<div>
    <x-slot name="header">

        {{-- ── Header del usuario ───────────────────────────────────────────── --}}
        <div class="flex items-start justify-between gap-4 flex-wrap">

            {{-- Izquierda: avatar + datos --}}
            <div class="flex items-start gap-4">
                {{-- Avatar --}}
                <div class="w-14 h-14 rounded-full bg-primary flex items-center justify-center shrink-0 shadow">
                    <span class="text-xl font-bold text-primary-content">
                        {{ strtoupper(substr($user->first_name ?: $user->name, 0, 1)) }}{{ strtoupper(substr($user->last_name ?: '', 0, 1)) }}
                    </span>
                </div>

                {{-- Nombre + datos de contacto --}}
                <div>
                    <h2 class="font-bold text-xl leading-tight">
                        @if($user->title) <span class="text-gray-500 font-normal">{{ $user->title }}</span> @endif
                        {{ $user->first_name && $user->last_name
                            ? $user->first_name . ' ' . $user->last_name
                            : $user->name }}
                    </h2>

                    {{-- Empresa --}}
                    @if($user->company)
                        <div class="flex items-center gap-1.5 mt-0.5">
                            @if($user->company->logo_path && \Illuminate\Support\Facades\Storage::disk('public')->exists($user->company->logo_path))
                                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($user->company->logo_path) }}"
                                    class="w-4 h-4 object-contain rounded" alt="" />
                            @else
                                <x-heroicon-o-building-office class="w-3.5 h-3.5 text-gray-400" />
                            @endif
                            <span class="text-sm text-gray-600">{{ $user->company->apodo ?: $user->company->name }}</span>
                        </div>
                    @endif

                    {{-- Contacto inline --}}
                    <div class="flex flex-wrap items-center gap-x-4 gap-y-0.5 mt-1 text-sm text-gray-500">
                        @if($user->email)
                            <span class="flex items-center gap-1">
                                <x-heroicon-o-envelope class="w-3.5 h-3.5 opacity-60" />
                                {{ $user->email }}
                            </span>
                        @endif
                        @if($user->phone)
                            <span class="flex items-center gap-1">
                                <x-heroicon-o-phone class="w-3.5 h-3.5 opacity-60" />
                                {{ $user->phone }}
                            </span>
                        @endif
                        @if($user->address)
                            <span class="flex items-center gap-1 max-w-xs">
                                <x-heroicon-o-map-pin class="w-3.5 h-3.5 opacity-60 shrink-0" />
                                <span class="truncate">{{ $user->address }}</span>
                            </span>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Derecha: estado + validez + botones --}}
            <div class="flex flex-col items-end gap-2">
                <div class="flex items-center gap-2">
                    {{-- Estado --}}
                    @php
                        $statusBadge = match($user->status ?? 'active') {
                            'active'    => ['badge-success', 'Activo'],
                            'inactive'  => ['badge-ghost',   'Inactivo'],
                            'suspended' => ['badge-error',   'Suspendido'],
                            default     => ['badge-ghost',   ucfirst($user->status ?? '')],
                        };
                    @endphp
                    <span class="badge {{ $statusBadge[0] }} badge-md">{{ $statusBadge[1] }}</span>

                    {{-- Rol principal --}}
                    @foreach($user->roles->take(1) as $role)
                        <span class="badge {{ $role->name === 'Admin' ? 'badge-error' : 'badge-primary' }} badge-md">
                            {{ $role->name }}
                        </span>
                    @endforeach
                </div>

                {{-- Validez --}}
                @if($user->valid_from || $user->valid_until)
                    @php
                        $now   = now();
                        $from  = $user->valid_from;
                        $until = $user->valid_until;
                        $isExpired  = $until && $until->lt($now);
                        $expireSoon = !$isExpired && $until && $until->diffInDays($now) <= 30;
                        $notStarted = $from && $from->gt($now);
                        $validColor = $isExpired || $notStarted ? 'text-error' : ($expireSoon ? 'text-warning' : 'text-gray-400');
                    @endphp
                    <p class="text-xs {{ $validColor }} flex items-center gap-1">
                        <x-heroicon-o-calendar-days class="w-3.5 h-3.5" />
                        @if($from && $until)
                            {{ $from->format('d/m/Y') }} → {{ $until->format('d/m/Y') }}
                        @elseif($from)
                            Desde {{ $from->format('d/m/Y') }}
                        @else
                            Hasta {{ $until->format('d/m/Y') }}
                        @endif
                        @if($isExpired) <span class="font-semibold">(Expirado)</span>
                        @elseif($notStarted) <span class="font-semibold">(No activo aún)</span>
                        @elseif($expireSoon) <span class="font-semibold">(Expira pronto)</span>
                        @endif
                    </p>
                @endif

                {{-- Botones --}}
                <div class="flex gap-2 mt-1">
                    <a href="{{ route('admin.users.edit', $user) }}"
                    class="btn btn-outline btn-sm gap-1" wire:navigate>
                        <x-heroicon-o-pencil class="w-4 h-4" />
                        Editar
                    </a>
                    <a href="{{ route('admin.users') }}"
                    class="btn btn-ghost btn-sm gap-1" wire:navigate>
                        <x-heroicon-o-arrow-left class="w-4 h-4" />
                        Volver
                    </a>
                </div>
            </div>
        </div>

    </x-slot>

    {{-- ── Tabs ──────────────────────────────────────────────────────────────── --}}
    <div class="py-6">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-4">

            <div role="tablist" class="tabs tabs-bordered gap-4">
                <button role="tab" wire:click="setTab('ficha')"
                        class="tab gap-2 {{ $activeTab === 'ficha' ? 'tab-active font-semibold' : '' }}">
                    <x-heroicon-o-identification class="w-4 h-4" />
                    Ficha
                </button>
                <button role="tab" wire:click="setTab('permissions')"
                        class="tab gap-2 {{ $activeTab === 'permissions' ? 'tab-active font-semibold' : '' }}">
                    <x-heroicon-o-shield-check class="w-4 h-4" />
                    Permisos
                </button>
                <button role="tab" wire:click="setTab('projects')"
                        class="tab gap-2 {{ $activeTab === 'projects' ? 'tab-active font-semibold' : '' }}">
                    <x-heroicon-o-folder-open class="w-4 h-4" />
                    Proyectos
                    <span class="badge badge-sm badge-outline">{{ $user->projects->count() }}</span>
                </button>
                <button role="tab" wire:click="setTab('activity')"
                        class="tab gap-2 {{ $activeTab === 'activity' ? 'tab-active font-semibold' : '' }}">
                    <x-heroicon-o-clock class="w-4 h-4" />
                    Actividad
                </button>
                <button role="tab" wire:click="setTab('notes')"
                        class="tab gap-2 {{ $activeTab === 'notes' ? 'tab-active font-semibold' : '' }}">
                    <x-heroicon-o-document-text class="w-4 h-4" />
                    Notas
                    @if($user->notes)
                        <span class="badge badge-sm badge-primary">•</span>
                    @endif
                </button>
            </div>

            {{-- ════════════════════════════════════════════════════════════════════
                TAB: FICHA
            ════════════════════════════════════════════════════════════════════ --}}
            @if($activeTab === 'ficha')
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

                {{-- Información básica --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-4">
                            <x-heroicon-o-identification class="w-5 h-5 text-primary" />
                            Información básica
                        </h3>
                        <div class="space-y-1 text-sm">
                            <div class="flex justify-between gap-4 py-2 border-b border-base-200">
                                <span class="text-gray-500">Nombre</span>
                                <span class="font-medium text-right">{{ trim(($user->title ? $user->title.' ' : '').($user->first_name ?? '').' '.($user->last_name ?? '')) ?: $user->name }}</span>
                            </div>
                            <div class="flex justify-between gap-4 py-2 border-b border-base-200">
                                <span class="text-gray-500">Usuario</span>
                                <span class="font-medium text-right">{{ $user->name }}</span>
                            </div>
                            <div class="flex justify-between gap-4 py-2 border-b border-base-200">
                                <span class="text-gray-500">Email</span>
                                <span class="font-medium text-right">{{ $user->email }}</span>
                            </div>
                            <div class="flex justify-between gap-4 py-2 border-b border-base-200">
                                <span class="text-gray-500">Teléfono</span>
                                <span class="font-medium text-right">{{ $user->phone ?: '—' }}</span>
                            </div>
                            <div class="flex justify-between gap-4 py-2 border-b border-base-200">
                                <span class="text-gray-500">Dirección</span>
                                <span class="font-medium text-right">{{ $user->address ?: '—' }}</span>
                            </div>
                            <div class="flex justify-between gap-4 py-2">
                                <span class="text-gray-500">Miembro desde</span>
                                <span class="font-medium text-right">{{ $user->created_at?->format('d/m/Y') ?? '—' }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Validez y estado --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-4">
                            <x-heroicon-o-calendar-days class="w-5 h-5 text-primary" />
                            Validez de acceso
                        </h3>
                        <div class="space-y-3 text-sm">
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Estado</span>
                                <span class="badge {{ $statusBadge[0] }}">{{ $statusBadge[1] }}</span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Válido desde</span>
                                <span class="font-medium">
                                    {{ $user->valid_from ? $user->valid_from->format('d/m/Y') : '—  (sin límite)' }}
                                </span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Válido hasta</span>
                                <span class="font-medium {{ isset($isExpired) && $isExpired ? 'text-error font-bold' : '' }}">
                                    {{ $user->valid_until ? $user->valid_until->format('d/m/Y') : '—  (sin límite)' }}
                                </span>
                            </div>
                            <div class="flex justify-between items-center py-2">
                                <span class="text-gray-500">Email verificado</span>
                                @if($user->email_verified_at)
                                    <span class="flex items-center gap-1 text-success text-xs font-medium">
                                        <x-heroicon-o-check-circle class="w-4 h-4" />
                                        {{ $user->email_verified_at->format('d/m/Y') }}
                                    </span>
                                @else
                                    <span class="text-warning text-xs flex items-center gap-1">
                                        <x-heroicon-o-clock class="w-4 h-4" />
                                        Pendiente
                                    </span>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Empresa --}}
                @if($user->company)
                <div class="card bg-base-100 shadow md:col-span-2">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-3">
                            <x-heroicon-o-building-office-2 class="w-5 h-5 text-primary" />
                            Empresa
                        </h3>
                        <div class="flex items-center gap-4">
                            @if($user->company->logo_path && \Illuminate\Support\Facades\Storage::disk('public')->exists($user->company->logo_path))
                                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($user->company->logo_path) }}"
                                    class="w-14 h-14 object-contain border border-base-300 rounded-lg" alt="" />
                            @else
                                <div class="w-14 h-14 bg-base-200 rounded-lg flex items-center justify-center">
                                    <x-heroicon-o-building-office class="w-7 h-7 opacity-30" />
                                </div>
                            @endif
                            <div>
                                <p class="font-semibold">{{ $user->company->name }}</p>
                                @if($user->company->apodo)
                                    <p class="text-sm text-gray-500">{{ $user->company->apodo }}</p>
                                @endif
                                @if($user->company->email)
                                    <p class="text-xs text-gray-400">{{ $user->company->email }}</p>
                                @endif
                            </div>
                            @php
                                $typeBadge = match($user->company->type) {
                                    'owner'         => ['badge-success',  'Promotor'],
                                    'constructor'   => ['badge-primary',  'Constructor'],
                                    'subcontractor' => ['badge-secondary','Subcontratista'],
                                    'consultant'    => ['badge-info',     'Consultor'],
                                    'supplier'      => ['badge-warning',  'Proveedor'],
                                    default         => ['badge-ghost',    'Otro'],
                                };
                            @endphp
                            <span class="badge {{ $typeBadge[0] }} ml-auto">{{ $typeBadge[1] }}</span>
                        </div>
                    </div>
                </div>
                @endif

            </div>
            @endif

            {{-- ════════════════════════════════════════════════════════════════════
                TAB: PERMISOS
            ════════════════════════════════════════════════════════════════════ --}}
            @if($activeTab === 'permissions')
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

                {{-- Roles --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-4">
                            <x-heroicon-o-shield-check class="w-5 h-5 text-primary" />
                            Roles asignados
                        </h3>
                        @if($user->roles->isEmpty())
                            <p class="text-sm text-gray-400">Sin roles asignados.</p>
                        @else
                            <div class="space-y-2">
                                @foreach($user->roles as $role)
                                    <div class="flex items-center gap-3 p-3 bg-base-200 rounded-lg">
                                        <span class="badge {{ $role->name === 'Admin' ? 'badge-error' : 'badge-primary' }} badge-lg">
                                            {{ $role->name }}
                                        </span>
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>

                {{-- Validez y estado --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-4">
                            <x-heroicon-o-calendar-days class="w-5 h-5 text-primary" />
                            Validez de acceso
                        </h3>
                        <div class="space-y-3 text-sm">
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Estado</span>
                                <span class="badge {{ $statusBadge[0] }}">{{ $statusBadge[1] }}</span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Válido desde</span>
                                <span class="font-medium">
                                    {{ $user->valid_from ? $user->valid_from->format('d/m/Y') : '—  (sin límite)' }}
                                </span>
                            </div>
                            <div class="flex justify-between items-center py-2 border-b border-base-200">
                                <span class="text-gray-500">Válido hasta</span>
                                <span class="font-medium {{ isset($isExpired) && $isExpired ? 'text-error font-bold' : '' }}">
                                    {{ $user->valid_until ? $user->valid_until->format('d/m/Y') : '—  (sin límite)' }}
                                </span>
                            </div>
                            <div class="flex justify-between items-center py-2">
                                <span class="text-gray-500">Email verificado</span>
                                @if($user->email_verified_at)
                                    <span class="flex items-center gap-1 text-success text-xs font-medium">
                                        <x-heroicon-o-check-circle class="w-4 h-4" />
                                        {{ $user->email_verified_at->format('d/m/Y') }}
                                    </span>
                                @else
                                    <span class="text-warning text-xs flex items-center gap-1">
                                        <x-heroicon-o-clock class="w-4 h-4" />
                                        Pendiente
                                    </span>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Empresa --}}
                @if($user->company)
                <div class="card bg-base-100 shadow md:col-span-2">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-3">
                            <x-heroicon-o-building-office-2 class="w-5 h-5 text-primary" />
                            Empresa
                        </h3>
                        <div class="flex items-center gap-4">
                            @if($user->company->logo_path && \Illuminate\Support\Facades\Storage::disk('public')->exists($user->company->logo_path))
                                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($user->company->logo_path) }}"
                                    class="w-14 h-14 object-contain border border-base-300 rounded-lg" alt="" />
                            @else
                                <div class="w-14 h-14 bg-base-200 rounded-lg flex items-center justify-center">
                                    <x-heroicon-o-building-office class="w-7 h-7 opacity-30" />
                                </div>
                            @endif
                            <div>
                                <p class="font-semibold">{{ $user->company->name }}</p>
                                @if($user->company->apodo)
                                    <p class="text-sm text-gray-500">{{ $user->company->apodo }}</p>
                                @endif
                                @if($user->company->email)
                                    <p class="text-xs text-gray-400">{{ $user->company->email }}</p>
                                @endif
                            </div>
                            @php
                                $typeBadge = match($user->company->type) {
                                    'owner'         => ['badge-success',  'Promotor'],
                                    'constructor'   => ['badge-primary',  'Constructor'],
                                    'subcontractor' => ['badge-secondary','Subcontratista'],
                                    'consultant'    => ['badge-info',     'Consultor'],
                                    'supplier'      => ['badge-warning',  'Proveedor'],
                                    default         => ['badge-ghost',    'Otro'],
                                };
                            @endphp
                            <span class="badge {{ $typeBadge[0] }} ml-auto">{{ $typeBadge[1] }}</span>
                        </div>
                    </div>
                </div>
                @endif

                {{-- Permisos directos del usuario --}}
                <div class="card bg-base-100 shadow md:col-span-2">
                    <div class="card-body p-6">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-1">
                            <x-heroicon-o-key class="w-5 h-5 text-primary" />
                            Permisos
                        </h3>
                        <p class="text-xs text-gray-400 mb-4">
                            Los permisos heredados de un rol aparecen marcados y bloqueados. Aquí puedes conceder permisos extra directamente a este usuario.
                        </p>

                        <div class="space-y-3">
                            @forelse($grouped as $section => $perms)
                                <div x-data="{ open: true }" class="border border-base-200 rounded-lg overflow-hidden">
                                    <div class="flex items-center justify-between px-4 py-2.5 bg-base-200/60">
                                        <button type="button" @click="open = !open" class="flex items-center gap-2 flex-1 text-left">
                                            <span class="transition-transform duration-200" :class="open ? 'rotate-90' : ''">
                                                <x-heroicon-o-chevron-right class="w-4 h-4 text-gray-500" />
                                            </span>
                                            <span class="font-semibold text-gray-700">{{ $section }}</span>
                                            <span class="badge badge-ghost badge-sm">{{ $perms->count() }}</span>
                                        </button>
                                        <div class="flex items-center gap-1 shrink-0">
                                            <button wire:click="setUserGroup('{{ $section }}', true)" class="btn btn-xs btn-ghost gap-1" title="{{ __('Check all') }}">
                                                <x-heroicon-o-check class="w-3.5 h-3.5" /> {{ __('All') }}
                                            </button>
                                            <button wire:click="setUserGroup('{{ $section }}', false)" class="btn btn-xs btn-ghost gap-1" title="{{ __('Uncheck all') }}">
                                                <x-heroicon-o-x-mark class="w-3.5 h-3.5" /> {{ __('None') }}
                                            </button>
                                        </div>
                                    </div>
                                    <div x-show="open" x-transition.opacity class="divide-y divide-base-200">
                                        @foreach($perms as $perm)
                                            @php
                                                $viaRole = in_array($perm->name, $rolePerms, true);
                                                $direct  = in_array($perm->name, $directPerms, true);
                                            @endphp
                                            <label class="flex items-center justify-between gap-3 px-4 py-2.5 {{ $viaRole ? 'opacity-70' : 'cursor-pointer hover:bg-base-100' }}">
                                                <div class="min-w-0">
                                                    <span class="text-sm font-medium">{{ $perm->name }}</span>
                                                    @if($viaRole)<span class="badge badge-ghost badge-xs ml-1">{{ __('from role') }}</span>@endif
                                                    @if($perm->description)
                                                        <p class="text-xs text-gray-400 leading-tight">{{ $perm->description }}</p>
                                                    @endif
                                                </div>
                                                <input type="checkbox"
                                                       class="toggle toggle-primary toggle-sm shrink-0"
                                                       wire:key="uperm-{{ $user->id }}-{{ $perm->id }}"
                                                       @checked($viaRole || $direct)
                                                       @disabled($viaRole)
                                                       @if(! $viaRole) wire:click="togglePermission('{{ $perm->name }}')" @endif />
                                            </label>
                                        @endforeach
                                    </div>
                                </div>
                            @empty
                                <p class="text-sm text-gray-400">{{ __('No permissions') }}</p>
                            @endforelse
                        </div>
                    </div>
                </div>

            </div>
            @endif

            {{-- ════════════════════════════════════════════════════════════════════
                TAB: PROYECTOS
            ════════════════════════════════════════════════════════════════════ --}}
            @if($activeTab === 'projects')
            <div class="space-y-4">

                {{-- Formulario asignar --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-5">
                        <h3 class="font-semibold text-sm mb-3 flex items-center gap-2">
                            <x-heroicon-o-plus-circle class="w-4 h-4 text-primary" />
                            Asignar proyecto
                        </h3>
                        @if($availableProjects->isEmpty())
                            <p class="text-sm text-gray-400">El usuario ya está asignado a todos los proyectos disponibles.</p>
                        @else
                            <div class="flex flex-wrap items-end gap-3">
                                <div class="form-control flex-1 min-w-[200px]">
                                    <label class="label-text text-xs mb-1">Proyecto</label>
                                    <select wire:model="addProjectId" class="select select-bordered select-sm w-full">
                                        <option value="">— Seleccionar —</option>
                                        @foreach($availableProjects as $p)
                                            <option value="{{ $p->id }}">{{ $p->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('addProjectId') <p class="text-error text-xs mt-0.5">{{ $message }}</p> @enderror
                                </div>
                                <div class="form-control flex-1 min-w-[160px]">
                                    <label class="label-text text-xs mb-1">Rol en proyecto</label>
                                    <input type="text" wire:model="addProjectRole"
                                        class="input input-bordered input-sm w-full"
                                        placeholder="ej: Jefe de obra" />
                                </div>
                                <button wire:click="assignProject" class="btn btn-primary btn-sm gap-1 shrink-0">
                                    <x-heroicon-o-plus class="w-4 h-4" />
                                    Asignar
                                </button>
                            </div>
                        @endif
                    </div>
                </div>

                {{-- Lista proyectos --}}
                @if($user->projects->isEmpty())
                    <div class="card bg-base-100 shadow">
                        <div class="card-body items-center text-center py-10 text-gray-400">
                            <x-heroicon-o-folder-open class="w-10 h-10 opacity-25 mb-2" />
                            <p class="text-sm">Sin proyectos asignados.</p>
                        </div>
                    </div>
                @else
                    <div class="card bg-base-100 shadow overflow-x-auto">
                        <table class="table table-zebra w-full">
                            <thead>
                                <tr>
                                    <th>Proyecto</th>
                                    <th>Rol</th>
                                    <th>Estado</th>
                                    <th>Progreso</th>
                                    <th class="w-16"></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($user->projects as $project)
                                    @php
                                        $avg = $project->phases->avg('progress_percent') ?? 0;
                                        $sCfg = match($project->status) {
                                            'in_progress' => ['badge-primary',  'En progreso'],
                                            'completed'   => ['badge-success',  'Completado'],
                                            'paused'      => ['badge-warning',  'Pausado'],
                                            'planning'    => ['badge-ghost',    'Planificación'],
                                            default       => ['badge-ghost',    ucfirst($project->status)],
                                        };
                                    @endphp
                                    <tr wire:key="proj-{{ $project->id }}">
                                        <td>
                                            <a href="{{ route('projects.dashboard', $project) }}"
                                            class="font-medium hover:text-primary transition-colors" wire:navigate>
                                                {{ $project->name }}
                                            </a>
                                            @if($project->address)
                                                <p class="text-xs text-gray-400 truncate max-w-[200px]">{{ $project->address }}</p>
                                            @endif
                                        </td>
                                        <td class="text-sm text-gray-600">
                                            {{ $project->pivot->role_in_project ?? '—' }}
                                        </td>
                                        <td>
                                            <span class="badge badge-sm {{ $sCfg[0] }}">{{ $sCfg[1] }}</span>
                                        </td>
                                        <td>
                                            <div class="flex items-center gap-2">
                                                <progress class="progress progress-primary w-20 h-1.5"
                                                        value="{{ round($avg) }}" max="100"></progress>
                                                <span class="text-xs text-gray-500">{{ round($avg) }}%</span>
                                            </div>
                                        </td>
                                        <td>
                                            <button wire:click="removeProject({{ $project->id }})"
                                                    wire:confirm="¿Desasignar a {{ $user->name }} del proyecto '{{ $project->name }}'?"
                                                    class="btn btn-xs btn-outline btn-error" title="Desasignar">
                                                <x-heroicon-o-x-mark class="w-3.5 h-3.5" />
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif

            </div>
            @endif

            {{-- ════════════════════════════════════════════════════════════════════
                TAB: ACTIVIDAD
            ════════════════════════════════════════════════════════════════════ --}}
            @if($activeTab === 'activity')
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

                {{-- Inspecciones --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-5">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-3">
                            <x-heroicon-o-clipboard-document-list class="w-5 h-5 text-yellow-500" />
                            Últimas inspecciones
                        </h3>
                        @if($recentInspections->isEmpty())
                            <div class="text-center py-8 text-gray-400">
                                <x-heroicon-o-clipboard-document-list class="w-8 h-8 mx-auto opacity-25 mb-1" />
                                <p class="text-sm">Sin inspecciones registradas</p>
                            </div>
                        @else
                            <div class="space-y-2">
                                @foreach($recentInspections as $ins)
                                    @php
                                        $rCfg = match($ins->result ?? '') {
                                            'pass' => ['badge-success', 'OK'],
                                            'fail' => ['badge-error',   'Fallo'],
                                            default => ['badge-ghost',  '—'],
                                        };
                                    @endphp
                                    <div class="p-2.5 rounded-lg bg-base-200 text-sm">
                                        <div class="flex items-start justify-between gap-2">
                                            <span class="font-medium truncate flex-1">
                                                {{ $ins->template?->name ?? 'Inspección' }}
                                            </span>
                                            <span class="badge badge-xs {{ $rCfg[0] }} shrink-0">{{ $rCfg[1] }}</span>
                                        </div>
                                        <div class="flex items-center justify-between mt-0.5 text-xs text-gray-400">
                                            <span class="truncate">
                                                @if($ins->feature?->layer?->phase?->project)
                                                    <x-heroicon-o-folder-open class="w-3 h-3 inline" />
                                                    {{ $ins->feature->layer->phase->project->name }}
                                                @endif
                                            </span>
                                            <span class="shrink-0 ml-1">{{ $ins->created_at->diffForHumans() }}</span>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>

                {{-- Issues reportados --}}
                <div class="card bg-base-100 shadow">
                    <div class="card-body p-5">
                        <h3 class="font-semibold text-base flex items-center gap-2 mb-3">
                            <x-heroicon-o-exclamation-triangle class="w-5 h-5 text-orange-500" />
                            Issues reportados
                        </h3>
                        @if($recentIssues->isEmpty())
                            <div class="text-center py-8 text-gray-400">
                                <x-heroicon-o-check-circle class="w-8 h-8 mx-auto opacity-25 mb-1" />
                                <p class="text-sm">Sin issues reportados</p>
                            </div>
                        @else
                            <div class="space-y-2">
                                @foreach($recentIssues as $issue)
                                    @php
                                        $pCfg = match($issue->priority ?? 'medium') {
                                            'critical' => ['badge-error',   'Crítico'],
                                            'high'     => ['badge-warning', 'Alto'],
                                            'medium'   => ['badge-info',    'Medio'],
                                            default    => ['badge-ghost',   'Bajo'],
                                        };
                                        $stCfg = match($issue->status ?? 'open') {
                                            'open'    => 'text-orange-500',
                                            'closed'  => 'text-green-500',
                                            default   => 'text-gray-400',
                                        };
                                    @endphp
                                    <div class="p-2.5 rounded-lg bg-base-200 text-sm">
                                        <div class="flex items-start justify-between gap-2">
                                            <span class="font-medium truncate flex-1">{{ $issue->title }}</span>
                                            <span class="badge badge-xs {{ $pCfg[0] }} shrink-0">{{ $pCfg[1] }}</span>
                                        </div>
                                        <div class="flex items-center justify-between mt-0.5 text-xs text-gray-400">
                                            <span class="truncate">
                                                @if($issue->project)
                                                    <x-heroicon-o-folder-open class="w-3 h-3 inline" />
                                                    {{ $issue->project->name }}
                                                @endif
                                            </span>
                                            <span class="{{ $stCfg }} shrink-0 ml-1 font-medium">
                                                {{ ucfirst($issue->status ?? 'open') }}
                                            </span>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>

            </div>
            @endif

            {{-- ════════════════════════════════════════════════════════════════════
                TAB: NOTAS
            ════════════════════════════════════════════════════════════════════ --}}
            @if($activeTab === 'notes')
            <div class="card bg-base-100 shadow max-w-7xl">
                <div class="card-body p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="font-semibold text-base flex items-center gap-2">
                            <x-heroicon-o-document-text class="w-5 h-5 text-primary" />
                            Notas internas
                        </h3>
                        @if(!$editingNotes)
                            <button wire:click="$set('editingNotes', true)"
                                    class="btn btn-sm btn-outline gap-1">
                                <x-heroicon-o-pencil class="w-3.5 h-3.5" />
                                Editar
                            </button>
                        @endif
                    </div>

                    @if($editingNotes)
                        <textarea wire:model="notes" rows="10"
                                class="textarea textarea-bordered w-full text-sm"
                                placeholder="Añade notas, observaciones o información relevante sobre este usuario…"
                                autofocus></textarea>
                        <div class="flex justify-end gap-2 mt-3">
                            <button wire:click="$set('editingNotes', false)"
                                    class="btn btn-outline btn-sm">Cancelar</button>
                            <button wire:click="saveNotes"
                                    class="btn btn-primary btn-sm gap-1">
                                <x-heroicon-o-check class="w-4 h-4" />
                                Guardar
                            </button>
                        </div>
                    @else
                        @if($user->notes)
                            <div class="prose prose-sm max-w-none text-gray-700 whitespace-pre-line bg-base-200 rounded-lg p-4 min-h-[120px]">
                                {{ $user->notes }}
                            </div>
                        @else
                            <div class="text-center py-12 text-gray-400">
                                <x-heroicon-o-document-text class="w-10 h-10 mx-auto opacity-25 mb-2" />
                                <p class="text-sm">Sin notas.</p>
                                <button wire:click="$set('editingNotes', true)"
                                        class="btn btn-sm btn-outline mt-3 gap-1">
                                    <x-heroicon-o-plus class="w-4 h-4" />
                                    Añadir nota
                                </button>
                            </div>
                        @endif
                    @endif
                </div>
            </div>
            @endif

        </div>
    </div>
</div>
