const API = '/api/gallery';

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

function initSlider($container, images) {
    if (!images || images.length === 0) {
        $container.html(`
            <div class="gallery-no-images">
                <i class="bi bi-image d-block"></i>
                <p>Нет изображений</p>
            </div>
        `);
        return;
    }

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

    const trackId = 'slider-track-' + Math.random().toString(36).substr(2, 9);
    const dotsId = 'slider-dots-' + Math.random().toString(36).substr(2, 9);

    $container.html(`
        <div class="gallery-slider">
            <div class="gallery-slider-track" id="${trackId}">
                ${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" id="${dotsId}">
                    ${images.map((_, i) => `<span data-index="${i}" class="${i === 0 ? 'active' : ''}"></span>`).join('')}
                </div>
            ` : ''}
        </div>
    `);

    if (images.length <= 1) return;

    const $track = $(`#${trackId}`);
    const $dots = $(`#${dotsId}`);

    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 () {
        const dir = $(this).data('dir');
        goTo(dir === 'prev' ? current - 1 : current + 1);
    });

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

    // Touch support
    let startX = 0;
    $container.on('touchstart', e => { startX = e.originalEvent.touches[0].clientX; });
    $container.on('touchend', e => {
        const diff = startX - e.originalEvent.changedTouches[0].clientX;
        if (Math.abs(diff) > 50) {
            goTo(diff > 0 ? current + 1 : current - 1);
        }
    });
}

function renderPost(post) {
    const sliderId = 'slider-' + post.uuid;
    return `
        <div class="gallery-post-card">
            <div id="${sliderId}"></div>
            <div class="gallery-post-content">
                <h3 class="gallery-post-title">${esc(post.title)}</h3>
                <div class="gallery-post-date">
                    <i class="bi bi-calendar3 me-1"></i>${formatDate(post.publishedAt || post.createdAt)}
                </div>
                ${post.content ? `<div class="gallery-post-text">${esc(post.content)}</div>` : ''}
            </div>
        </div>
    `;
}

function esc(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function loadPosts(page = 0) {
    const $container = $('#gallery-posts-container');
    $container.html('<div class="text-center py-5"><div class="spinner-border text-success" role="status"></div></div>');

    $.ajax({
        url: `${API}/posts`,
        type: 'GET',
        data: { page, size: 12 },
        success: (response) => {
            $container.empty();
            if (!response.content || response.content.length === 0) {
                $container.html(`
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-images fs-1 d-block mb-3 opacity-50"></i>
                        <h5>Пока нет публикаций</h5>
                        <p>Следите за обновлениями!</p>
                    </div>
                `);
                return;
            }

            const $list = $('<div></div>');
            response.content.forEach(post => {
                $list.append(renderPost(post));
            });
            $container.append($list);

            // Init sliders
            response.content.forEach(post => {
                if (post.imageUrls && post.imageUrls.length > 0) {
                    initSlider($(`#slider-${post.uuid}`), post.imageUrls);
                }
            });

            // Pagination
            if (response.totalPages > 1) {
                const $pagination = $(`
                    <nav aria-label="Галерея">
                        <ul class="pagination justify-content-center mt-4">
                            <li class="page-item ${page === 0 ? 'disabled' : ''}">
                                <button class="page-link" data-page="${page - 1}">&laquo;</button>
                            </li>
                            ${Array.from({ length: response.totalPages }, (_, i) => `
                                <li class="page-item ${i === page ? 'active' : ''}">
                                    <button class="page-link" data-page="${i}">${i + 1}</button>
                                </li>
                            `).join('')}
                            <li class="page-item ${page >= response.totalPages - 1 ? 'disabled' : ''}">
                                <button class="page-link" data-page="${page + 1}">&raquo;</button>
                            </li>
                        </ul>
                    </nav>
                `);

                $pagination.on('click', '[data-page]', function (e) {
                    e.preventDefault();
                    const p = parseInt($(this).data('page'));
                    if (!isNaN(p) && p >= 0 && p < response.totalPages) {
                        loadPosts(p);
                    }
                });

                $container.append($pagination);
            }
        },
        error: () => $container.html('<div class="alert alert-danger">Ошибка загрузки галереи</div>')
    });
}

$(document).ready(() => {
    loadPosts(0);
});
