<x-app-layout>
<x-slot name="header"><div><p class="text-[10px] font-black uppercase tracking-widest text-indigo-600">Aula virtual</p><h2 class="text-xl font-black dark:text-white">{{$curso->nombre}}</h2></div></x-slot>
@php
$completed=auth()->user()->leccionesCompletadas()->where('curso_id',$curso->id)->pluck('lecciones.id');
$publishedExams=$curso->examenes->where('publicado',true); $total=$curso->lecciones->count()+$curso->tareas->count()+$publishedExams->count();
$submitted=$misEntregas->whereNotNull('entregada_at')->count(); $examDone=$examResults->count(); $done=$completed->count()+$submitted+$examDone; $progress=$total?min(100,round($done*100/$total)):0;
$nextTasks=$curso->tareas->where('publicada',true)->where('fecha_limite','>=',now())->sortBy('fecha_limite');
$standalone=$curso->lecciones->whereNull('unidad_id'); $unread=$mensajes->where('destinatario_id',auth()->id())->whereNull('leido_at')->count();
$weightedTasks=$curso->tareas->filter(fn($t)=>$t->ponderacion>0&&$misEntregas->get($t->id)?->calificacion!==null);
$weightedExams=$publishedExams->filter(fn($e)=>$e->ponderacion>0&&$examResults->has($e->id));
$weight=$weightedTasks->sum('ponderacion')+$weightedExams->sum('ponderacion');
$weightedScore=$weightedTasks->sum(fn($t)=>($misEntregas->get($t->id)->calificacion/$t->puntaje_maximo)*10*$t->ponderacion)+$weightedExams->sum(fn($e)=>($examResults->get($e->id)->first()->calificacion)*$e->ponderacion);
$courseGrade=$weight?round($weightedScore/$weight,1):null;
$field='w-full rounded-xl border-slate-300 text-sm dark:border-slate-700 dark:bg-slate-900';
@endphp
<div x-data="{section:@js(request('seccion','inicio'))}" class="mx-auto max-w-7xl space-y-5 p-4 sm:p-6">
@if(session('success'))<div class="rounded-2xl bg-emerald-50 p-4 text-sm font-bold text-emerald-700">✓ {{session('success')}}</div>@endif
@if($errors->any())<div class="rounded-2xl bg-rose-50 p-4 text-sm font-bold text-rose-700">{{$errors->first()}}</div>@endif
<section class="overflow-hidden rounded-[2rem] bg-gradient-to-br from-indigo-700 via-violet-700 to-slate-900 p-6 text-white shadow-xl sm:p-8"><div class="flex flex-col justify-between gap-6 lg:flex-row lg:items-end"><div><a href="{{route('alumno.dashboard',['section'=>'cursos'])}}" class="text-xs font-black text-indigo-200">← Mis cursos</a><p class="mt-4 text-xs font-black uppercase tracking-[.2em] text-indigo-200">Mi ruta de aprendizaje</p><h1 class="mt-2 text-3xl font-black sm:text-4xl">{{$curso->nombre}}</h1><p class="mt-2 max-w-2xl text-indigo-100">{{$curso->descripcion?:'Avanza por las unidades, completa actividades y consulta tu retroalimentación.'}}</p><div class="mt-4 flex flex-wrap gap-2"><span class="rounded-full bg-white/15 px-3 py-1 text-xs font-bold">{{$curso->sede->nombre}}</span><span class="rounded-full bg-white/15 px-3 py-1 text-xs font-bold">Docente: {{$curso->user?->name??'Equipo académico'}}</span></div></div><div class="min-w-56 rounded-2xl bg-white/10 p-4"><div class="flex justify-between text-sm font-black"><span>Avance</span><span>{{$progress}}%</span></div><div class="mt-2 h-2 overflow-hidden rounded-full bg-white/20"><div class="h-full bg-emerald-400" style="width:{{$progress}}%"></div></div><small class="mt-2 block text-indigo-100">{{$done}} de {{$total}} elementos completados</small></div></div></section>
<div class="grid gap-5 lg:grid-cols-[15rem_minmax(0,1fr)]"><aside class="h-fit rounded-2xl border bg-white p-2 shadow-sm dark:border-slate-700 dark:bg-slate-800 lg:sticky lg:top-4"><p class="px-3 py-2 text-xs font-black uppercase text-slate-400">Dentro del curso</p>@foreach(['inicio'=>'Inicio','contenido'=>'Contenido','actividades'=>'Actividades','evaluaciones'=>'Evaluaciones','calificaciones'=>'Calificaciones','comunicacion'=>'Comunicación','participantes'=>'Participantes'] as $key=>$label)<button @click="section='{{$key}}'" :class="section==='{{$key}}'?'bg-indigo-600 text-white shadow':'text-slate-600 dark:text-slate-300'" class="flex w-full justify-between rounded-xl px-3 py-3 text-left text-sm font-black"><span>{{$label}}</span>@if($key==='comunicacion'&&$unread)<span class="rounded-full bg-rose-500 px-2 text-white">{{$unread}}</span>@endif</button>@endforeach</aside>
<main class="min-w-0 space-y-5">
<section x-show="section==='inicio'" class="space-y-5"><div class="grid gap-3 sm:grid-cols-4">@foreach([['Contenido',$curso->lecciones->count(),'Recursos disponibles','text-indigo-600'],['Por entregar',$nextTasks->filter(fn($t)=>!$misEntregas->get($t->id)?->entregada_at)->count(),'Actividades pendientes','text-amber-600'],['Completado',$done,'Elementos terminados','text-emerald-600'],['Promedio',$courseGrade??'—','Ponderación publicada','text-violet-600']] as [$label,$value,$caption,$tone])<article class="rounded-2xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><p class="text-xs font-black uppercase {{$tone}}">{{$label}}</p><b class="mt-2 block text-3xl">{{$value}}</b><small class="text-slate-500">{{$caption}}</small></article>@endforeach</div>
@if($anuncios->isNotEmpty())<article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="text-xl font-black">Anuncios del docente</h3><div class="mt-3 space-y-3">@foreach($anuncios as $a)<div class="rounded-2xl {{$a->destacado?'bg-amber-50 dark:bg-amber-950/30':'bg-slate-50 dark:bg-slate-900'}} p-4"><div class="flex justify-between gap-3"><b>{{$a->titulo}}</b><small class="text-slate-500">{{$a->publicado_at->diffForHumans()}}</small></div><p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{$a->mensaje}}</p></div>@endforeach</div></article>@endif
<article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="text-xl font-black">Próximas entregas</h3><div class="mt-3 space-y-2">@forelse($nextTasks->take(5) as $t)<button @click="section='actividades'" class="flex w-full items-center justify-between rounded-xl bg-amber-50 p-4 text-left dark:bg-amber-950/30"><span><b>{{$t->titulo}}</b><small class="block text-slate-500">{{$t->fecha_limite->format('d/m/Y H:i')}}</small></span><span class="text-xs font-black text-amber-700">{{$misEntregas->get($t->id)?->entregada_at?'Entregada':($misEntregas->has($t->id)?'Borrador':'Pendiente')}}</span></button>@empty<p class="rounded-xl border border-dashed p-8 text-center text-slate-500">No tienes entregas próximas.</p>@endforelse</div></article></section>

