<x-app-layout>
    <x-slot name="header">
        Panel de Control
    </x-slot>

    <div class="space-y-6">

        {{-- ===================================================================
        SECCIÓN 1: BIENVENIDA + HORA
        =================================================================== --}}
        <div class="bg-gradient-to-r from-green-700 to-green-900 rounded-xl p-4 sm:p-6 text-white shadow-lg">
            <div class="flex items-center justify-between flex-wrap gap-4">
                <div>
                    <h2 class="text-xl sm:text-2xl font-bold">Bienvenido, {{ Auth::user()->name }} {{ Auth::user()->apellido }}
                    </h2>
                    <p class="text-green-200 mt-1 text-sm">
                        {{ Auth::user()->cargo ?? 'Usuario' }}
                        @if(Auth::user()->gerencia)
                            &mdash; {{ optional(Auth::user()->gerencia)->nombre }}
                        @endif
                    </p>
                </div>
                <div class="text-left sm:text-right text-sm text-green-200">
                    <p class="font-semibold text-white text-lg" x-data
                        x-text="new Date().toLocaleTimeString('es-VE', {hour: '2-digit', minute:'2-digit'})"
                        x-init="setInterval(() => $el.textContent = new Date().toLocaleTimeString('es-VE', {hour:'2-digit',minute:'2-digit'}), 30000)">
                    </p>
                    <p>{{ now()->translatedFormat('l, d \d\e F \d\e Y') }}</p>
                </div>
            </div>
        </div>

        {{-- ===================================================================
        ALERTA: SOLICITUDES PENDIENTES DE CONFORMAR
        =================================================================== --}}
        @if($accionesRequeridas->count() > 0)
            <div class="bg-amber-50 border border-amber-300 rounded-xl p-4 flex items-start gap-3">
                <div class="flex-shrink-0 mt-0.5">
                    <svg class="w-5 h-5 text-amber-500" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd"
                            d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                            clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="flex-1">
                    <h3 class="font-semibold text-amber-800">Tienes {{ $accionesRequeridas->count() }} solicitud(es)
                        esperando tu conformación</h3>
                    <div class="mt-2 space-y-1">
                        @foreach($accionesRequeridas as $sol)
                            <div class="flex items-center justify-between text-sm">
                                <span class="text-amber-700">#{{ $sol->numero }} &mdash;
                                    {{ Str::limit($sol->descripcion, 50) }}</span>
                                <a href="{{ route('conformaciones.show', $sol->id) }}"
                                    class="ml-4 inline-flex items-center px-3 py-1 bg-amber-500 hover:bg-amber-600 text-white text-xs font-semibold rounded-full transition">
                                    Revisar →
                                </a>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        @endif

        {{-- ===================================================================
        SECCIÓN 2: KPI CARDS — MIS SOLICITUDES
        =================================================================== --}}
        {{-- ===================================================================
        SECCIÓN 2: KPI CARDS
        =================================================================== --}}
        <div x-data="{ activeTab: 'personales' }">
            @if($misSolicitudesTecnicas)
                <div class="flex items-center gap-4 mb-4 border-b border-gray-200">
                    <button @click="activeTab = 'personales'"
                        :class="activeTab === 'personales' ? 'border-green-600 text-green-700' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                        class="whitespace-nowrap py-2 px-1 border-b-2 font-semibold text-sm transition-colors">
                        Mis Solicitudes Personales
                    </button>
                    <button @click="activeTab = 'tecnicas'"
                        :class="activeTab === 'tecnicas' ? 'border-green-600 text-green-700' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                        class="whitespace-nowrap py-2 px-1 border-b-2 font-semibold text-sm transition-colors">
                        {{ auth()->user()->isAdmin() ? 'Gestión Global' : 'Gestión Técnica / Área' }}
                    </button>
                </div>
            @else
                <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-widest mb-3">Mis Solicitudes Personales
                </h3>
            @endif

            <!-- Tab Personales -->
            <div x-show="activeTab === 'personales'">
                @php
                    $kpisPersonales = [
                        ['label' => 'Total', 'value' => $misSolicitudesPersonales['total'], 'color' => 'bg-slate-100 text-slate-700', 'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2'],
                        ['label' => 'Ingresadas', 'value' => $misSolicitudesPersonales['ingresadas'], 'color' => 'bg-blue-50 text-blue-700', 'icon' => 'M12 4v16m8-8H4'],
                        ['label' => 'Asignadas', 'value' => $misSolicitudesPersonales['asignadas'], 'color' => 'bg-indigo-50 text-indigo-700', 'icon' => 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'],
                        ['label' => 'En Espera', 'value' => $misSolicitudesPersonales['en_espera'], 'color' => 'bg-orange-50 text-orange-700', 'icon' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
                        ['label' => 'Por Conformar', 'value' => $misSolicitudesPersonales['conformar'], 'color' => 'bg-yellow-50 text-yellow-700', 'icon' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
                        ['label' => 'Conformadas', 'value' => $misSolicitudesPersonales['conformadas'], 'color' => 'bg-amber-50 text-amber-700', 'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'],
                        ['label' => 'Cerradas', 'value' => $misSolicitudesPersonales['cerradas'], 'color' => 'bg-green-50 text-green-700', 'icon' => 'M5 13l4 4L19 7'],
                    ];
                @endphp
                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-7 gap-2 sm:gap-3">
                    @foreach($kpisPersonales as $kpi)
                        <div class="rounded-xl p-2 shadow-sm border border-gray-100 {{ $kpi['color'] }}">
                            <div class="flex items-center justify-between">
                                <div class="min-w-0">
                                    <p class="text-[9px] sm:text-[10px] font-bold uppercase tracking-wider text-slate-900 truncate"
                                        title="{{ $kpi['label'] }}">{{ $kpi['label'] }}</p>
                                    <p class="text-xl sm:text-2xl font-bold leading-none mt-1">{{ $kpi['value'] }}</p>
                                </div>
                                <svg class="w-5 h-5 opacity-30 shrink-0 ml-1" fill="none" stroke="currentColor"
                                    stroke-width="2" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="{{ $kpi['icon'] }}" />
                                </svg>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>

            <!-- Tab Técnicas -->
            @if($misSolicitudesTecnicas)
                <div x-show="activeTab === 'tecnicas'" x-cloak>
                    @php
                        $kpisTecnicas = [
                            ['label' => auth()->user()->isAdmin() ? 'Total Global' : 'Total (Depto)', 'value' => $misSolicitudesTecnicas['total'], 'color' => 'bg-slate-100 text-slate-700', 'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2'],
                            ['label' => auth()->user()->isAdmin() ? 'Ingresadas' : 'Ingresadas (Depto)', 'value' => $misSolicitudesTecnicas['ingresadas'], 'color' => 'bg-blue-50 text-blue-700', 'icon' => 'M12 4v16m8-8H4'],
                            ['label' => auth()->user()->isAdmin() ? 'Asignadas' : 'Asignadas a mí', 'value' => $misSolicitudesTecnicas['asignadas'], 'color' => 'bg-indigo-50 text-indigo-700', 'icon' => 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'],
                            ['label' => 'En Espera', 'value' => $misSolicitudesTecnicas['en_espera'], 'color' => 'bg-orange-50 text-orange-700', 'icon' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
                            ['label' => auth()->user()->isAdmin() ? 'Ejec. / Conformar' : 'Por Conformar (Mis)', 'value' => $misSolicitudesTecnicas['conformar'], 'color' => 'bg-yellow-50 text-yellow-700', 'icon' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
                            ['label' => auth()->user()->isAdmin() ? 'Conformadas' : 'Conformadas (Mías)', 'value' => $misSolicitudesTecnicas['conformadas'], 'color' => 'bg-amber-50 text-amber-700', 'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'],
                            ['label' => auth()->user()->isAdmin() ? 'Cerradas' : 'Cerradas (Mías)', 'value' => $misSolicitudesTecnicas['cerradas'], 'color' => 'bg-green-50 text-green-700', 'icon' => 'M5 13l4 4L19 7'],
                        ];
                    @endphp
                    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-7 gap-2 sm:gap-3 mt-3">
                        @foreach($kpisTecnicas as $kpi)
                            <div class="rounded-xl p-2 shadow-sm border border-gray-100 {{ $kpi['color'] }}">
                                <div class="flex items-center justify-between">
                                    <div class="min-w-0">
                                        <p class="text-[9px] sm:text-[10px] font-bold uppercase tracking-wider text-slate-900 truncate"
                                            title="{{ $kpi['label'] }}">{{ $kpi['label'] }}</p>
                                        <p class="text-xl sm:text-2xl font-bold leading-none mt-1">{{ $kpi['value'] }}</p>
                                    </div>
                                    <svg class="w-5 h-5 opacity-30 shrink-0 ml-1" fill="none" stroke="currentColor"
                                        stroke-width="2" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="{{ $kpi['icon'] }}" />
                                    </svg>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif
        </div>

        {{-- ===================================================================
        SECCIÓN 3: TAREAS DEL ANALISTA + ACCIONES RÁPIDAS
        =================================================================== --}}
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            {{-- Tareas del Analista / Técnico --}}
            @if((auth()->user()->canManageTickets() || auth()->user()->canBeAssignedTickets()) && auth()->user()->canOperateInCurrentModule())
                <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                    <h3 class="font-semibold text-gray-700 mb-4 flex items-center gap-2">
                        <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" stroke-width="2"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                        </svg>
                        {{ $isTecnico ? 'Mi Bandeja' : 'Bandeja del Analista' }}
                    </h3>

                    <div class="space-y-3">
                        {{-- Pendientes: técnico ve su depto, roles superiores ven todas --}}
                        <a href="{{ route('asignaciones.index') }}"
                            class="flex items-center justify-between p-3 rounded-lg bg-blue-50 hover:bg-blue-100 transition group">
                            <div>
                                <p class="text-sm font-medium text-blue-800">Pendientes por Recibir</p>
                                <p class="text-xs text-blue-500 mt-0.5">
                                    {{ $isTecnico ? 'Ingresadas en mi departamento' : 'Solicitudes en estado Ingresada' }}
                                </p>
                            </div>
                            <span class="text-2xl font-bold text-blue-700 group-hover:scale-110 transition-transform">
                                {{ $misTareas['pendientes_asignar'] }}
                            </span>
                        </a>

                        <a href="{{ route('ejecuciones.index') }}"
                            class="flex items-center justify-between p-3 rounded-lg bg-yellow-50 hover:bg-yellow-100 transition group">
                            <div>
                                <p class="text-sm font-medium text-yellow-800">En Mis Manos</p>
                                <p class="text-xs text-yellow-500 mt-0.5">Asignadas o en ejecución</p>
                            </div>
                            <span class="text-2xl font-bold text-yellow-700 group-hover:scale-110 transition-transform">
                                {{ $misTareas['en_mis_manos'] }}
                            </span>
                        </a>

                    </div>
                </div>
            @else
                {{-- Usuario base: recordatorio de conformación --}}
                <div
                    class="bg-amber-50 rounded-xl border border-amber-100 p-5 flex items-center justify-center text-center text-amber-700 text-sm">
                    <div>
                        <svg class="w-8 h-8 mx-auto mb-2 text-amber-400" fill="none" stroke="currentColor" stroke-width="2"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        Recuerda conformar tus solicitudes una vez que el servicio técnico haya terminado.
                    </div>
                </div>
            @endif

            {{-- Acciones Rápidas --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-semibold text-gray-700 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" stroke-width="2"
                        viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                    Acciones Rápidas
                </h3>
                <div class="space-y-2">
                    <a href="{{ route('solicitudes.create') }}"
                        class="flex items-center gap-3 w-full px-4 py-2.5 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                        </svg>
                        Nueva Solicitud de Servicio
                    </a>
                    <a href="{{ route('solicitudes.index') }}"
                        class="flex items-center gap-3 w-full px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-200 text-gray-700 text-sm font-medium rounded-lg transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                        </svg>
                        Ver Mis Solicitudes
                    </a>
                    @if((auth()->user()->canManageTickets() || $isTecnico) && auth()->user()->canOperateInCurrentModule())
                        <a href="{{ route('asignaciones.index') }}"
                            class="flex items-center gap-3 w-full px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-200 text-gray-700 text-sm font-medium rounded-lg transition">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round"
                                    d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                            Bandeja de Recepción
                        </a>
                        <a href="{{ route('ejecuciones.index') }}"
                            class="flex items-center gap-3 w-full px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-200 text-gray-700 text-sm font-medium rounded-lg transition">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round"
                                    d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                            Ejecución del Servicio
                        </a>
                    @endif
                    <a href="{{ route('conformaciones.index') }}"
                        class="flex items-center gap-3 w-full px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-200 text-gray-700 text-sm font-medium rounded-lg transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        Conformación de Servicio
                    </a>
                </div>
            </div>

            {{-- Actividad Reciente --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-semibold text-gray-700 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" stroke-width="2"
                        viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round"
                            d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Actividad Reciente
                </h3>

                @if($actividadReciente->isEmpty())
                    <p class="text-sm text-gray-400 text-center py-4">No tienes solicitudes aún.<br>¡Crea una nueva!</p>
                @else
                    <div class="space-y-3">
                        @php
                            $estadoConfig = [
                                'I' => ['label' => 'Ingresada', 'class' => 'bg-blue-100 text-blue-700'],
                                'A' => ['label' => 'Asignada', 'class' => 'bg-indigo-100 text-indigo-700'],
                                'EJ' => ['label' => 'En Ejecución', 'class' => 'bg-emerald-100 text-emerald-700'],
                                'EE' => ['label' => 'En Espera', 'class' => 'bg-orange-100 text-orange-700'],
                                'CO' => ['label' => 'Ejecutado/Por Conformar', 'class' => 'bg-yellow-100 text-yellow-700'],
                                'CF' => ['label' => 'Conformada', 'class' => 'bg-indigo-100 text-indigo-700'],
                                'CE' => ['label' => 'Cerrada', 'class' => 'bg-green-100 text-green-700'],
                            ];
                        @endphp
                        @foreach($actividadReciente as $sol)
                            @php
                                $cfg = $estadoConfig[$sol->estado] ?? ['label' => $sol->estado, 'class' => 'bg-gray-100 text-gray-600'];
                                $authUser = auth()->user();

                                // Verificar si el usuario actual tiene asignación ACTIVA en esta solicitud
                                // (la relación 'asignaciones' ya viene filtrada por analista_id activo desde el controller)
                                $tieneAsignacionActiva = $authUser->canBeAssignedTickets()
                                    && $sol->relationLoaded('asignaciones')
                                    && $sol->asignaciones->isNotEmpty();

                                // Determinar la URL de destino según el estado, rol y asignación activa
                                $destUrl = match($sol->estado) {
                                    'I' => ($authUser->canManageTickets() || $authUser->canBeAssignedTickets())
                                            ? route('asignaciones.index')
                                            : route('solicitudes.index'),

                                    // Solo redirige a ejecuciones si tiene asignación activa en esta solicitud
                                    'A', 'EE', 'EJ' => $tieneAsignacionActiva
                                            ? route('ejecuciones.show', $sol->id)
                                            : route('solicitudes.index'),

                                    'CO' => ($sol->usuario_id == $authUser->id)
                                            ? route('conformaciones.show', $sol->id)
                                            : ($tieneAsignacionActiva
                                                ? route('ejecuciones.show', $sol->id)
                                                : route('solicitudes.index')),

                                    'CF' => ($sol->usuario_id == $authUser->id)
                                            ? route('conformaciones.index', ['tab' => 'conformadas'])
                                            : route('solicitudes.index'),

                                    'CE' => route('solicitudes.index'),

                                    default => route('solicitudes.index'),
                                };
                            @endphp
                            <a href="{{ $destUrl }}"
                               class="flex items-start gap-3 p-2 -mx-2 rounded-lg hover:bg-gray-50 transition-colors group cursor-pointer">
                                <div class="flex-shrink-0 w-2 h-2 rounded-full bg-green-400 mt-2 group-hover:bg-green-500 transition-colors"></div>
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center justify-between gap-2">
                                        <p class="text-xs font-semibold text-gray-800 truncate group-hover:text-green-700 transition-colors">
                                            #{{ $sol->numero }}
                                        </p>
                                        <span class="flex-shrink-0 text-xs px-1.5 py-0.5 rounded-full font-medium {{ $cfg['class'] }}">
                                            {{ $cfg['label'] }}
                                        </span>
                                    </div>
                                    <p class="text-xs text-gray-500 truncate mt-0.5">
                                        {{ Str::limit($sol->descripcion ?? $sol->areaTrabajo?->nombre ?? 'Sin detalle', 40) }}
                                    </p>
                                    <p class="text-xs text-gray-400 mt-0.5">{{ $sol->updated_at->diffForHumans() }}</p>
                                </div>
                                {{-- Ícono de flecha indicador de navegación --}}
                                <svg class="w-3 h-3 text-gray-300 group-hover:text-green-500 flex-shrink-0 mt-1 transition-colors"
                                     fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
                                </svg>
                            </a>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>


    </div>
</x-app-layout>