import { getSpinner } from '../../utils/helpers.js';

export function initClubsSection($container) {
    $container.html(getSpinner());
    loadClubs($container);
}

function loadClubs($container) {
    $.ajax({
        url: '/api/clubs',
        type: 'GET',
        success: (clubs) => {
            $container.empty();
            if (!clubs || clubs.length === 0) {
                $container.html(buildEmpty());
                return;
            }
            const $row = $('<div class="row g-4"></div>');
            clubs.forEach(c => $row.append(buildClubCard(c)));
            $container.append($row);
        },
        error: () => $container.html('<div class="alert alert-danger">Ошибка загрузки клубов</div>')
    });
}

function buildClubCard(club) {
    const img = club.images && club.images.length > 0
        ? club.images[0]
        : 'https://placehold.co/400x200/2ecc71/ffffff?text=Теннис';

    const courtCount = club.courtUuids ? club.courtUuids.length : 0;
    const courtBadge = courtCount > 0
        ? `<span class="badge rounded-pill" style="background:#e8f8ef;color:#1a7a4a;font-size:0.75rem;font-weight:600">
               <i class="bi bi-grid me-1"></i>${courtCount} ${courtCount === 1 ? 'корт' : courtCount < 5 ? 'корта' : 'кортов'} · аренда
           </span>`
        : '';

    return $(`
        <div class="col-12 col-lg-4">
            <div class="card card-hover club-card h-100">
                <img src="${img}" class="card-img-top" style="height:200px;object-fit:cover" alt="${club.name}">
                <div class="card-body">
                    <h5 class="card-title fw-bold">${club.name}</h5>
                    ${club.address ? `<p class="text-muted small mb-2"><i class="bi bi-geo-alt me-1"></i>${club.address}</p>` : ''}
                    <p class="card-text text-muted small">${club.description || 'Описание отсутствует'}</p>
                    ${courtBadge}
                </div>
                <div class="card-footer bg-transparent d-flex justify-content-between align-items-center">
                    ${club.phone ? `<span class="small text-muted"><i class="bi bi-telephone me-1"></i>${club.phone}</span>` : '<span></span>'}
                    <a href="/clubs/${club.uuid}" class="btn btn-sm btn-tennis-green">Подробнее</a>
                </div>
            </div>
        </div>
    `);
}

function buildEmpty() {
    return `<div class="col-12 text-center py-5 text-muted">
        <i class="bi bi-building fs-1 d-block mb-3"></i>
        <p>Клубов пока нет</p>
    </div>`;
}