<section x-show="section==='contenido'" x-cloak class="space-y-4"><div><h3 class="text-2xl font-black">Ruta de aprendizaje</h3><p class="text-sm text-slate-500">El contenido mostrado aquí fue cargado y programado por tu docente.</p></div>
@foreach($curso->unidades as $u)<x-student-unit :unit="$u" :lessons="$curso->lecciones->where('unidad_id',$u->id)" :completed="$completed" :locked="$lockedLessonIds"/>@endforeach
@if($standalone->isNotEmpty())<x-student-unit title="Material general" :lessons="$standalone" :completed="$completed" :locked="$lockedLessonIds"/>@endif
@if($curso->unidades->isEmpty()&&$standalone->isEmpty())<p class="rounded-3xl border-2 border-dashed p-12 text-center text-slate-500">Todavía no hay contenido publicado por el docente.</p>@endif</section>

<section x-show="section==='actividades'" x-cloak class="space-y-4"><h3 class="text-2xl font-black">Actividades y entregas</h3>@forelse($curso->tareas->where('publicada',true) as $t)@php($delivery=$misEntregas->get($t->id))<article class="rounded-3xl border bg-white p-6 dark:border-slate-700 dark:bg-slate-800"><div class="flex justify-between gap-3"><div><h4 class="text-lg font-black">{{$t->titulo}}</h4><p class="text-xs text-slate-500">Límite {{$t->fecha_limite->format('d/m/Y H:i')}} · {{$t->puntaje_maximo}} puntos</p></div><span class="h-fit rounded-full bg-slate-100 px-3 py-1 text-xs font-black dark:bg-slate-700">{{$delivery?->estatus??'PENDIENTE'}}</span></div><p class="mt-3 text-sm text-slate-600 dark:text-slate-300">{{$t->instrucciones}}</p>@if($delivery?->calificada_at)<div class="mt-4 rounded-2xl bg-emerald-50 p-4 text-sm text-emerald-800"><strong>Calificación: {{$delivery->calificacion}} / {{$t->puntaje_maximo}}</strong><p>{{$delivery->retroalimentacion}}</p></div>@else<form method="POST" enctype="multipart/form-data" action="{{route('alumno.aulas.tareas.submit',$t)}}" class="mt-4 grid gap-3">@csrf<textarea name="comentario_alumno" placeholder="Comentario o respuesta" class="{{$field}}">{{$delivery?->comentario_alumno}}</textarea><label class="text-xs font-bold">Adjuntar evidencia<input type="file" name="archivo" class="mt-1 block w-full text-xs"></label>@if($delivery?->archivo_path)<a href="{{route('lms.deliveries.file',$delivery)}}" class="text-xs font-black text-indigo-600">Archivo actual: {{$delivery->archivo_nombre}}</a>@endif<div class="flex flex-wrap justify-end gap-2"><button name="accion" value="BORRADOR" class="rounded-xl border px-4 py-2 text-sm font-black dark:border-slate-600">Guardar borrador</button><button name="accion" value="ENTREGAR" class="rounded-xl bg-indigo-600 px-5 py-2 text-sm font-black text-white">Entregar actividad</button></div></form>@endif</article>@empty<p class="rounded-2xl border-2 border-dashed p-8 text-center text-slate-400">No hay tareas publicadas</p>@endforelse</section>

