
$(document).ready(function() {
    const visualizations = $(".visualization");
    const batchSize = 10;
    let startIndex = 0;
    let loading = false; // Flag to prevent multiple simultaneous loads

    $(".visualization").closest("tr").prev("tr").hide();
    $(".visualization").closest("tr").hide();

    function loadVisualizations(start, count) {
        if (loading) return; // Prevent concurrent loads
        loading = true;

        const visualizationsToLoad = visualizations.slice(start, start + count);
        let promises = [];

        visualizationsToLoad.each(function() {
            var $this = $(this); // Cache $(this) for better performance
            var example_id = $this.data("example-id");
            var example_positions = $this.data("example-positions");
            var window_location = window.location.pathname.split("/");
            var subtree_hash = window_location.pop(); // This line overwrites the earlier subtree_hash, is this intended?
            var dir_name = window_location.pop();
            var url = window.location.origin + '/stark/visualization/' + dir_name + '/' + example_id + '/' + example_positions;

            promises.push($.ajax({
                url: url,
                success: function(result) {
                    var escapedHtml = `<pre><code class="conllu">${result['annodoc']}</code></pre>`;
                    $this.html(escapedHtml);
                    $('.conllu', $this).each(function() {
                        Annodoc.embedAnnotation($(this), Annodoc.parseConllU, Config.bratCollData);
                    });
                    $this.closest("tr").prev("tr").show();
                    $this.closest("tr").show();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("AJAX Error:", textStatus, errorThrown);
                    $this.html("<p>Error loading data.</p>");
                    $this.closest("tr").prev("tr").show();
                    $this.closest("tr").show();
                },
                complete: function() {
                    // Check if all AJAX calls in the current batch are complete
                    if (promises.every(p => p.state() === 'resolved' || p.state() === 'rejected')) {
                        loading = false; // Allow further loading
                    }
                }
            }));
        });
    }

    function checkScroll() {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200 && !loading) { // 200px buffer
            loadVisualizations(startIndex, batchSize);
            startIndex += batchSize;
        }
    }

    // Initial load
    if (typeof head !== 'undefined' && typeof head.ready === 'function') {
        head.ready(function() {
            loadVisualizations(startIndex, batchSize);
            startIndex += batchSize;
        });
    } else {
        if (typeof Annodoc !== 'undefined') {
            loadVisualizations(startIndex, batchSize);
            startIndex += batchSize;
        } else {
            console.error("head.js or Annodoc is not available. Ensure they are loaded correctly.");
        }
    }


    $(window).scroll(checkScroll); // Attach scroll event listener

});