@extends('admin.layouts.app')
@section('title', 'Concursos / Resultados')
@section('icon', 'award-fill')
@section('page-title', 'Olimpiadas & Concursos')

@section('styles')
<style>
/* ── Variables ── */
:root {
    --c-gold:   #f59e0b;
    --c-blue:   #1a237e;
    --c-purple: #7c3aed;
    --c-green:  #059669;
    --c-red:    #dc2626;
}

/* ── Header Banner ── */
.concurso-hero {
    background: linear-gradient(135deg, #0d1b6e 0%, #1a237e 40%, #4527a0 100%);
    border-radius: 20px;
    padding: 28px 32px;
    margin-bottom: 28px;
    position: relative;
    overflow: hidden;
}
.concurso-hero::before {
    content: '';
    position: absolute;
    top: -40px; right: -40px;
    width: 220px; height: 220px;
    border-radius: 50%;
    background: rgba(255,255,255,.05);
}
.concurso-hero::after {
    content: '';
    position: absolute;
    bottom: -60px; left: 30%;
    width: 280px; height: 280px;
    border-radius: 50%;
    background: rgba(255,255,255,.03);
}
.hero-title {
    font-size: 1.75rem;
    font-weight: 800;
    color: #fff;
    margin: 0 0 4px;
    letter-spacing: -.5px;
}
.hero-sub {
    color: rgba(255,255,255,.65);
    font-size: .9rem;
    margin: 0;
}
.hero-icon {
    width: 56px; height: 56px;
    border-radius: 16px;
    background: rgba(255,224,130,.15);
    display: flex; align-items: center; justify-content: center;
    border: 2px solid rgba(255,224,130,.25);
}

/* ── Stat Cards ── */
.stat-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}
@media(max-width:900px) { .stat-grid { grid-template-columns: repeat(2,1fr); } }
@media(max-width:500px) { .stat-grid { grid-template-columns: 1fr; } }

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 18px 20px;
    border: 1.5px solid #f1f5f9;
    display: flex; align-items: center; gap: 14px;
    box-shadow: 0 2px 12px rgba(0,0,0,.05);
    transition: transform .2s, box-shadow .2s;
}
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 28px rgba(0,0,0,.1); }
.stat-icon {
    width: 48px; height: 48px; border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 20px; flex-shrink: 0;
}
.stat-num { font-size: 1.7rem; font-weight: 800; line-height: 1; margin-bottom: 2px; }
.stat-lbl { font-size: .75rem; color: #94a3b8; font-weight: 600; text-transform: uppercase; letter-spacing: .5px; }

/* ── Concurso Cards ── */
.concurso-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 20px;
}
.cc {
    background: #fff;
    border-radius: 18px;
    border: 1.5px solid #e8edf5;
    overflow: hidden;
    box-shadow: 0 2px 16px rgba(0,0,0,.06);
    transition: transform .22s, box-shadow .22s;
    display: flex; flex-direction: column;
}
.cc:hover { transform: translateY(-4px); box-shadow: 0 12px 40px rgba(26,35,126,.13); }

