import { getSpinner, formatDate, formatTime, buildPagination, eventTypeLabel } from '../../utils/helpers.js';
import { openApplyModal } from './applyModal.js';

export function initEventsSection($container) {
    loadEvents($container, 0);
}

function loadEvents($container, page) {
    $container.html(getSpinner());

    $.ajax({
        url: `/api/events?page=${page}&size=9`,
        type: 'GET',
        success: (resp) => {
            $container.empty();
            if (!resp.content || resp.content.length === 0) {
                $container.html(buildEmpty());
                return;
            }
            const $row = $('<div class="row g-4"></div>');
            resp.content.forEach(e => {
                const $card = buildEventCard(e);
                $card.on('click', '.apply-btn', () => openApplyModal(e));
                $row.append($card);
            });
            $container.append($row);

            const $pag = buildPagination(resp, page, p => loadEvents($container, p));
            if ($pag) $container.append($pag);
        },
        error: () => $container.html('<div class="alert alert-danger">Ошибка загрузки мероприятий</div>')
    });
}

function buildEventCard(event) {
    const img = event.imageUrl || 'https://placehold.co/400x200/e67e22/ffffff?text=Мероприятие';
    const badgeClass = {
        TOURNAMENT: 'bg-danger',
        TRAINING: 'bg-success',
        LESSON: 'bg-primary',
        EXHIBITION: 'bg-warning text-dark',
        CAMP: 'bg-info text-dark'
    }[event.type] || 'bg-secondary';

    return $(`
        <div class="col-12 col-md-6 col-lg-4">
            <div class="card card-hover event-card h-100">
                <img src="${img}" class="card-img-top" style="height:200px;object-fit:cover" alt="${event.title}">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h5 class="card-title fw-bold mb-0">${event.title}</h5>
                        <span class="badge ${badgeClass} ms-2 flex-shrink-0">${eventTypeLabel(event.type)}</span>
                    </div>
                    ${event.clubName ? `<p class="text-muted small mb-1"><i class="bi bi-building me-1"></i>${event.clubName}</p>` : ''}
                    <p class="card-text text-muted small">${event.description || 'Описание отсутствует'}</p>
                </div>
                <div class="card-footer bg-transparent">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <span class="small text-muted">
                            <i class="bi bi-calendar me-1"></i>${formatDate(event.startDateTime)}
                            <i class="bi bi-clock ms-2 me-1"></i>${formatTime(event.startDateTime)}
                        </span>
                        ${event.takePartPrice != null
                            ? `<span class="fw-bold" style="color:var(--tennis-green)">${event.takePartPrice > 0 ? event.takePartPrice + ' ₽' : 'Бесплатно'}</span>`
                            : ''}
                    </div>
                    ${event.maxParticipants ? buildParticipantsBadge(event) : ''}
                    <div class="mt-2">
                        ${event.registrationOpen !== false
                            ? `<button class="apply-btn btn btn-sm fw-semibold w-100"
                                    style="background:var(--tennis-green);color:#fff;border:none;border-radius:8px">
                                   <i class="bi bi-send me-1"></i>Подать заявку
                               </button>`
                            : `<button class="btn btn-sm fw-semibold w-100 disabled" disabled
                                    style="background:#e9ecef;color:#6c757d;border:none;border-radius:8px;cursor:not-allowed">
                                   <i class="bi bi-lock me-1"></i>Приём заявок закрыт
                               </button>`
                        }
                    </div>
                </div>
            </div>
        </div>
    `);
}

function buildParticipantsBadge(event) {
    const current = event.currentParticipants || 0;
    const max = event.maxParticipants;
    let cls = 'text-muted';
    if (max && current > max)      cls = 'text-danger fw-semibold';
    else if (max && current >= max) cls = 'fw-semibold' + ' ' + 'text-warning';
    return `<div class="mt-1 small ${cls}">
        <i class="bi bi-people me-1"></i>${current} / ${max} участников
        ${current > max ? '<span class="ms-1">(мест нет)</span>' : ''}
    </div>`;
}

function buildEmpty() {
    return `<div class="col-12 text-center py-5 text-muted">
        <i class="bi bi-calendar-event fs-1 d-block mb-3"></i>
        <p>Мероприятий пока нет</p>
    </div>`;
}
