document.addEventListener('DOMContentLoaded', function () {
    const searchForm = document.getElementById('searchForm');
    const searchInput = document.querySelector('.form-control');
    const searchResultsDiv = document.getElementById("searchResultsDiv");
    const closeResultsBtn = document.getElementById("closeResultsBtn");
    const clearSearchInputBtn = document.getElementById('clearSearchInputBtn');
    const resultsWaitMsg = document.getElementById('ResultsWaitMsg');

    // Flag to check if search results are already visible
    let searchResultsVisible = false;

    searchForm.addEventListener('submit', function (event) {
        event.preventDefault();

        // Change cursor to "wait"
        document.body.style.cursor = 'wait';

        // Show the waiting message
        resultsWaitMsg.style.display = 'block';

        const userInput = searchInput.value.trim().toLowerCase();
        performSearch(userInput, function(results) {
            // console.log('Search Results:', results);
            // Call function to display search results with search term
            displaySearchResults(results, userInput);

            if (!searchResultsVisible) {
                showSearchResults(); // Call function to show search results with animation only if not already shown
            }
            searchResultsVisible = true;

            // Hide the waiting message when results are returned
            resultsWaitMsg.style.display = 'none';

            // Reset cursor to default
            document.body.style.cursor = 'default';
        });
    });

    // Add event listener to the clear button
    clearSearchInputBtn.addEventListener('click', function() {
        // Clear the search input field
        searchInput.value = '';
        // Bring focus to the input field
        searchInput.focus();
    });

    // Function to show search results with animation
    function showSearchResults() {
        searchResultsDiv.style.display = 'block'; // Make sure search results div is visible
        searchResultsDiv.style.transform = 'translateX(100%)'; // Start from the right side of the screen
        setTimeout(function() {
            searchResultsDiv.style.transform = 'translateX(0%)'; // Slide back into view

            // Hide the waiting message after results div is shown
            resultsWaitMsg.style.display = 'none';
        }, 50); // Adjust the delay to ensure the animation is visible
    }

    closeResultsBtn.addEventListener('click', function() {
        if (searchResultsVisible) { // Check if search results are currently visible
            searchResultsDiv.style.transform = 'translateX(100%)'; // Slide to the right
            setTimeout(function() {
                searchResultsDiv.style.display = 'none'; // Hide the element after the animation completes
            }, 300); // Adjust the timeout to match the transition duration
            searchResultsVisible = false;
        }
    });

    function performSearch(searchQuery, callback) {
        console.log('Performing search for query:', searchQuery);
        fetchIndexData().then(indexData => {
            const results = [];
            let totalMatches = 0; // Variable to keep track of total matches found
            for (const productIdentifier in indexData) {
                // Filter out records with '`Reuse' in the path
                if (indexData[productIdentifier].Path.includes('`Reuse')) {
                    // console.log('Skipping productIdentifier containing `Reuse` in path:', productIdentifier);
                    continue;
                }
                const htmlContent = indexData[productIdentifier].Content.value;
                const parser = new DOMParser();
                const doc = parser.parseFromString(htmlContent, 'text/html');
                const text = doc.body.textContent || '';
                const matches = text.match(new RegExp(searchQuery, 'gi')); // Use RegExp to find all matches
                if (matches && matches.length > 0) {
                    totalMatches += matches.length; // Increment total matches count
                    results.push(indexData[productIdentifier]); // Push entire object to results
                }
            }
            // console.log('Total matches found:', totalMatches);
            callback(results);
        }).catch(error => {
            console.error('Error fetching index data:', error);
            callback([]);
        });
    }
    

    function fetchIndexData() {
        const productIdentifier = getProductIdentifier();
        const indexPath = `s-index.json`;

        return fetch(indexPath)
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else if (response.status === 404) {
                    return fetchAndCreateIndexFile(productIdentifier);
                } else {
                    throw new Error(`Error fetching index data. Status: ${response.status}, URL: ${indexPath}`);
                }
            })
            .then(data => {
                return data;
            })
            .catch(error => console.error('Error fetching index data:', error));
    }

    function fetchAndCreateIndexFile(productIdentifier) {
        return fetch(`/resources/landingpages/js/${productIdentifier}_searchIndexData.json`)
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else if (response.status === 404) {
                    console.warn(`Index data file not found for ${productIdentifier}. Creating an empty index.`);
                    return {};
                } else {
                    throw new Error(`Error fetching index data. Status: ${response.status}`);
                }
            })
            .then(indexData => {
                const blob = new Blob([JSON.stringify(indexData)], { type: 'application/json' });

                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = `${productIdentifier}_searchIndex.json`;

                link.click();

                return indexData;
            })
            .catch(error => {
                console.error('Error fetching and creating index file:', error);
                return {};
            });
    }

    function getProductIdentifier() {
        const currentPath = window.location.pathname;
        return currentPath.split('/')[2];
    }
});


