<x-app-layout>
    <x-slot name="header">
        Recepción de Solicitudes (Bandeja de Entrada)
    </x-slot>

    {{-- Mapa JSON: departamento_id → lista de analistas asignables (generado por Blade, sin AJAX) --}}
    @php
        $analistasPorDepto = [];
        $userAuth = auth()->user();
        $isAdmin = $userAuth->isAdmin();
        $miDeptoId = $userAuth->departamento_id;

        foreach ($departamentos as $dep) {
            if ($isAdmin || $dep->id == $miDeptoId) {
                $analistasPorDepto[$dep->id] = \App\Models\User::where('departamento_id', $dep->id)
                    ->get()
                    ->filter(fn($u) => $u->canBeAssignedTickets())
                    ->values()
                    ->map(fn($u) => ['id' => $u->id, 'name' => trim($u->name . ' ' . $u->apellido)])
                    ->toArray();
            } else {
                $analistasPorDepto[$dep->id] = [];
            }
        }
    @endphp

    <!-- Table -->
    <div class="bg-white shadow-lg rounded-sm border border-slate-200">
        <header class="px-5 py-4 border-b border-slate-100">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <h2 class="font-semibold text-slate-800">Recepción de Solicitudes <span
                        class="text-slate-400 font-medium">({{ $solicitudesPendientes->total() }})</span></h2>

                <form method="GET" action="{{ route('asignaciones.index') }}" class="flex">
                    <input type="hidden" name="tab" value="{{ $tab }}">
                    <input type="text" name="search" value="{{ request('search') }}" placeholder="Buscar por Nro..."
                        class="form-input text-sm rounded-l-md border-slate-300 border-r-0 focus:ring-0 w-full sm:w-56" />
                    <button type="submit"
                        class="btn bg-green-600 hover:bg-green-700 text-white rounded-r-md px-3 border border-transparent shadow-sm">
                        Buscar
                    </button>
                    @if(request('search'))
                        <a href="{{ route('asignaciones.index', ['tab' => $tab]) }}"
                            class="btn ml-2 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-md px-3 border border-slate-200 shadow-sm"
                            title="Limpiar">
                            &times;
                        </a>
                    @endif
                </form>
            </div>

            <!-- Tabs de Filtrado -->
            <div class="flex flex-wrap gap-2 mt-4">
                <a href="{{ route('asignaciones.index', ['tab' => 'ingresadas']) }}"
                    class="inline-flex items-center px-4 py-2 rounded-full text-sm font-medium transition-all duration-150
                          {{ $tab === 'ingresadas' ? 'bg-emerald-600 text-white shadow-md' : 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100' }}">
                    Ingresadas
                    <span
                        class="ml-2 inline-flex items-center justify-center px-2 py-0.5 rounded-full text-xs font-bold
                               {{ $tab === 'ingresadas' ? 'bg-white/20 text-white' : 'bg-emerald-100 text-emerald-700' }}">
                        {{ $contadores['ingresadas'] }}
                    </span>
                </a>
                <a href="{{ route('asignaciones.index', ['tab' => 'asignadas']) }}"
                    class="inline-flex items-center px-4 py-2 rounded-full text-sm font-medium transition-all duration-150
                          {{ $tab === 'asignadas' ? 'bg-amber-500 text-white shadow-md' : 'bg-amber-50 text-amber-700 hover:bg-amber-100' }}">
                    Asignadas
                    <span class="ml-2 inline-flex items-center justify-center px-2 py-0.5 rounded-full text-xs font-bold
                               {{ $tab === 'asignadas' ? 'bg-white/20 text-white' : 'bg-amber-100 text-amber-700' }}">
                        {{ $contadores['asignadas'] }}
                    </span>
                </a>
            </div>
        </header>

        <div class="p-3">
            <!-- Mensajes de Sesión -->
            @if(session('success'))
                <div x-data="{ show: true }" x-show="show"
                    class="mb-4 p-4 bg-emerald-50 border border-emerald-200 text-emerald-600 rounded">
                    <div class="flex justify-between">
                        <span>{{ session('success') }}</span>
                        <button @click="show = false" class="text-emerald-500 hover:text-emerald-700">&times;</button>
                    </div>
                </div>
            @endif
            @if(session('error'))
                <div x-data="{ show: true }" x-show="show"
                    class="mb-4 p-4 bg-rose-50 border border-rose-200 text-rose-600 rounded">
                    <div class="flex justify-between">
                        <span>{{ session('error') }}</span>
                        <button @click="show = false" class="text-rose-500 hover:text-rose-700">&times;</button>
                    </div>
                </div>
            @endif

            <!-- Desktop Table -->
            <div class="hidden md:block overflow-x-auto">
                <table class="table-auto w-full min-w-[1500px] border-collapse">
                    <thead
                        class="text-xs font-semibold uppercase text-slate-500 bg-slate-50 border-t border-b border-slate-200">
                        <tr>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-32">
                                <div class="font-semibold text-left">Nro. Solicitud</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-64">
                                <div class="font-semibold text-left">Solicitante</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-48">
                                <div class="font-semibold text-left">Área Requerida</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3">
                                <div class="font-semibold text-left">Descripción</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-32">
                                <div class="font-semibold text-left">Estado</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-40">
                                <div class="font-semibold text-left">Fecha</div>
                            </th>
                            <th class="px-2 first:pl-5 last:pr-5 py-3 w-96">
                                <div class="font-semibold text-center">Acciones</div>
                            </th>
                        </tr>
                    </thead>
                    <tbody class="text-sm divide-y divide-slate-200">
                        @forelse($solicitudesPendientes as $solicitud)
                            <tr>
                                <td class="px-2 first:pl-5 last:pr-5 py-3 whitespace-nowrap">
                                    <div class="font-medium text-sky-500">{{ $solicitud->numero }}</div>
                                </td>
                                <td class="px-2 first:pl-5 last:pr-5 py-3">
                                    <div class="font-medium text-slate-800">
                                        {{ optional($solicitud->usuario)->name }}
                                        {{ optional($solicitud->usuario)->apellido }}
                                    </div>
                                    <div class="text-xs text-slate-500">{{ optional($solicitud->usuario)->cedula }}</div>
                                    <div class="text-xs text-slate-400 mt-1">
                                        {{ optional(optional($solicitud->usuario)->gerencia)->nombre ?? 'N/A' }}
                                    </div>
                                </td>
                                <td class="px-2 first:pl-5 last:pr-5 py-3">
                                    <div class="text-slate-800 font-medium">
                                        {{ optional($solicitud->areaTrabajo)->nombre ?? 'N/A' }}
                                    </div>
                                </td>
                                <td class="px-2 first:pl-5 last:pr-5 py-3">
                                    <div class="text-slate-600 truncate max-w-xs" title="{{ $solicitud->descripcion }}">
                                        {{ \Illuminate\Support\Str::limit($solicitud->descripcion, 60) }}
                                    </div>
                                </td>
                                <td class="px-2 first:pl-5 last:pr-5 py-3 whitespace-nowrap">
                                    @if($solicitud->estado == 'I')
                                        <div
                                            class="inline-flex font-medium rounded-full px-2.5 py-0.5 bg-emerald-100 text-emerald-600 text-sm">
                                            Ingresada</div>
                                    @elseif($solicitud->estado == 'A')
                                        <div
                                            class="inline-flex font-medium rounded-full px-2.5 py-0.5 bg-amber-100 text-amber-600 text-sm">
                                            Asignada</div>
                                        @if(auth()->user()->canManageTickets())
                                            @php
                                                $analistaResp = $solicitud->asignaciones->where('activa', true)->first()->analista ?? null;
                                            @endphp
                                            @if($analistaResp)
                                                <div class="block mt-1">
                                                    <span class="text-[11px] font-semibold text-slate-500 uppercase">Resp:</span>
                                                    <span class="text-xs text-slate-700 font-medium" title="{{ $analistaResp->name }} {{ $analistaResp->apellido }}">
                                                        {{ strtok($analistaResp->name, ' ') }} {{ strtok($analistaResp->apellido, ' ') }}
                                                    </span>
                                                </div>
                                            @endif
                                        @endif

                                    @else
                                        <div
                                            class="inline-flex font-medium rounded-full px-2.5 py-0.5 bg-slate-100 text-slate-500 text-sm">
                                            {{ $solicitud->estado }}
                                        </div>
                                    @endif
                                </td>
                                <td class="px-2 first:pl-5 last:pr-5 py-3 whitespace-nowrap">
                                    <div class="text-sm text-slate-500 font-medium">
                                        {{ $solicitud->updated_at->format('d/m/Y h:i A') }}
                                    </div>
                                </td>


                                {{-- ══════════════ COLUMNA ACCIONES ══════════════ --}}
                                <td class="px-2 first:pl-5 last:pr-5 py-3 align-top">
                                    <div class="flex justify-center mb-3">
                                        <button x-data="" x-on:click.prevent="$dispatch('open-modal', 'ver-solicitud-{{ $solicitud->id }}')" class="text-slate-400 hover:text-slate-500 rounded-full"
                                            title="Ver detalles">
                                            <span class="sr-only">Ver</span>
                                            <svg class="w-8 h-8 fill-current" viewBox="0 0 32 32">
                                                <path
                                                    d="M16 20c-2.2 0-4-1.8-4-4s1.8-4 4-4 4 1.8 4 4-1.8 4-4 4zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
                                                <path
                                                    d="M16 23c-5.4 0-10.2-2.9-12.7-7.6.8-1.5 2-2.8 3.5-3.8 1.9-1.3 4.2-2 6.7-2 2.5 0 4.8.7 6.7 2 1.5 1 2.7 2.3 3.5 3.8C26.2 20.1 21.4 23 16 23zm0-11c-2.1 0-4.1.6-5.8 1.7-1.2.8-2.2 1.9-3 3.1 1.7 3.5 5.5 5.8 9.5 5.8s7.8-2.3 9.5-5.8c-.8-1.2-1.8-2.3-3-3.1-1.7-1.1-3.7-1.7-5.8-1.7z" />
                                            </svg>
                                        </button>

                                        <!-- Modal de Detalles -->
                                        <x-solicitud-modal :solicitud="$solicitud" />
                                    </div>
                                    @php
                                        $userAuth = auth()->user();
                                        $isTecnico = $userAuth->isRole(['técnico']);
                                        $canManage = $userAuth->canManageTickets();
                                        $asignacionActual = $solicitud->asignaciones->first();
                                        $depActualId = $solicitud->departamento_id;
                                        // Preselecciones iniciales para Alpine
                                        $initDepId = $asignacionActual?->departamento_destino_id ?? $depActualId ?? '';
                                        $initAnalistaId = $asignacionActual?->analista_id ?? '';
                                    @endphp

                                    @if($isTecnico)
                                        <div class="flex flex-col gap-2 min-w-[260px]">
                                            @if($solicitud->estado == 'A')
                                                {{-- Acción de Desasignar --}}
                                                <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}"
                                                    class="flex flex-col"
                                                    onsubmit="return confirm('¿Está seguro de desasignarse esta solicitud? Volverá a la bandeja de ingresadas.');">
                                                    @csrf
                                                    @method('PUT')
                                                    <input type="hidden" name="desasignar" value="1">
                                                    <div>
                                                        <button type="submit"
                                                            class="btn bg-red-600 hover:bg-red-700 text-white rounded-md px-4 py-1.5 w-full inline-flex items-center justify-center gap-2 text-sm font-medium shadow-sm border-none transition-all">
                                                            <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="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z">
                                                                </path>
                                                            </svg>
                                                            Desasignar
                                                        </button>
                                                    </div>
                                                </form>
                                            @else
                                                {{-- Acción de Auto-Asignación --}}
                                                <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}"
                                                    class="flex flex-col">
                                                    @csrf
                                                    @method('PUT')
                                                    <input type="hidden" name="asignarme" value="1">
                                                    <div>
                                                        <button type="submit"
                                                            class="btn bg-green-600 hover:bg-green-700 text-white rounded-md px-4 py-1.5 w-full inline-flex items-center justify-center gap-2 text-sm font-medium shadow-sm border-none transition-all">
                                                            <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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                            </svg>
                                                            Asignarme
                                                        </button>
                                                    </div>
                                                </form>
                                            @endif

                                            <div class="h-px bg-slate-100 my-1"></div>

                                            {{-- Acción de Redireccionamiento --}}
                                            <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}"
                                                class="flex flex-col gap-2">
                                                @csrf
                                                @method('PUT')
                                                <div>
                                                    <label class="text-sm font-medium text-slate-600 mb-1 block">Redirigir a
                                                        otro departamento</label>
                                                    <div class="flex items-center gap-2">
                                                        <select name="departamento_destino_id"
                                                            class="form-select text-sm py-1.5 px-3 border-slate-300 rounded bg-slate-50 text-slate-700 w-full shadow-sm"
                                                            required>
                                                            <option value="" disabled selected>Seleccionar...</option>
                                                            @foreach($departamentos as $dep)
                                                                @if($dep->id !== $depActualId)
                                                                    <option value="{{ $dep->id }}">{{ $dep->nombre }}</option>
                                                                @endif
                                                            @endforeach
                                                        </select>
                                                        <button type="submit"
                                                            class="rounded-md px-4 py-1.5 inline-flex items-center text-sm font-semibold shadow-sm whitespace-nowrap transition-all"
                                                            style="background-color: #2B7A4C; color: white !important; border: none;">
                                                            Redirigir
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>

                                        {{-- ── ROLES SUPERIORES: depto → analista en cascada ── --}}
                                    @elseif($canManage)
                                        <div x-data="{
                                                                                                              mapa: {{ Js::from($analistasPorDepto) }},
                                                                                                              depId: '{{ $initDepId }}',
                                                                                                              analistas: [],
                                                                                                              analista: '{{ $initAnalistaId }}',
                                                                                                              init() {
                                                                                                                  this.cargarAnalistas();
                                                                                                             },
                                                                                                             cargarAnalistas() {
                                                                                                                     this.analistas = this.depId ? (this.mapa[this.depId] || []) : [];
                                                                                                                     if (!this.analistas.find(a => String(a.id) === String(this.analista))) {
                                                                                                                         this.analista = '';
                                                                                                                     }
                                                                                                                 }
                                                                                                             }"
                                            class="flex flex-col gap-2 min-w-[260px]">
                                            <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}"
                                                class="flex flex-col gap-2">
                                                @csrf
                                                @method('PUT')

                                                {{-- Campo oculto que envía el analista_id seleccionado --}}
                                                <input type="hidden" name="analista_id" :value="analista">

                                                {{-- 1. Departamento destino --}}
                                                <div>
                                                    <label class="text-sm font-medium text-slate-600 mb-1 block">1. Departamento
                                                        destino</label>
                                                    <select name="departamento_destino_id" x-model="depId"
                                                        @change="analista = ''; cargarAnalistas()"
                                                        class="form-select text-sm py-1.5 px-3 border-slate-300 rounded bg-amber-50 text-slate-700 w-full shadow-sm">
                                                        <option value="">— Seleccionar departamento —</option>
                                                        @foreach($departamentos as $dep)
                                                            <option value="{{ $dep->id }}">
                                                                {{ $dep->nombre }}
                                                                @if($dep->id == $depActualId) (actual) @endif
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>

                                                {{-- 2. Analista / Técnico del departamento seleccionado --}}
                                                <div>
                                                    <label class="text-sm font-medium text-slate-600 mb-1 block">2. Analista /
                                                        Técnico</label>
                                                    <div class="flex items-center gap-2">
                                                        <select x-model="analista" :disabled="analistas.length === 0"
                                                            class="form-select text-sm py-1.5 px-3 border-slate-300 rounded bg-slate-50 text-slate-700 w-full shadow-sm"
                                                            :class="{ 'opacity-50 cursor-not-allowed': analistas.length === 0 }">
                                                            <option value="">
                                                                <span
                                                                    x-text="depId ? (analistas.length === 0 ? 'Sin personal — Se redirigirá' : 'Nadie (Solo Redirigir)') : 'Seleccione depto. primero'"></span>
                                                            </option>
                                                            <template x-for="a in analistas" :key="a.id">
                                                                <option :value="a.id" x-text="a.name"></option>
                                                            </template>
                                                        </select>
                                                        <button type="submit" :disabled="!depId"
                                                            class="btn bg-green-600 hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-md px-4 py-1.5 inline-flex items-center text-sm font-medium shadow-md whitespace-nowrap border-none transition-all">
                                                            <span
                                                                x-text="analista ? ({{ $solicitud->estado == 'I' ? "'Asignar'" : "'Reasignar'" }}) : 'Redirigir a Depto'"></span>
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>

                                        {{-- ── Sin permisos de gestión pero puede recibirse ── --}}
                                    @elseif($solicitud->estado == 'I' && $userAuth->canReceiveTickets())
                                        <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}">
                                            @csrf
                                            @method('PUT')
                                            <button type="submit"
                                                class="btn bg-green-600 hover:bg-green-700 text-white rounded-md px-4 py-2 flex items-center text-sm font-medium shadow-md border-none transition-all">
                                                Recibir / Asignarme
                                            </button>
                                        </form>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="px-2 first:pl-5 last:pr-5 py-5 text-center text-slate-500 italic">
                                    Bandeja limpia. No hay solicitudes pendientes de recepción.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <!-- Mobile Cards -->
            <div class="md:hidden space-y-4">
                @forelse($solicitudesPendientes as $solicitud)
                    @php
                        $userAuth = auth()->user();
                        $isTecnico = $userAuth->isRole(['técnico']);
                        $canManage = $userAuth->canManageTickets();
                        $asignacionActual = $solicitud->asignaciones->first();
                        $depActualId = $solicitud->departamento_id;
                        $initDepId = $asignacionActual?->departamento_destino_id ?? $depActualId ?? '';
                        $initAnalistaId = $asignacionActual?->analista_id ?? '';
                    @endphp
                    <div class="bg-white border border-slate-200 rounded-lg shadow-sm p-4">
                        <div class="flex justify-between items-start mb-3">
                            <div class="font-bold text-sky-600 text-lg">
                                #{{ $solicitud->numero }}
                            </div>
                            <div>
                                @if($solicitud->estado == 'I')
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-emerald-100 text-emerald-600">Ingresada</span>
                                @elseif($solicitud->estado == 'A')
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-amber-100 text-amber-600">Asignada</span>
                                @else
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-slate-100 text-slate-500">{{ $solicitud->estado }}</span>
                                @endif
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-2 text-xs mb-3">
                            <div>
                                <span class="block text-slate-400 uppercase font-bold text-[10px]">Solicitante</span>
                                <span class="text-slate-800 font-medium">{{ optional($solicitud->usuario)->name }} {{ optional($solicitud->usuario)->apellido }}</span>
                            </div>
                            <div>
                                <span class="block text-slate-400 uppercase font-bold text-[10px]">Ubicación</span>
                                <span class="text-slate-800 font-medium">{{ optional($solicitud->areaTrabajo)->nombre ?? 'N/A' }}</span>
                            </div>
                        </div>

                        <div class="mb-3">
                            <span class="block text-slate-400 uppercase font-bold text-[10px]">Descripción</span>
                            <p class="text-sm text-slate-600 line-clamp-2 italic">"{{ $solicitud->descripcion }}"</p>
                        </div>

                        <div class="flex items-center justify-between py-2 border-t border-b border-slate-50 mb-4">
                             <div class="text-[11px] text-slate-400">
                                {{ $solicitud->updated_at->format('d/m/Y h:i A') }}
                             </div>
                             <button x-data="" x-on:click.prevent="$dispatch('open-modal', 'ver-solicitud-{{ $solicitud->id }}')" 
                                class="text-sky-600 font-bold text-xs flex items-center">
                                <svg class="w-4 h-4 mr-1" 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>
                                VER DETALLES
                             </button>
                             <x-solicitud-modal :solicitud="$solicitud" />
                        </div>

                        {{-- Acciones en Móvil --}}
                        <div class="space-y-3 bg-slate-50 p-3 rounded-lg">
                            @if($isTecnico)
                                @if($solicitud->estado == 'A')
                                    <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}" onsubmit="return confirm('¿Está seguro de desasignarse?');">
                                        @csrf @method('PUT')
                                        <input type="hidden" name="desasignar" value="1">
                                        <button type="submit" class="w-full bg-red-600 text-white text-xs font-bold py-2 rounded shadow-sm uppercase">Desasignar</button>
                                    </form>
                                @else
                                    <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}">
                                        @csrf @method('PUT')
                                        <input type="hidden" name="asignarme" value="1">
                                        <button type="submit" class="w-full bg-green-600 text-white text-xs font-bold py-2 rounded shadow-sm uppercase">Asignarme</button>
                                    </form>
                                @endif
                                
                                <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}" class="mt-2 pt-2 border-t border-slate-200">
                                    @csrf @method('PUT')
                                    <label class="text-[10px] font-bold text-slate-500 uppercase mb-1 block">Redirigir a:</label>
                                    <div class="flex gap-2">
                                        <select name="departamento_destino_id" class="form-select text-xs py-1 px-2 border-slate-300 rounded bg-white w-full shadow-sm" required>
                                            <option value="" disabled selected>Departamento...</option>
                                            @foreach($departamentos as $dep)
                                                @if($dep->id !== $depActualId)
                                                    <option value="{{ $dep->id }}">{{ $dep->nombre }}</option>
                                                @endif
                                            @endforeach
                                        </select>
                                        <button type="submit" class="bg-slate-800 text-white text-[10px] px-3 py-1 rounded font-bold uppercase">Redirigir</button>
                                    </div>
                                </form>
                            @elseif($canManage)
                                <div x-data="{ mapa: {{ Js::from($analistasPorDepto) }}, depId: '{{ $initDepId }}', analistas: [], analista: '{{ $initAnalistaId }}', init() { this.cargarAnalistas(); }, cargarAnalistas() { this.analistas = this.depId ? (this.mapa[this.depId] || []) : []; if (!this.analistas.find(a => String(a.id) === String(this.analista))) { this.analista = ''; } } }">
                                    <form method="POST" action="{{ route('asignaciones.update', $solicitud->id) }}" class="space-y-2">
                                        @csrf @method('PUT')
                                        <input type="hidden" name="analista_id" :value="analista">
                                        
                                        <div>
                                            <label class="text-[10px] font-bold text-slate-500 uppercase mb-1 block">1. Departamento Destino:</label>
                                            <select name="departamento_destino_id" x-model="depId" @change="analista = ''; cargarAnalistas()" class="form-select text-xs py-1 px-2 border-slate-300 rounded bg-white w-full">
                                                <option value="">Seleccionar...</option>
                                                @foreach($departamentos as $dep)
                                                    <option value="{{ $dep->id }}">{{ $dep->nombre }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div>
                                            <label class="text-[10px] font-bold text-slate-500 uppercase mb-1 block">2. Analista Responsable:</label>
                                            <select x-model="analista" :disabled="analistas.length === 0" class="form-select text-xs py-1 px-2 border-slate-300 rounded bg-white w-full">
                                                <option value="">Nadie (Solo Redirigir)</option>
                                                <template x-for="a in analistas" :key="a.id">
                                                    <option :value="a.id" x-text="a.name"></option>
                                                </template>
                                            </select>
                                        </div>

                                        <button type="submit" :disabled="!depId" class="w-full bg-green-600 text-white text-xs font-bold py-2 rounded shadow-sm uppercase disabled:opacity-50">
                                            <span x-text="analista ? 'Asignar / Reasignar' : 'Redirigir a Depto'"></span>
                                        </button>
                                    </form>
                                </div>
                            @endif
                        </div>
                    </div>
                @empty
                    <div class="text-center py-10 text-slate-500 italic">
                        Bandeja limpia. No hay solicitudes pendientes.
                    </div>
                @endforelse
            </div>

            <!-- Pagination -->
            <div class="mt-4">
                {{ $solicitudesPendientes->links() }}
            </div>
        </div>
    </div>

</x-app-layout>