export function getSpinner() {
    return `<div class="text-center py-5">
        <div class="spinner-border text-success" role="status">
            <span class="visually-hidden">Загрузка...</span>
        </div>
    </div>`;
}

export function formatDate(dt) {
    if (!dt) return '—';
    return new Date(dt).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

export function formatTime(dt) {
    if (!dt) return '—';
    return new Date(dt).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
}

export function eventTypeLabel(type) {
    const map = {
        TOURNAMENT: 'Турнир',
        TRAINING: 'Тренировка',
        LESSON: 'Урок',
        EXHIBITION: 'Выставочный',
        CAMP: 'Лагерь'
    };
    return map[type] || type || '—';
}

export function buildPagination(response, currentPage, onPageClick) {
    if (!response || response.totalPages <= 1) return null;
    const { totalPages } = response;
    const items = [];

    items.push(`<li class="page-item ${currentPage === 0 ? 'disabled' : ''}">
        <button class="page-link" data-page="${currentPage - 1}">&laquo;</button></li>`);

    for (let i = 0; i < totalPages; i++) {
        if (i === currentPage) {
            items.push(`<li class="page-item active"><button class="page-link">${i + 1}</button></li>`);
        } else if (Math.abs(i - currentPage) <= 2 || i === 0 || i === totalPages - 1) {
            items.push(`<li class="page-item"><button class="page-link" data-page="${i}">${i + 1}</button></li>`);
        } else if (Math.abs(i - currentPage) === 3) {
            items.push(`<li class="page-item disabled"><span class="page-link">…</span></li>`);
        }
    }

    items.push(`<li class="page-item ${currentPage >= totalPages - 1 ? 'disabled' : ''}">
        <button class="page-link" data-page="${currentPage + 1}">&raquo;</button></li>`);

    const $nav = $(`<nav aria-label="Пагинация"><ul class="pagination justify-content-center mt-4">${items.join('')}</ul></nav>`);
    $nav.on('click', '[data-page]', function () {
        const page = parseInt($(this).data('page'));
        if (!isNaN(page) && page >= 0 && page < totalPages) onPageClick(page);
    });
    return $nav;
}

export function getCsrfToken() {
    const cookie = document.cookie.split(';').find(c => c.trim().startsWith('XSRF-TOKEN='));
    return cookie ? decodeURIComponent(cookie.split('=')[1]) : '';
}

export function isAuthenticated() {
    return document.cookie.split(';').some(c => c.trim().startsWith('dp-access='));
}