// Function to display search results MINUS NULL
function displaySearchResults(searchResults, searchTerm) {


        // Get all radio buttons with the class 'sortOption'
        const radioButtons = document.querySelectorAll('.sortOption');

        // Iterate through the radio buttons and disable them
        radioButtons.forEach(button => {
            button.disabled = true;
        });
    

        

    // Get the search results div element
    const searchResultsDiv = document.getElementById("searchResultsDiv");

    // Check if the header already exists
    let searchResultsHeader = searchResultsDiv.querySelector(".search-results-header");

    // If the header doesn't exist, create it
    if (!searchResultsHeader) {
        // Create a new div element for the header
        searchResultsHeader = document.createElement("div");
        searchResultsHeader.classList.add("search-results-header");

        // Create HTML content for the header
        const headerContent = `
            <h2>Search Results</h2>
            <button id="closeResultsBtn" class="close-results-btn">×</button>
        `;

        // Set the inner HTML of the header div
        searchResultsHeader.innerHTML = headerContent;

        // Append the header div to the search results div
        searchResultsDiv.appendChild(searchResultsHeader);
    }

    // Get the search results container
    const searchResultsContainer = document.getElementById("searchResultsContainer");

    // Clear any previous search results
    searchResultsContainer.innerHTML = "";

    // If no results were found, display a message
    if (searchResults.length === 0) {
        const noResultsMessage = document.createElement("p");
        noResultsMessage.innerHTML = `Your search returned no results for <strong>${searchTerm}</strong>`;
        noResultsMessage.id = "resultNotFound"; // Add id to the resulting paragraph element
        searchResultsContainer.appendChild(noResultsMessage);
        return; // Stop execution since there are no results to display
    }

    // Add a count of the number of results and display it at the top
    const resultsCount = document.createElement("p");
    resultsCount.innerHTML = `${searchResults.length} document(s) found for <strong>${searchTerm}</strong>`;
    resultsCount.id = "resultsFound";
    searchResultsContainer.appendChild(resultsCount);

    // Loop through the search results and create HTML elements to display them
    searchResults.forEach(result => {
        // Modify the link if the base path of the result includes '/dev/' or '\dev\'
        let link = result.Link + `?hl=${encodeURIComponent(searchTerm)}`;
        // console.log("Original link:", link); // Log the original link for debugging
        if (link.includes('/dev/') || link.includes('\\dev\\')) {
            link = link.replace(/^.*?[\/\\]dev[\/\\]/i, 'https://dev-documentation.wolterskluwerfs.com/');
            // console.log("Modified link:", link); // Log the modified link for debugging
        }
        if (link.includes('/stg/') || link.includes('\\stg\\')) {
            link = link.replace(/^.*?[\/\\]stg[\/\\]/i, 'https://stg-documentation.wolterskluwerfs.com/');
            // console.log("Modified link:", link); // Log the modified link for debugging
        }
        if (link.includes('/tst/') || link.includes('\\tst\\')) {
            link = link.replace(/^.*?[\/\\]tst[\/\\]/i, 'https://tst-documentation.wolterskluwerfs.com/');
            // console.log("Modified link:", link); // Log the modified link for debugging
        }
        if (link.includes('/prod/') || link.includes('\\prod\\')) {
            link = link.replace(/^.*?[\/\\]prod[\/\\]/i, 'https://documentation.wolterskluwerfs.com/');
            // console.log("Modified link:", link); // Log the modified link for debugging
        }
        if (link.includes('/tst-expere/') || link.includes('\\tst-expere\\')) {
            link = link.replace(/^.*?[\/\\]tst-expere[\/\\]/i, 'https://tst-expere-documentation.wolterskluwerfs.com/');
            // console.log("Modified link:", link); // Log the modified link for debugging
        }

        // Create a new div element for each search result
        const resultDiv = document.createElement("div");
        resultDiv.classList.add("search-result");

        // Create HTML content for the search result
        const resultContent = `
            <p class="searchResultTitle"><a href="${link}" target="_blank">${result.Title}</a></p>
            <p class="RelDocTitle">${result.Document}</p> <!-- Add paragraph with class RelDocTitle -->
            <p id="relevanceIndicator${result.Id}"></p> <!-- Provide an id for relevance indicator -->
        `;

        // Set the inner HTML of the result div
        resultDiv.innerHTML = resultContent;

        // Append the result div to the search results container
        searchResultsContainer.appendChild(resultDiv);
    });
}


// #region SORTING OPTIONS
// Add event listener to the sort options dropdown menu or buttons
const sortOptions = document.getElementById("sortOptions");
sortOptions.addEventListener("change", function(event) {
    const selectedOption = event.target.value;
    sortSearchResults(selectedOption);
});

// Define searchResults in a global scope
let searchResults = [];

// Function to sort the search results based on the selected option
function sortSearchResults(option, results) {
    // Modify the sorting logic based on the selected option
    switch(option) {
        case "relevance":
            // Implement sorting by relevance
            results.sort((a, b) => {
                // Compare relevance of search results 'a' and 'b'
                // and return -1, 0, or 1 based on the comparison
            });
            break;
        case "title":
            // Implement sorting by title
            results.sort((a, b) => {
                // Compare titles of search results 'a' and 'b'
                const titleA = a.Title.toLowerCase();
                const titleB = b.Title.toLowerCase();
                if (titleA < titleB) return -1;
                if (titleA > titleB) return 1;
                return 0;
            });
            break;
        case "docname":
            // Implement sorting by document name
            results.sort((a, b) => {
                // Compare document names of search results 'a' and 'b'
                const docNameA = a.Document.toLowerCase();
                const docNameB = b.Document.toLowerCase();
                if (docNameA < docNameB) return -1;
                if (docNameA > docNameB) return 1;
                return 0;
            });
            break;
        default:
            // Default sorting option
            break;
    }


    // Display the sorted results
    displaySearchResults(results);
}

// #endregion