<section x-show="section==='evaluaciones'" x-cloak class="space-y-4"><h3 class="text-2xl font-black">Evaluaciones</h3><div class="grid gap-4 sm:grid-cols-2">@forelse($publishedExams as $e)@php($available=(!$e->disponible_desde||now()->gte($e->disponible_desde))&&(!$e->disponible_hasta||now()->lte($e->disponible_hasta)))<article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><span class="text-xs font-black text-amber-600">EVALUACIÓN</span><h4 class="mt-1 text-xl font-black">{{$e->titulo}}</h4><p class="text-sm text-slate-500">{{$e->limite_tiempo}} min · {{$e->intentos_permitidos}} intento(s) · {{$examResults->get($e->id)?->count()??0}} realizados</p>@if($available)<a href="{{route('alumno.examen',$e)}}" class="mt-4 inline-flex rounded-xl bg-amber-500 px-4 py-2 text-sm font-black text-white">Iniciar evaluación</a>@else<p class="mt-4 text-xs font-black text-slate-500">Disponible {{$e->disponible_desde?->format('d/m/Y H:i')??'próximamente'}}</p>@endif</article>@empty<p class="col-span-full rounded-2xl border-2 border-dashed p-8 text-center text-slate-400">No hay evaluaciones disponibles.</p>@endforelse</div></section>

<section x-show="section==='calificaciones'" x-cloak><article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><div class="flex justify-between"><div><h3 class="text-2xl font-black">Libro de calificaciones</h3><p class="text-sm text-slate-500">Tareas, evaluaciones y retroalimentación.</p></div><b class="text-2xl text-indigo-600">{{$courseGrade??'—'}}</b></div><div class="mt-5 space-y-3">@foreach($curso->tareas as $t)@php($d=$misEntregas->get($t->id))<div class="flex justify-between gap-4 rounded-xl bg-slate-50 p-4 dark:bg-slate-900"><span><b>{{$t->titulo}}</b><small class="block text-slate-500">{{$d?->retroalimentacion?:'Sin retroalimentación publicada'}}</small></span><b>{{$d?->calificacion??'—'}} / {{$t->puntaje_maximo}}</b></div>@endforeach @foreach($publishedExams as $e)<div class="flex justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-900"><span><b>{{$e->titulo}}</b><small class="block text-slate-500">Mejor/último intento publicado</small></span><b>{{$examResults->get($e->id)?->first()->calificacion??'—'}} / 10</b></div>@endforeach @if($curso->tareas->isEmpty()&&$publishedExams->isEmpty())<p class="text-sm text-slate-500">Todavía no hay actividades calificables.</p>@endif</div></article></section>

