/*
    This script is responsible for fetching new results on the same page when the user scrolls to the bottom of the page.
*/
document.addEventListener("DOMContentLoaded", function() {
    const templateData = document.getElementById('template-data');
    let page = parseInt(templateData.getAttribute('data-page')) || 1;
    const query = templateData.getAttribute('data-query') || '';
    let searchType = templateData.getAttribute('data-type') || 'text';  // Default to 'text' if not provided
    let loading = false;
    let hasMoreResults = true;
    const loadingIndicator = document.getElementById('message-bottom-left');
    let loadingTimeout;

    function loadResults(newPage) {
        if (loading || !hasMoreResults) return;
        loading = true;

        // Show loading indicator if taking more than 150ms
        loadingTimeout = setTimeout(() => {
            loadingIndicator.style.display = 'flex';
        }, 150);

        fetch(`/search?q=${encodeURIComponent(query)}&t=${encodeURIComponent(searchType)}&p=${newPage}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.text();
            })
            .then(data => {
                clearTimeout(loadingTimeout);
                loadingIndicator.style.display = 'none';
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const newResultsHTML = doc.getElementById('results').innerHTML;
                const noResultsMessage = `No results found for '${query}'. Try different keywords.`;
                const endOfResultsMessage = "Looks like this is the end of results.";
                const serverError = "Internal Server Error";

                const resultsContainer = document.getElementById('results');
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = newResultsHTML;
                while (tempDiv.firstChild) {
                    resultsContainer.appendChild(tempDiv.firstChild);
                }

                if (newResultsHTML.includes(noResultsMessage) || newResultsHTML.includes(endOfResultsMessage) || newResultsHTML.includes(serverError)) {
                    hasMoreResults = false;
                } else {
                    page = newPage;
                    // Automatically load more results if content height is less than window height
                    checkIfMoreResultsNeeded();
                }
                loading = false;
            })
            .catch(error => {
                clearTimeout(loadingTimeout);
                loadingIndicator.style.display = 'none';
                console.error('Error loading results:', error);
                hasMoreResults = false;
                loading = false;
            });
    }

    function checkIfMoreResultsNeeded() {
        if (document.body.scrollHeight <= window.innerHeight && hasMoreResults) {
            loadResults(page + 1);
        }
    }

    window.addEventListener('scroll', () => {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
            loadResults(page + 1);
        }
    });

    // Ensure the correct search button has the active class at load
    const buttons = document.querySelectorAll('.search-container-results-btn button');
    if (buttons.length === 0) {
        console.error("No search buttons found");
    } else {
        buttons.forEach(btn => {
            btn.addEventListener('click', function() {
                const activeElement = document.querySelector('.search-container-results-btn .search-active');
                if (activeElement) {
                    activeElement.classList.remove('search-active');
                }
                this.classList.add('search-active');
                // Update search type when button is clicked
                searchType = this.getAttribute('value');
            });
        });

        // Ensure one button is active on page load
        const initialActiveElement = document.querySelector('.search-container-results-btn .search-active');
        if (!initialActiveElement) {
            buttons[0].classList.add('search-active');
            searchType = buttons[0].getAttribute('value');  // Set default search type
        }
    }

    // Check if more results are needed right after the initial content is loaded
    checkIfMoreResultsNeeded();
});