(function() {
    let currentPage = window.currentPage || 1;
    let totalPages = window.totalPages || 1;
    let loading = false;
    const container = document.getElementById('projects-container');
    const spinner = document.getElementById('loading-spinner');

    if (!container || currentPage >= totalPages) return;

    function shouldLoad() {
        if (loading) return false;
        const scrollPosition = window.scrollY + window.innerHeight;
        const threshold = document.documentElement.scrollHeight - 300;
        return scrollPosition >= threshold;
    }

    function loadNextPage() {
        if (!shouldLoad()) return;

        loading = true;
        if (spinner) spinner.style.display = 'block';

        const nextPage = currentPage + 1;
        fetch(`?page=${nextPage}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                container.insertAdjacentHTML('beforeend', data.html);
                currentPage = nextPage;
            }
            if (spinner) spinner.style.display = 'none';
            loading = false;
            if (currentPage >= totalPages) spinner?.remove();
        })
        .catch(error => {
            console.error('Ошибка загрузки:', error);
            if (spinner) spinner.style.display = 'none';
            loading = false;
        });
    }

    let timer;
    window.addEventListener('scroll', () => {
        clearTimeout(timer);
        timer = setTimeout(loadNextPage, 150);
    });
    window.addEventListener('load', loadNextPage);
})();