.cc-header {
    padding: 18px 20px 14px;
    border-bottom: 1.5px solid #f1f5f9;
    position: relative;
    background: linear-gradient(135deg, #f8faff 0%, #fff 100%);
}
.cc-header-stripe {
    position: absolute; top: 0; left: 0; right: 0; height: 4px;
    border-radius: 18px 18px 0 0;
}
.cc-title {
    font-size: 1rem; font-weight: 800;
    color: #1e293b; margin: 0 0 6px;
    line-height: 1.3;
    padding-right: 70px;
}
.cc-badge-row { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 8px; }
.cc-badge {
    padding: 3px 10px;
    border-radius: 50px;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: .3px;
}
.cc-status-pill {
    position: absolute; top: 16px; right: 16px;
    padding: 4px 12px; border-radius: 50px;
    font-size: 11px; font-weight: 800;
    letter-spacing: .5px; display: flex; align-items: center; gap: 4px;
}

.cc-body { padding: 16px 20px; flex: 1; }
.cc-info-row {
    display: flex; align-items: center; gap: 8px;
    font-size: .82rem; color: #64748b;
    margin-bottom: 8px;
}
.cc-info-row i { font-size: 14px; color: #94a3b8; }
.cc-info-row strong { color: #334155; }

.cc-participants {
    margin-top: 12px; padding: 10px 14px;
    background: #f8faff;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: space-between;
}
.cc-part-num { font-size: 1.4rem; font-weight: 800; color: #1a237e; }
.cc-part-lbl { font-size: .7rem; color: #94a3b8; font-weight: 600; text-transform: uppercase; }

.cc-footer {
    padding: 12px 20px;
    border-top: 1.5px solid #f1f5f9;
    display: flex; gap: 6px; flex-wrap: wrap;
    background: #fafbfe;
}
.cc-btn {
    flex: 1; min-width: 0;
    padding: 8px 6px;
    border-radius: 10px;
    border: 1.5px solid;
    font-size: 12px; font-weight: 700;
    cursor: pointer; text-align: center;
    display: flex; align-items: center; justify-content: center; gap: 4px;
    text-decoration: none; transition: all .18s; white-space: nowrap;
}
.cc-btn:hover { transform: translateY(-1px); }

/* ── Empty State ── */
.empty-state {
    text-align: center; padding: 64px 32px;
    background: #fff; border-radius: 20px;
    border: 2px dashed #e2e8f0;
}

/* ── Search bar ── */
.search-bar {
    background: #fff;
    border-radius: 14px;
    border: 1.5px solid #e2e8f0;
    padding: 10px 16px;
    display: flex; align-items: center; gap: 10px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,.04);
}
.search-bar input {
    border: none; outline: none; background: transparent;
    font-size: .9rem; flex: 1; color: #334155;
}
.search-bar i { color: #94a3b8; font-size: 16px; }

/* ── Alert ── */
.alert-custom {
    padding: 12px 18px; border-radius: 12px;
    display: flex; align-items: center; gap: 10px;
    margin-bottom: 18px; font-size: .88rem; font-weight: 600;
}
</style>
@endsection

@section('content')

{{-- ═══════ HERO BANNER ═══════ --}}
<div class="concurso-hero">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px;position:relative;z-index:1;">
        <div style="display:flex;align-items:center;gap:16px;">
            <div class="hero-icon">
                <i class="bi bi-award-fill" style="font-size:26px;color:#ffe082;"></i>
            </div>
            <div>
                <h1 class="hero-title">Olimpiadas &amp; Concursos</h1>
                <p class="hero-sub">ONEM · OHUNSA · Canguro Matemático y otras olimpiadas académicas</p>
            </div>
        </div>
        <a href="{{ route('admin.concursos.create') }}"
           style="display:inline-flex;align-items:center;gap:8px;padding:12px 22px;background:linear-gradient(135deg,#ffe082,#ffca28);color:#1a237e;font-weight:800;border-radius:14px;text-decoration:none;font-size:.9rem;box-shadow:0 4px 20px rgba(255,202,40,.35);transition:all .2s;"
           onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 8px 28px rgba(255,202,40,.5)'"
           onmouseout="this.style.transform='';this.style.boxShadow='0 4px 20px rgba(255,202,40,.35)'">
            <i class="bi bi-plus-circle-fill" style="font-size:16px;"></i>
            Nuevo Concurso
        </a>
    </div>
</div>

{{-- ═══════ ESTADÍSTICAS ═══════ --}}
@php
    $total       = $concursos->total();
    $publicados  = $concursos->getCollection()->where('estado','publicado')->count();
    $borradores  = $concursos->getCollection()->where('estado','borrador')->count();
    $totalParts  = $concursos->getCollection()->sum('participantes_count');
@endphp
<div class="stat-grid">
    <div class="stat-card">
        <div class="stat-icon" style="background:#eff6ff;">
            <i class="bi bi-collection-fill" style="color:#2563eb;"></i>
        </div>
        <div>
            <div class="stat-num" style="color:#1e40af;">{{ $total }}</div>
            <div class="stat-lbl">Total concursos</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:#f0fdf4;">
            <i class="bi bi-check-circle-fill" style="color:#16a34a;"></i>
        </div>
        <div>
            <div class="stat-num" style="color:#15803d;">{{ $publicados }}</div>
            <div class="stat-lbl">Publicados</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:#fffbeb;">
            <i class="bi bi-pencil-square" style="color:#d97706;"></i>
        </div>
        <div>
            <div class="stat-num" style="color:#b45309;">{{ $borradores }}</div>
            <div class="stat-lbl">Borradores</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:#fdf4ff;">
            <i class="bi bi-people-fill" style="color:#9333ea;"></i>
        </div>
        <div>
            <div class="stat-num" style="color:#7e22ce;">{{ $totalParts }}</div>
            <div class="stat-lbl">Participantes</div>
        </div>
    </div>
</div>

{{-- ═══════ BÚSQUEDA ═══════ --}}
<div class="search-bar">
    <i class="bi bi-search"></i>
    <input type="text" id="searchInput" placeholder="Buscar concurso por nombre, sigla, año..." oninput="filtrarConcursos()">
    <span id="resultCount" style="font-size:12px;color:#94a3b8;white-space:nowrap;"></span>
</div>

{{-- ═══════ GRID DE TARJETAS ═══════ --}}
@if($concursos->isEmpty())
<div class="empty-state">
    <div style="width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,#eff6ff,#dbeafe);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
        <i class="bi bi-trophy" style="font-size:36px;color:#3b82f6;"></i>
    </div>
    <h3 style="font-weight:800;color:#334155;margin-bottom:8px;">Sin concursos aún</h3>
    <p style="color:#94a3b8;margin-bottom:20px;">Registra el primer concurso para comenzar a gestionar resultados.</p>
    <a href="{{ route('admin.concursos.create') }}"
       style="display:inline-flex;align-items:center;gap:8px;padding:12px 24px;background:linear-gradient(135deg,#1a237e,#4527a0);color:#fff;border-radius:12px;text-decoration:none;font-weight:700;">
        <i class="bi bi-plus-circle-fill"></i> Crear primer concurso
    </a>
</div>
@else

<div class="concurso-grid" id="concursoGrid">
    @foreach($concursos as $c)
    @php
        $publicado = $c->estado === 'publicado';
        $stripeColor = $publicado ? '#059669' : '#f59e0b';
        $modoLabel = match($c->modo_clasificados ?? 'general') {
            'general' => 'General',
            'genero'  => 'Por Género',
            'ambos'   => 'General + Género',
            default   => ucfirst($c->modo_clasificados ?? ''),
        };
    @endphp
    <div class="cc" data-search="{{ strtolower($c->nombre . ' ' . $c->sigla . ' ' . $c->anio . ' ' . $c->grado) }}">

        {{-- Stripe de color + cabecera --}}
        <div class="cc-header">
            <div class="cc-header-stripe" style="background:linear-gradient(90deg,{{ $stripeColor }},{{ $publicado ? '#34d399' : '#fcd34d' }});"></div>

            {{-- Status pill --}}
            @if($publicado)
            <span class="cc-status-pill" style="background:#dcfce7;color:#15803d;">
                <i class="bi bi-broadcast-pin"></i> Publicado
            </span>
            @else
            <span class="cc-status-pill" style="background:#fef9c3;color:#92400e;">
                <i class="bi bi-pencil"></i> Borrador
            </span>
            @endif

            <h3 class="cc-title">{{ $c->nombre }}</h3>

            <div class="cc-badge-row">
                @if($c->sigla)
                <span class="cc-badge" style="background:#eff6ff;color:#1d4ed8;">{{ $c->sigla }}</span>
                @endif
                @if($c->anio)
                <span class="cc-badge" style="background:#f5f3ff;color:#6d28d9;">{{ $c->anio }}</span>
                @endif
                @if($c->grado)
                <span class="cc-badge" style="background:#fdf4ff;color:#86198f;">{{ $c->grado }}</span>
                @endif
                @if($c->categoria)
                <span class="cc-badge" style="background:#fff7ed;color:#c2410c;">Cat. {{ $c->categoria }}</span>
                @endif
            </div>
        </div>

        {{-- Cuerpo --}}
        <div class="cc-body">
            @if($c->etapa)
            <div class="cc-info-row">
                <i class="bi bi-layers"></i>
                <span>Etapa: <strong>{{ $c->etapa }}</strong></span>
            </div>
            @endif
            <div class="cc-info-row">
                <i class="bi bi-bar-chart"></i>
                <span>Clasificados: <strong>{{ $c->top_clasificados ?? 3 }} primeros</strong></span>
            </div>
            <div class="cc-info-row">
                <i class="bi bi-gender-ambiguous"></i>
                <span>Modo: <strong>{{ $modoLabel }}</strong></span>
            </div>
            @if($c->num_preguntas)
            <div class="cc-info-row">
                <i class="bi bi-patch-question"></i>
                <span>Preguntas: <strong>{{ $c->num_preguntas }}</strong></span>
            </div>
            @endif

            {{-- Participantes --}}
            <div class="cc-participants">
                <div>
                    <div class="cc-part-num">{{ $c->participantes_count }}</div>
                    <div class="cc-part-lbl">Participantes</div>
                </div>
                <a href="{{ route('admin.concursos.participantes.index', $c) }}"
                   style="display:inline-flex;align-items:center;gap:6px;padding:7px 14px;background:#1a237e;color:#fff;border-radius:10px;font-size:12px;font-weight:700;text-decoration:none;transition:opacity .2s;"
                   onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
                    <i class="bi bi-people-fill"></i> Ver todos
                </a>
            </div>

            {{-- Publicado: link público --}}
            @if($publicado && $c->slug)
            <a href="{{ route('resultado.show', $c->slug) }}" target="_blank"
               style="display:flex;align-items:center;gap:6px;margin-top:10px;padding:8px 12px;background:#f0fdf4;border:1.5px solid #bbf7d0;border-radius:10px;color:#15803d;font-size:12px;font-weight:700;text-decoration:none;transition:background .18s;"
               onmouseover="this.style.background='#dcfce7'" onmouseout="this.style.background='#f0fdf4'">
                <i class="bi bi-box-arrow-up-right"></i>
                Ver resultado público
                <i class="bi bi-arrow-right ms-auto"></i>
            </a>
            @endif
        </div>

        {{-- Footer acciones --}}
        <div class="cc-footer">
            {{-- Participantes --}}
            <a href="{{ route('admin.concursos.participantes.index', $c) }}"
               class="cc-btn" style="color:#475569;border-color:#e2e8f0;background:#fff;"
               title="Gestionar participantes">
                <i class="bi bi-people-fill"></i> Participantes
            </a>
            {{-- Editar --}}
            <a href="{{ route('admin.concursos.edit', $c) }}"
               class="cc-btn" style="color:#1d4ed8;border-color:#bfdbfe;background:#eff6ff;"
               title="Editar concurso">
                <i class="bi bi-pencil-fill"></i> Editar
            </a>
            {{-- Publicar / Re-publicar --}}
            @if(!$publicado)
            <a href="{{ route('admin.concursos.publicar', $c) }}"
               class="cc-btn" style="color:#15803d;border-color:#bbf7d0;background:#f0fdf4;"
               title="Publicar en noticias"
               onclick="return confirm('¿Publicar este resultado en la sección de noticias?')">
                <i class="bi bi-megaphone-fill"></i> Publicar
            </a>
            @else
            <a href="{{ route('admin.concursos.publicar', $c) }}"
               class="cc-btn" style="color:#92400e;border-color:#fde68a;background:#fffbeb;"
               title="Re-publicar"
               onclick="return confirm('Ya está publicado. ¿Crear una actualización?')">
                <i class="bi bi-arrow-repeat"></i> Re-pub.
            </a>
            @endif
            {{-- Eliminar --}}
            <form action="{{ route('admin.concursos.destroy', $c) }}" method="POST" style="flex:0;"
                  onsubmit="return confirm('¿Eliminar este concurso y TODOS sus datos?\n\nEsta acción es irreversible.')">
                @csrf @method('DELETE')
                <button type="submit" class="cc-btn" style="color:#dc2626;border-color:#fecaca;background:#fef2f2;width:40px;" title="Eliminar">
                    <i class="bi bi-trash3-fill"></i>
                </button>
            </form>
        </div>
    </div>
    @endforeach
</div>

{{-- Paginación --}}
@if($concursos->hasPages())
<div style="margin-top:24px;display:flex;justify-content:center;">
    {{ $concursos->links() }}
</div>
@endif

@endif
@endsection

@section('scripts')
<script>
function filtrarConcursos() {
    const q     = document.getElementById('searchInput').value.toLowerCase().trim();
    const cards = document.querySelectorAll('#concursoGrid .cc');
    let visible = 0;

    cards.forEach(card => {
        const text = card.dataset.search || '';
        const show = q === '' || text.includes(q);
        card.style.display = show ? '' : 'none';
        if (show) visible++;
    });

    const rc = document.getElementById('resultCount');
    if (rc) rc.textContent = q ? `${visible} resultado${visible !== 1 ? 's' : ''}` : '';
}
</script>
@endsection
