import { initClubsSection } from './clubsSection.js';
import { initEventsSection } from './eventsSection.js';
import { initApplyModal } from './applyModal.js';

initApplyModal();
initClubsSection($('#home-clubs-container'));
initEventsSection($('#home-events-container'));

// ── Home Gallery Slider ──
function initHomeGallerySlider(images) {
    const $container = $('#home-gallery-slider');
    if (!$container.length || !images || images.length === 0) return;

    const cdn = window.cdn || '';
    let current = 0;

    $container.html(`
        <div class="gallery-slider-track">
            ${images.map(img => `<img src="${cdn}${img}" alt="gallery" loading="lazy">`).join('')}
        </div>
        ${images.length > 1 ? `
            <button class="gallery-slider-btn prev" data-dir="prev"><i class="bi bi-chevron-left"></i></button>
            <button class="gallery-slider-btn next" data-dir="next"><i class="bi bi-chevron-right"></i></button>
            <div class="gallery-slider-dots">
                ${images.map((_, i) => `<span data-index="${i}" class="${i === 0 ? 'active' : ''}"></span>`).join('')}
            </div>
        ` : ''}
    `);

    if (images.length <= 1) return;

    const $track = $container.find('.gallery-slider-track');
    const $dots = $container.find('.gallery-slider-dots');

    function goTo(index) {
        current = ((index % images.length) + images.length) % images.length;
        $track.css('transform', `translateX(-${current * 100}%)`);
        $dots.find('span').removeClass('active').eq(current).addClass('active');
    }

    $container.on('click', '.gallery-slider-btn', function () {
        goTo($(this).data('dir') === 'prev' ? current - 1 : current + 1);
    });

    $container.on('click', '.gallery-slider-dots span', function () {
        goTo(parseInt($(this).data('index')));
    });
}

// Init slider из данных, переданных через Thymeleaf
const $galleryPost = $('#home-gallery-container .gallery-post-preview');
if ($galleryPost.length) {
    const imagesAttr = $galleryPost.data('images');
    const images = imagesAttr ? imagesAttr.split(',') : [];
    initHomeGallerySlider(images);
}
