@extends('layouts.dashboard')

@section('title', __('Eventos'))

@section('content')
    @include('dashboard.partials.bootstrap-table-assets')

    <div class="rt-events-hub mb-4">
        <div class="d-flex flex-wrap align-items-start justify-content-between rt-flex-gap-3 mb-3">
            <div>
                <h1 class="h3 mb-1 text-gray-800 font-weight-bold">{{ __('Tus eventos') }}</h1>
            </div>
            @can('create', \App\Models\Event::class)
                <a href="{{ route('dashboard.events.create') }}" class="btn rt-btn-cherry btn-sm px-3 shadow-sm flex-shrink-0">
                    <i class="bi bi-plus-lg mr-1" aria-hidden="true"></i> {{ __('Nuevo evento') }}
                </a>
            @endcan
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-primary shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">{{ __('Total') }}</div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800">{{ number_format($stats['total']) }}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-success shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">{{ __('Publicados') }}</div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800">{{ number_format($stats['published']) }}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-warning shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{ __('Borrador / revisión') }}</div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800">{{ number_format($stats['in_progress']) }}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-info shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">{{ __('Próximos publicados') }}</div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800">{{ number_format($stats['upcoming_published']) }}</div>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex flex-wrap align-items-center rt-flex-gap-2 mb-3">
        <span class="small font-weight-bold text-muted text-uppercase mr-1">{{ __('Filtrar:') }}</span>
        <a href="{{ route('dashboard.events.index', ['status' => 'all']) }}" class="btn btn-sm {{ $statusFilter === 'all' ? 'rt-btn-cherry' : 'btn-outline-secondary' }}">{{ __('Todos') }}</a>
        <a href="{{ route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Published->value]) }}" class="btn btn-sm {{ $statusFilter === \App\Enums\EventStatus::Published->value ? 'rt-btn-cherry' : 'btn-outline-secondary' }}">{{ __('Publicados') }}</a>
        <a href="{{ route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Pending->value]) }}" class="btn btn-sm {{ $statusFilter === \App\Enums\EventStatus::Pending->value ? 'rt-btn-cherry' : 'btn-outline-secondary' }}">{{ __('Pendientes') }}</a>
        <a href="{{ route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Draft->value]) }}" class="btn btn-sm {{ $statusFilter === \App\Enums\EventStatus::Draft->value ? 'rt-btn-cherry' : 'btn-outline-secondary' }}">{{ __('Borradores') }}</a>
        <a href="{{ route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Cancelled->value]) }}" class="btn btn-sm {{ $statusFilter === \App\Enums\EventStatus::Cancelled->value ? 'rt-btn-cherry' : 'btn-outline-secondary' }}">{{ __('Cancelados') }}</a>
    </div>

    <div class="card shadow mb-4 rt-events-table-card">
        <div class="card-header py-3 d-flex flex-wrap align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">{{ __('Listado') }}</h6>
            <span class="small text-muted">{{ __('Orden: fecha de inicio más reciente') }}</span>
        </div>
        <div class="card-body p-0">
            @if ($events->isEmpty())
                <div class="rt-empty-events p-5 text-center">
                    <div class="rt-empty-events__icon mb-3 mx-auto d-flex align-items-center justify-content-center rounded-circle bg-light border">
                        <i class="bi bi-calendar-event text-muted" style="font-size: 2rem" aria-hidden="true"></i>
                    </div>
                    <h2 class="h5 font-weight-bold text-gray-800">{{ __('Aún no tienes eventos') }}</h2>
                    <p class="text-muted small col-md-8 mx-auto mb-4">
                        {{ __('Crea tu primer evento: podrás definir distancias para carreras, tipos de entrada y más adelante BIB y resultados al estilo de las mejores plataformas de la región.') }}
                    </p>
                    @can('create', \App\Models\Event::class)
                        <a href="{{ route('dashboard.events.create') }}" class="btn rt-btn-cherry px-4">{{ __('Crear mi primer evento') }}</a>
                    @endcan
                </div>
            @else
                <div class="table-responsive">
                    <table class="table table-hover mb-0 rt-events-wp-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width:220px">{{ __('Título') }}</th>
                                <th style="min-width:120px">{{ __('Autor') }}</th>
                                <th class="text-center" style="min-width:100px">{{ __('Asistentes') }}</th>
                                <th style="min-width:80px">{{ __('Distancias') }}</th>
                                <th style="min-width:110px">{{ __('Fecha de inicio') }}</th>
                                <th style="min-width:110px">{{ __('Fecha de fin') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($events as $ev)
                                @php
                                    $sport   = is_array($ev->metadata) ? ($ev->metadata['sport'] ?? []) : [];
                                    $distances = isset($sport['distances']) && is_array($sport['distances']) ? $sport['distances'] : [];

                                    // Capacity & attendee %
                                    $totalCapacity = $ev->ticketTypes->sum(function ($tt) {
                                        return match ($tt->capacity_strategy->value) {
                                            'unlimited' => 0,
                                            'shared_pool' => $tt->shared_pool_size ?? 0,
                                            default      => $tt->capacity ?? 0,
                                        };
                                    });
                                    $attendeesCount = $ev->attendees_count ?? 0;
                                    $pct = ($totalCapacity > 0)
                                        ? min(100, (int) round(($attendeesCount / $totalCapacity) * 100))
                                        : null;

                                    $authorName  = $ev->organizer?->user?->name ?? '—';
                                    $isPublished = $ev->status === \App\Enums\EventStatus::Published;
                                    $isDraft     = in_array($ev->status, [\App\Enums\EventStatus::Draft, \App\Enums\EventStatus::Pending], true);
                                    $isArchived  = $ev->trashed();
                                    $isCancelled = $ev->status === \App\Enums\EventStatus::Cancelled;
                                @endphp
                                <tr class="rt-ev-row {{ $isArchived ? 'table-secondary' : '' }}" id="rt-ev-{{ $ev->id }}">
                                    {{-- TÍTULO + STATUS + ACCIONES --}}
                                    <td>
                                        <div class="d-flex align-items-center mb-1 rt-flex-gap-2">
                                            @if ($isArchived)
                                                <span class="badge badge-dark rt-badge-xs">{{ __('Archivado') }}</span>
                                            @else
                                                @switch($ev->status)
                                                    @case(\App\Enums\EventStatus::Published)
                                                        <span class="badge badge-success rt-badge-xs">{{ __('Publicado') }}</span>
                                                        @break
                                                    @case(\App\Enums\EventStatus::Pending)
                                                        <span class="badge badge-warning text-dark rt-badge-xs">{{ __('En revisión') }}</span>
                                                        @break
                                                    @case(\App\Enums\EventStatus::Draft)
                                                        <span class="badge badge-secondary rt-badge-xs">{{ __('Borrador') }}</span>
                                                        @break
                                                    @case(\App\Enums\EventStatus::Cancelled)
                                                        <span class="badge badge-danger rt-badge-xs">{{ __('Cancelado') }}</span>
                                                        @break
                                                @endswitch
                                            @endif
                                            @if ($ev->is_featured)
                                                <span class="badge badge-light border rt-badge-xs" title="{{ __('Destacado') }}"><i class="bi bi-star-fill text-warning small" aria-hidden="true"></i></span>
                                            @endif
                                        </div>

                                        <strong class="d-block text-gray-900 rt-ev-title">{{ $ev->title }}</strong>
                                        <div class="small text-muted mb-1">{{ $ev->venue?->name }}</div>

                                        {{-- ACCIONES estilo WordPress --}}
                                        <div class="rt-ev-actions">
                                            @if ($isArchived)
                                                @can('restore', $ev)
                                                    <form action="{{ route('dashboard.events.restore', $ev->id) }}" method="post" class="d-inline mr-1">
                                                        @csrf
                                                        <button type="submit" class="rt-ev-action btn-reset text-success font-weight-bold">{{ __('Activar') }}</button>
                                                    </form>
                                                    <span class="rt-ev-sep">|</span>
                                                @endcan
                                                @can('update', $ev)
                                                    <a href="{{ route('dashboard.events.edit', $ev) }}" class="rt-ev-action">{{ __('Editar') }}</a>
                                                @endcan
                                            @else
                                                @can('update', $ev)
                                                    <a href="{{ route('dashboard.events.edit', $ev) }}" class="rt-ev-action">{{ __('Editar') }}</a>
                                                    <span class="rt-ev-sep">|</span>
                                                @endcan

                                                @if ($isPublished)
                                                    <a href="{{ route('landing.event.show', $ev->slug) }}" target="_blank" class="rt-ev-action">{{ __('Ver') }}</a>
                                                    <span class="rt-ev-sep">|</span>
                                                @elseif ($isDraft)
                                                    <a href="{{ route('landing.event.show', $ev->slug) }}" target="_blank" class="rt-ev-action text-muted">{{ __('Vista previa') }}</a>
                                                    <span class="rt-ev-sep">|</span>
                                                @endif

                                                @can('view', $ev)
                                                    <a href="{{ route('dashboard.events.attendees.index', $ev) }}" class="rt-ev-action">{{ __('Asistentes / Check-in') }}</a>
                                                    <span class="rt-ev-sep">|</span>
                                                @endcan
                                                @can('update', $ev)
                                                    <a href="{{ route('dashboard.events.edit', $ev) }}#qr" class="rt-ev-action">{{ __('Generar QR') }}</a>
                                                    <span class="rt-ev-sep">|</span>
                                                @endcan

                                                @can('cancel', $ev)
                                                    @if (! $isCancelled)
                                                        <form action="{{ route('dashboard.events.cancel', $ev) }}" method="post" class="d-inline rt-ev-cancel-form mr-1">
                                                            @csrf
                                                            <button type="submit" class="rt-ev-action btn-reset text-warning">{{ __('Desactivar') }}</button>
                                                        </form>
                                                        <span class="rt-ev-sep">|</span>
                                                    @endif
                                                @endcan

                                                @can('delete', $ev)
                                                    <form action="{{ route('dashboard.events.destroy', $ev) }}" method="post" class="d-inline rt-ev-delete-form">
                                                        @csrf
                                                        @method('DELETE')
                                                        <button type="submit" class="rt-ev-action rt-ev-action--danger btn-reset">{{ __('Eliminar') }}</button>
                                                    </form>
                                                @endcan
                                            @endif
                                        </div>
                                    </td>

                                    {{-- AUTOR --}}
                                    <td>
                                        <span class="small text-gray-800">{{ $authorName }}</span>
                                    </td>

                                    {{-- ASISTENTES + % --}}
                                    <td class="text-center">
                                        @if ($attendeesCount > 0 || $totalCapacity > 0)
                                            <strong class="d-block text-gray-800">{{ number_format($attendeesCount) }}</strong>
                                            @if ($pct !== null)
                                                <div class="rt-capacity-bar mt-1" title="{{ $attendeesCount }}/{{ $totalCapacity }}">
                                                    <div class="rt-capacity-bar__fill @if($pct >= 90) rt-capacity-bar__fill--danger @elseif($pct >= 70) rt-capacity-bar__fill--warn @endif"
                                                         style="width:{{ $pct }}%"></div>
                                                </div>
                                                <span class="text-muted small">({{ $pct }}%)</span>
                                            @endif
                                        @else
                                            <span class="text-muted">—</span>
                                        @endif
                                    </td>

                                    {{-- DISTANCIAS --}}
                                    <td>
                                        @if (! empty($sport['enabled']) && count($distances) > 0)
                                            <div class="d-flex flex-wrap rt-flex-gap-1">
                                                @foreach (array_slice($distances, 0, 4) as $d)
                                                    <span class="badge badge-light border text-dark font-weight-normal">{{ $d }}</span>
                                                @endforeach
                                                @if (count($distances) > 4)
                                                    <span class="badge badge-secondary">+{{ count($distances) - 4 }}</span>
                                                @endif
                                            </div>
                                        @else
                                            <span class="text-muted small">—</span>
                                        @endif
                                    </td>

                                    {{-- FECHA INICIO --}}
                                    <td>
                                        <span class="small">{{ $ev->start_date->timezone($ev->timezone)->format('d/m/Y') }}</span>
                                        <span class="d-block text-muted" style="font-size:.75rem">{{ $ev->start_date->timezone($ev->timezone)->format('H:i') }}</span>
                                    </td>

                                    {{-- FECHA FIN --}}
                                    <td>
                                        <span class="small">{{ $ev->end_date->timezone($ev->timezone)->format('d/m/Y') }}</span>
                                        <span class="d-block text-muted" style="font-size:.75rem">{{ $ev->end_date->timezone($ev->timezone)->format('H:i') }}</span>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        </div>
        @if ($events->hasPages())
            <div class="card-footer">{{ $events->links() }}</div>
        @endif
    </div>

    @push('scripts')
        <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.rt-ev-cancel-form').forEach(function (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'question',
                            title: @json(__('¿Desactivar (cancelar) este evento?')),
                            text: @json(__('Seguirá en la base de datos; el público verá el estado cancelado según tu página.')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, cancelar')),
                            cancelButtonText: @json(__('No')),
                            confirmButtonColor: '#f6993f',
                        }).then(function (r) {
                            if (r.isConfirmed) {
                                form.submit();
                            }
                        });
                    } else if (confirm(@json(__('¿Marcar este evento como cancelado?')))) {
                        form.submit();
                    }
                });
            });
            document.querySelectorAll('.rt-ev-delete-form').forEach(function (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    if (typeof Swal !== 'undefined' && typeof rtSwalCrud !== 'undefined') {
                        rtSwalCrud
                            .confirmDelete(
                                @json(__('Se archivará el evento; órdenes y asistentes permanecen en la base de datos.')),
                                @json(__('¿Archivar este evento?'))
                            )
                            .then(function (r) {
                                if (r.isConfirmed) {
                                    form.submit();
                                }
                            });
                    } else if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'warning',
                            title: @json(__('¿Archivar este evento?')),
                            text: @json(__('Se conservan ventas y asistentes para informes; puedes reactivarlo desde el listado.')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, eliminar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#b91830',
                        }).then(function (r) {
                            if (r.isConfirmed) {
                                form.submit();
                            }
                        });
                    } else {
                        if (confirm(@json(__('¿Archivar este evento? Los datos históricos se conservan.')))) { form.submit(); }
                    }
                });
            });
        });
        </script>
    @endpush
@endsection
