@extends('admin.layouts.app')
@section('title', isset($participante) ? 'Editar Participante' : 'Agregar Participante')

@section('styles')
<style>
:root { --cc-blue:#1a237e; --cc-gold:#ffe082; }

/* ── Hero ── */
.part-form-hero {
    background: linear-gradient(135deg,#0d1b6e 0%,#1a237e 45%,#1565c0 100%);
    border-radius: 20px; padding: 22px 28px;
    margin-bottom: 24px; position: relative; overflow: hidden;
}
.part-form-hero::after {
    content:''; position:absolute; right:-50px; top:-50px;
    width:200px; height:200px; border-radius:50%; background:rgba(255,255,255,.04);
}

/* ── Sections ── */
.form-sec {
    background: #fff; border-radius: 18px;
    border: 1.5px solid #e8edf5;
    box-shadow: 0 2px 16px rgba(0,0,0,.05);
    overflow: hidden; margin-bottom: 0;
    display: flex; flex-direction: column;
    height: 100%;
}
.form-sec-hdr {
    padding: 14px 20px;
    display: flex; align-items: center; gap: 10px;
    border-bottom: 1.5px solid #f1f5f9; flex-shrink: 0;
}
.sec-icon {
    width: 36px; height: 36px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px; flex-shrink: 0;
}
.form-sec-body { padding: 20px; flex: 1; overflow-y: auto; }

/* ── Inputs ── */
.fl { font-size:12.5px; font-weight:700; color:#475569; margin-bottom:5px; display:block; }
.fl .req { color:#ef4444; }
.fi {
    width:100%; padding:9px 13px;
    border:1.5px solid #e2e8f0; border-radius:10px;
    font-size:.87rem; color:#1e293b; background:#fafcff;
    transition:border-color .2s,box-shadow .2s; outline:none;
}
.fi:focus { border-color:#1a237e; box-shadow:0 0 0 3px rgba(26,35,126,.1); background:#fff; }
.fi::placeholder { color:#c0cbd8; }
.fc-select { appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24'%3E%3Cpath fill='%2394a3b8' d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;padding-right:30px; }
.fg { margin-bottom:14px; }

/* ── Tabla de respuestas ── */
.resp-tbl { width:100%; border-collapse:collapse; }
.resp-tbl thead th {
    background:#1a237e; color:#ffe082;
    padding:9px 10px; font-size:11px; font-weight:800;
    letter-spacing:.4px; text-align:center;
}
.resp-tbl thead th:first-child { text-align:center; width:56px; }
.resp-tbl thead th:last-child { text-align:left; }
.resp-tbl tbody td {
    padding:6px 10px; border-bottom:1px solid #f1f5f9;
    vertical-align:middle; text-align:center;
}
.resp-tbl tbody td:last-child { text-align:left; }
.resp-tbl tbody tr:hover { background:#fafbff; }
.resp-tbl tbody tr:last-child td { border-bottom:none; }

.resp-num-badge {
    display:inline-flex;align-items:center;justify-content:center;
    width:28px;height:28px;border-radius:8px;
    background:linear-gradient(135deg,#1a237e,#283593);
    color:#ffe082;font-size:10px;font-weight:800;
}
.resp-correcta {
    font-weight:800; color:#059669;
    background:#f0fdf4; border:1px solid #bbf7d0;
    padding:3px 10px; border-radius:8px; font-size:12px;
}
.resp-pts {
    font-size:10px; color:#94a3b8; margin-top:2px; font-weight:600;
}

/* Highlight de respuesta alumno */
.resp-input {
    border:1.5px solid #e2e8f0;
    border-radius:8px; padding:6px 10px;
    font-size:.85rem; width:100%;
    outline:none; transition:all .2s;
    background:#fafcff;
}
.resp-input:focus { border-color:#1a237e; box-shadow:0 0 0 3px rgba(26,35,126,.1); }
.resp-input.is-valid   { border-color:#16a34a !important; background:#f0fdf4 !important; color:#15803d; font-weight:700; }
.resp-input.is-invalid { border-color:#dc2626 !important; background:#fef2f2 !important; color:#991b1b; font-weight:700; }

/* ── Action bar ── */
.action-bar {
    background:#fff;border-radius:16px;
    border:1.5px solid #e8edf5;padding:16px 22px;
    display:flex;align-items:center;justify-content:space-between;gap:12px;
    box-shadow:0 2px 16px rgba(0,0,0,.05);flex-wrap:wrap;
    margin-top:22px;
}
.btn-save {
    display:inline-flex;align-items:center;gap:8px;
    padding:12px 28px;background:linear-gradient(135deg,#1a237e,#4527a0);
    color:#fff;border:none;border-radius:12px;font-weight:800;font-size:.9rem;
    cursor:pointer;box-shadow:0 4px 16px rgba(26,35,126,.3);transition:all .2s;
}
.btn-save:hover { transform:translateY(-2px);box-shadow:0 8px 24px rgba(26,35,126,.4); }
.btn-cancel {
    display:inline-flex;align-items:center;gap:8px;padding:11px 22px;
    background:#f8faff;color:#64748b;border:1.5px solid #e2e8f0;
    border-radius:12px;font-weight:700;font-size:.9rem;text-decoration:none;transition:all .18s;
}
.btn-cancel:hover { background:#f1f5f9;color:#334155; }
</style>
@endsection

@section('content')

{{-- ═══════ HERO ═══════ --}}
<div class="part-form-hero">
    <div style="display:flex;align-items:center;gap:14px;position:relative;z-index:1;">
        <a href="{{ route('admin.concursos.participantes.index', $concurso) }}"
           style="width:40px;height:40px;border-radius:12px;background:rgba(255,255,255,.12);border:1.5px solid rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;color:#fff;text-decoration:none;flex-shrink:0;transition:background .2s;"
           onmouseover="this.style.background='rgba(255,255,255,.22)'" onmouseout="this.style.background='rgba(255,255,255,.12)'">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:1.2px;color:rgba(255,255,255,.5);margin-bottom:4px;">
                <i class="bi bi-trophy-fill me-1" style="color:var(--cc-gold);"></i>
                {{ $concurso->sigla ?? 'Concurso' }} · {{ $concurso->anio }}
            </div>
            <h1 style="color:#fff;font-size:1.35rem;font-weight:800;margin:0 0 2px;letter-spacing:-.4px;">
                <i class="bi bi-person-{{ isset($participante) ? 'gear' : 'plus' }}-fill me-2" style="color:var(--cc-gold);"></i>
                {{ isset($participante) ? 'Editar Participante' : 'Agregar Participante' }}
            </h1>
            <p style="color:rgba(255,255,255,.6);margin:0;font-size:.82rem;">{{ $concurso->nombre }}</p>
        </div>
    </div>
</div>

{{-- ═══════ ERRORES ═══════ --}}
@if($errors->any())
<div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:12px;padding:14px 18px;margin-bottom:20px;color:#991b1b;font-size:.87rem;">
    <div style="font-weight:700;margin-bottom:6px;"><i class="bi bi-exclamation-triangle-fill me-2"></i>Hay errores en el formulario:</div>
    <ul style="margin:0;padding-left:18px;">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
</div>
@endif

<form action="{{ isset($participante)
    ? route('admin.concursos.participantes.update', [$concurso, $participante])
    : route('admin.concursos.participantes.store', $concurso) }}"
    method="POST">
    @csrf
    @if(isset($participante)) @method('PUT') @endif

    <div style="display:grid;grid-template-columns:5fr 7fr;gap:22px;" class="part-grid">

        {{-- ══════ DATOS DEL ESTUDIANTE ══════ --}}
        <div>
            <div class="form-sec">
                <div class="form-sec-hdr">
                    <div class="sec-icon" style="background:#eff6ff;">
                        <i class="bi bi-person-fill" style="color:#1d4ed8;"></i>
                    </div>
                    <div>
                        <div style="font-weight:800;font-size:.9rem;color:#1e293b;">Datos del Estudiante</div>
                        <div style="font-size:11.5px;color:#94a3b8;">Información personal y de sección</div>
                    </div>
                </div>
                <div class="form-sec-body">

                    <div class="fg">
                        <label class="fl">Apellidos <span class="req">*</span></label>
                        <input type="text" name="apellidos" class="fi"
                               value="{{ old('apellidos', $participante->apellidos ?? '') }}"
                               placeholder="GARCIA GARCIA" required
                               style="text-transform:uppercase;"
                               oninput="this.value=this.value.toUpperCase()">
                    </div>
                    <div class="fg">
                        <label class="fl">Nombres <span class="req">*</span></label>
                        <input type="text" name="nombres" class="fi"
                               value="{{ old('nombres', $participante->nombres ?? '') }}"
                               placeholder="Juan Carlos" required>
                    </div>

                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                        <div class="fg">
                            <label class="fl">Nivel educativo</label>
                            <select name="nivel" class="fi fc-select">
                                <option value="">—</option>
                                @foreach(['Primaria','Secundaria'] as $n)
                                <option value="{{ $n }}" {{ old('nivel', $participante->nivel ?? $concurso->nivel_educativo ?? '') === $n ? 'selected' : '' }}>{{ $n }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="fg">
                            <label class="fl">Grado</label>
                            <input type="text" name="grado" class="fi"
                                   value="{{ old('grado', $participante->grado ?? $concurso->grado ?? '') }}"
                                   placeholder="2°" maxlength="20">
                        </div>
                        <div class="fg">
                            <label class="fl">Sección</label>
                            <input type="text" name="seccion" class="fi"
                                   value="{{ old('seccion', $participante->seccion ?? '') }}"
                                   placeholder="A" maxlength="10"
                                   style="text-transform:uppercase;"
                                   oninput="this.value=this.value.toUpperCase()">
                        </div>
                    </div>

                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                        <div class="fg">
                            <label class="fl">Género</label>
                            <select name="genero" class="fi fc-select">
                                <option value="">— No especificado —</option>
                                <option value="F" {{ old('genero', $participante->genero ?? '') === 'F' ? 'selected' : '' }}>♀ Femenino</option>
                                <option value="M" {{ old('genero', $participante->genero ?? '') === 'M' ? 'selected' : '' }}>♂ Masculino</option>
                            </select>
                        </div>
                        <div class="fg">
                            <label class="fl">Tiempo de entrega</label>
                            <input type="time" name="tiempo" step="1" class="fi"
                                   value="{{ old('tiempo', isset($participante) ? substr($participante->tiempo ?? '', 0, 5) : '') }}">
                        </div>
                    </div>

                    <div class="fg" style="margin-bottom:0;">
                        <label class="fl">Observación</label>
                        <textarea name="observacion" class="fi" rows="2"
                                  placeholder="Ej: Entregó a tiempo, Descalificado, etc.">{{ old('observacion', $participante->observacion ?? '') }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        {{-- ══════ RESPUESTAS ══════ --}}
        <div>
            <div class="form-sec">
                <div class="form-sec-hdr">
                    <div class="sec-icon" style="background:#f0fdf4;">
                        <i class="bi bi-pencil-square" style="color:#059669;font-size:17px;"></i>
                    </div>
                    <div style="flex:1;">
                        <div style="font-weight:800;font-size:.9rem;color:#1e293b;">Respuestas del Alumno</div>
                        <div style="font-size:11.5px;color:#94a3b8;">Compara con la respuesta correcta</div>
                    </div>
                    <div style="font-size:11px;color:#059669;background:#f0fdf4;border:1px solid #bbf7d0;padding:3px 10px;border-radius:50px;font-weight:800;">
                        {{ $concurso->num_preguntas }} preguntas
                    </div>
                </div>

                <div style="overflow-y:auto;max-height:480px;">
                    <table class="resp-tbl">
                        <thead>
                            <tr>
                                <th>Preg.</th>
                                <th>Correcta</th>
                                <th style="text-align:left;">Respuesta del Alumno</th>
                            </tr>
                        </thead>
                        <tbody>
                            @for($i = 1; $i <= $concurso->num_preguntas; $i++)
                            @php
                                $preg     = $concurso->preguntas->firstWhere('numero', $i);
                                $respPrev = isset($respuestasIndexed) ? $respuestasIndexed->get($i) : null;
                                $pts      = $preg ? ($preg->puntos ?? $concurso->puntos_por_pregunta) : $concurso->puntos_por_pregunta;
                            @endphp
                            <tr>
                                <td>
                                    <span class="resp-num-badge">P{{ $i }}</span>
                                </td>
                                <td>
                                    <span class="resp-correcta">{{ $preg->respuesta_correcta ?? '?' }}</span>
                                    <div class="resp-pts">{{ $pts }} pts</div>
                                </td>
                                <td>
                                    <input type="text"
                                           name="respuesta[{{ $i }}]"
                                           class="resp-input"
                                           value="{{ old("respuesta.$i", $respPrev->respuesta_alumno ?? '') }}"
                                           placeholder="Dejar vacío = no respondió"
                                           data-correcta="{{ $preg->respuesta_correcta ?? '' }}">
                                </td>
                            </tr>
                            @endfor
                        </tbody>
                    </table>
                </div>

                <div style="padding:12px 20px;border-top:1.5px solid #f1f5f9;background:#fafbfe;">
                    <div style="display:flex;align-items:center;gap:8px;font-size:11.5px;color:#7c3aed;background:#f5f3ff;padding:8px 12px;border-radius:8px;">
                        <i class="bi bi-lightbulb-fill"></i>
                        Deja vacío si el alumno no respondió. Las notas se calculan automáticamente al guardar.
                    </div>
                </div>
            </div>
        </div>

    </div>

    {{-- ═══════ ACTION BAR ═══════ --}}
    <div class="action-bar">
        <a href="{{ route('admin.concursos.participantes.index', $concurso) }}" class="btn-cancel">
            <i class="bi bi-x-circle"></i> Cancelar
        </a>
        <button type="submit" class="btn-save">
            <i class="bi bi-save-fill"></i>
            {{ isset($participante) ? 'Actualizar Participante' : 'Agregar Participante' }}
        </button>
    </div>

</form>

<style>
@media(max-width:900px) { .part-grid { grid-template-columns:1fr !important; } }
</style>

@endsection

@section('scripts')
<script>
// Resaltar en tiempo real si coincide con la correcta
document.querySelectorAll('.resp-input').forEach(input => {
    input.addEventListener('input', function() {
        const correcta = this.dataset.correcta.trim().toLowerCase();
        const alumno   = this.value.trim().toLowerCase();
        this.classList.remove('is-valid', 'is-invalid');
        if (alumno === '') return;
        if (alumno === correcta) this.classList.add('is-valid');
        else                     this.classList.add('is-invalid');
    });
    // Al cargar (modo edición)
    input.dispatchEvent(new Event('input'));
});
</script>
@endsection