<section x-show="section==='comunicacion'" x-cloak class="space-y-5"><div class="grid gap-5 xl:grid-cols-2"><article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="font-black">Foros</h3>@forelse($curso->foros as $f)<div class="mt-3 rounded-2xl bg-slate-50 p-4 dark:bg-slate-900"><b>{{$f->titulo}}</b><p class="text-xs text-slate-500">{{$f->descripcion}}</p><form method="POST" action="{{route('lms.foros.post',$f)}}" class="mt-3 flex">@csrf<input name="contenido" required placeholder="Participar" class="min-w-0 flex-1 rounded-l-lg text-xs dark:bg-slate-800"><button class="rounded-r-lg bg-indigo-600 px-3 text-xs text-white">Publicar</button></form></div>@empty<p class="mt-4 text-sm text-slate-500">No hay foros abiertos.</p>@endforelse</article><article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="font-black">Mensaje al docente</h3><form method="POST" action="{{route('lms.messages.store',$curso)}}" class="mt-3 grid gap-2">@csrf<input type="hidden" name="destinatario_id" value="{{$curso->user_id}}"><input name="asunto" required placeholder="Asunto" class="{{$field}}"><textarea name="mensaje" required placeholder="Mensaje" class="{{$field}}"></textarea><button class="rounded-xl bg-slate-900 py-2 text-sm font-black text-white">Enviar mensaje</button></form></article></div><article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="font-black">Historial de mensajes</h3><div class="mt-3 divide-y dark:divide-slate-700">@forelse($mensajes as $m)<div class="py-4"><div class="flex justify-between gap-3"><b>{{$m->asunto}}</b><small class="text-slate-500">{{$m->created_at->diffForHumans()}}</small></div><p class="text-xs font-bold text-indigo-600">{{$m->remitente?->name}}</p><p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{$m->mensaje}}</p>@if(($m->destinatario_id===auth()->id()||$m->destinatario_id===null)&&!$m->leido_at)<form method="POST" action="{{route('alumno.mensajes.read',$m)}}" class="mt-2">@csrf @method('PATCH')<button class="text-xs font-black text-indigo-600">Marcar como leído</button></form>@endif</div>@empty<p class="py-8 text-center text-sm text-slate-500">No hay mensajes todavía.</p>@endforelse</div></article>
@foreach($encuestas as $survey)<article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="font-black">Encuesta · {{$survey->titulo}}</h3><p class="text-sm text-slate-500">{{$survey->pregunta}}</p><form method="POST" action="{{route('alumno.encuestas.answer',$survey)}}" class="mt-3 flex flex-wrap gap-2">@csrf<select name="valor" required class="rounded-xl text-sm dark:bg-slate-900"><option value="">Valoración</option>@foreach(range(1,5) as $n)<option value="{{$n}}">{{$n}} / 5</option>@endforeach</select><input name="comentario" placeholder="Comentario opcional" class="min-w-56 flex-1 rounded-xl text-sm dark:bg-slate-900"><button class="rounded-xl bg-violet-600 px-4 text-sm font-black text-white">Responder</button></form></article>@endforeach</section>
<section x-show="section==='participantes'" x-cloak><article class="rounded-3xl border bg-white p-5 dark:border-slate-700 dark:bg-slate-800"><h3 class="text-2xl font-black">Participantes</h3><div class="mt-4 grid gap-3 sm:grid-cols-2">@foreach($curso->usuarios as $student)<div class="rounded-xl bg-slate-50 p-4 dark:bg-slate-900"><b>{{$student->name}}</b><small class="block text-slate-500">Estudiante</small></div>@endforeach</div></article></section>
</main></div></div><style>[x-cloak]{display:none!important}</style>
</x-app-layout>
