@extends('admin.layout')

@section('title', 'Clubes - 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">Gestión de Afiliados</span>
            <h1 class="display-4 fw-bold font-header mb-0">Clubes<span class="text-primary">.</span></h1>
        </div>
        <a href="{{ route('admin.clubes.create') }}" class="btn-admin-primary">
            <i class="bi bi-plus-lg me-2"></i> NUEVO CLUB
        </a>
    </div>

    <div class="row g-3 align-items-center">
        <div class="col-lg-6">
            <form method="GET" action="{{ route('admin.clubes.index') }}" class="search-box-kinetic" id="clubes-search-form">
                <i class="bi bi-search"></i>
                <input type="text" name="q" id="clubes-search-input" class="form-control" placeholder="Buscar club por nombre..." value="{{ $search ?? '' }}" autocomplete="off">
            </form>
        </div>
    </div>
</div>

<div id="clubes-list-container">
<div class="admin-card">
    @if($clubes->isEmpty())
        <div class="text-center py-5">
            <i class="bi bi-shield text-muted mb-3" style="font-size: 3rem;"></i>
            <p class="fs-5 text-muted">{{ !empty($search) ? 'No se encontraron clubes para "' . $search . '"' : 'No hay clubes registrados.' }}</p>
        </div>
    @else
        <div class="table-responsive">
            <table class="kinetic-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Club</th>
                        <th>Equipos</th>
                        <th>Jugadores</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($clubes as $club)
                    <tr>
                        <td><span class="badge bg-light text-dark px-2 py-1">#{{ $club->id_club }}</span></td>
                        <td>
                            <div class="d-flex align-items-center gap-3">
                                @if($club->imagen)
                                    <img src="{{ asset($club->imagen) }}" alt="{{ $club->nombre }}" style="width: 40px; height: 40px; object-fit: contain;">
                                @else
                                    <div class="bg-light d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="bi bi-shield-shaded text-muted"></i>
                                    </div>
                                @endif
                                <span class="fw-bold fs-5">{{ $club->nombre }}</span>
                            </div>
                        </td>
                        <td>
                            <span class="fw-bold text-primary">{{ $club->equipos_count }}</span>
                            <span class="small text-muted text-uppercase ms-1">Equipos</span>
                        </td>
                        <td>
                            <span class="fw-bold text-success">{{ $club->jugadores_count }}</span>
                            <span class="small text-muted text-uppercase ms-1">Jugadores</span>
                        </td>
                        <td class="text-end">
                            <a href="{{ route('admin.clubes.edit', $club->id_club) }}" class="btn btn-sm btn-light fw-bold text-uppercase border me-2">
                                <i class="bi bi-pencil me-1"></i> Editar
                            </a>
                            <form action="{{ route('admin.clubes.destroy', $club->id_club) }}" method="POST" class="d-inline delete-form confirm-submit" data-confirm-text="¿Eliminar este club?">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-sm btn-outline-danger fw-bold text-uppercase">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @endif
</div>
</div>
@endsection

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

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

    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)) : '');
        history.replaceState(null, '', url);

        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('clubes-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
