@extends('admin.layout')

@section('title', 'Jugadores - Admin OnAPB')

@section('content')
<div class="mb-5">
    <div class="d-flex justify-content-between align-items-end mb-4">
        <div>
            <span class="text-primary fw-bold text-uppercase tracking-widest d-block mb-2">Base de Datos Deportiva</span>
            <h1 class="display-4 fw-bold font-header mb-0">Jugadores<span class="text-primary">.</span></h1>
        </div>
        <a href="{{ route('admin.jugadores.create') }}" class="btn-admin-primary">
            <i class="bi bi-person-plus me-2"></i> NUEVO JUGADOR
        </a>
    </div>

    <!-- Search & Tools Row -->
    <div class="row g-3 align-items-center">
        <div class="col-lg-6">
            <form method="GET" action="{{ route('admin.jugadores.index') }}" class="search-box-kinetic" id="jugadores-search-form">
                <i class="bi bi-search"></i>
                <input type="text" name="q" id="jugadores-search-input" class="form-control" placeholder="Buscar por nombre, apellido o DNI..." value="{{ $search ?? '' }}" autocomplete="off">
            </form>
        </div>
        <div class="col-lg-6 d-flex justify-content-lg-end gap-2">
            @if(session('admin_role') == 1 || session('admin_role') == 2)
            <div class="dropdown">
                <button class="btn btn-outline-dark fw-bold text-uppercase dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-file-earmark-arrow-up me-1"></i> Herramientas CSV
                </button>
                <div class="dropdown-menu dropdown-menu-end p-3" style="width: 300px; border-radius: 0; border: 2px solid #000;">
                    <form action="{{ route('admin.jugadores.import') }}" method="POST" enctype="multipart/form-data" id="importForm" class="mb-3">
                        @csrf
                        <label class="form-label small fw-bold text-uppercase">Importar Plantel</label>
                        
                        @if(session('admin_role') == 1)
                            <select name="id_club" class="form-select form-select-sm mb-2" required>
                                <option value="" selected disabled>Seleccionar Club...</option>
                                <option value="99">ID 99 (General)</option>
                                @foreach($clubes as $c)
                                    <option value="{{ $c->id_club }}">{{ $c->nombre }} (ID: {{ $c->id_club }})</option>
                                @endforeach
                            </select>
                        @endif

                        <input type="file" name="csv_file" class="form-control form-control-sm mb-2" accept=".csv,.txt">
                        <button type="submit" class="btn btn-dark btn-sm w-100 fw-bold text-uppercase">Subir CSV</button>
                    </form>
                    <hr>
                    <a href="{{ route('admin.jugadores.export') }}" class="btn btn-outline-success btn-sm w-100 fw-bold text-uppercase">
                        <i class="bi bi-file-earmark-arrow-down me-1"></i> Exportar Base Completa
                    </a>
                    <div class="mt-2 text-muted" style="font-size: 0.7rem;">
                        <strong>Formatos soportados:</strong><br>
                        - GES CAB (Confederación Argentina de Basquetbol)<br>
                        - Formato Interno OnAPB<br>
                        - Legado: DNI; Apellido; Nombre; ddmmaaaa; id_club
                    </div>
                </div>
            </div>
            @endif
        </div>
    </div>
</div>

<div id="jugadores-list-container">
<div class="admin-card">
    @if($jugadores->isEmpty())
        <div class="text-center py-5">
            <i class="bi bi-person-badge text-muted mb-3" style="font-size: 3rem;"></i>
            <p class="fs-5 text-muted">{{ $search ? 'No se encontraron resultados para "' . $search . '"' : 'No hay jugadores registrados.' }}</p>
        </div>
    @else
        <div class="table-responsive">
            <table class="kinetic-table">
                <thead>
                    <tr>
                        <th>Jugador</th>
                        <th>Documento</th>
                        <th>Categoría</th>
                        <th>Club Actual</th>
                        <th>Estado</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($jugadores as $j)
                    <tr>
                        <td>
                            <span class="fw-bold d-block">{{ $j->apellido }}, {{ $j->nombre }}</span>
                        </td>
                        <td><span class="text-muted fw-bold">{{ $j->documento }}</span></td>
                        <td><span class="badge bg-dark text-white text-uppercase px-2 py-1" style="font-size: 0.7rem;">{{ $j->categoria_calculada }}</span></td>
                        <td><span class="fw-bold">{{ $j->clubActual->nombre ?? '—' }}</span></td>
                        <td>
                            @if($j->activo)
                                <span class="badge bg-success text-uppercase px-2" style="font-size: 0.65rem;">Activo</span>
                            @else
                                <span class="badge bg-secondary text-uppercase px-2" style="font-size: 0.65rem;">Inactivo</span>
                            @endif
                        </td>
                        <td class="text-end">
                            <a href="{{ route('admin.jugadores.edit', $j->id_jugador) }}" class="btn btn-sm btn-light border me-1">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <form action="{{ route('admin.jugadores.destroy', $j->id_jugador) }}" method="POST" class="d-inline delete-form confirm-submit" data-confirm-text="¿Eliminar este jugador?">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <div class="mt-4 d-flex justify-content-center">
            {{ $jugadores->appends(['q' => $search])->links('pagination::bootstrap-5') }}
        </div>
    @endif
</div>
</div>
@endsection

@section('scripts')
<script>
(function () {
    const form      = document.getElementById('jugadores-search-form');
    const input     = document.getElementById('jugadores-search-input');
    const container = document.getElementById('jugadores-list-container');
    if (!form || !input || !container) return;

    let debounceTimer = null;
    let activeRequest = null;
    const baseUrl = form.getAttribute('action');

    // Evitar submit completo del form (recarga de página) al apretar Enter.
    form.addEventListener('submit', e => { e.preventDefault(); doSearch(input.value); });

    input.addEventListener('input', function () {
        clearTimeout(debounceTimer);
        const value = this.value;
        debounceTimer = setTimeout(() => doSearch(value), 350);
    });

    async function doSearch(query) {
        const url = baseUrl + (query ? ('?q=' + encodeURIComponent(query)) : '');
        // Mantener URL sincronizada para que recargas/back conserven el filtro.
        history.replaceState(null, '', url);

        // Cancelar request previa si el usuario sigue tipeando.
        if (activeRequest) activeRequest.abort();
        activeRequest = new AbortController();

        container.style.opacity = '0.55';

        try {
            const res = await fetch(url, {
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/html' },
                signal: activeRequest.signal
            });
            const html = await res.text();
            const doc = new DOMParser().parseFromString(html, 'text/html');
            const fresh = doc.getElementById('jugadores-list-container');
            if (fresh) {
                container.innerHTML = fresh.innerHTML;
            }
        } catch (err) {
            if (err.name !== 'AbortError') console.error('Búsqueda en vivo falló:', err);
        } finally {
            container.style.opacity = '';
            activeRequest = null;
        }
    }
})();
</script>
@endsection
