// List of common English stop words
const STOP_WORDS = [
    'a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'any', 'are', "aren't", 'as', 'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by',
    'could', "couldn't", 'did', "didn't", 'do', 'does', "doesn't", 'doing', "don't", 'down', 'during', 'each', 'few', 'for', 'from', 'further', 'had', "hadn't", 'has', "hasn't", 'have', "haven't", 'having', 'he', "he'd", "he'll", "he's", 'her', 'here', "here's", 'hers', 'herself', 'him', 'himself', 'his', 'how', "how's", 'i', "i'd", "i'll", "i'm", "i've", 'if', 'in', 'into', 'is', "isn't", 'it', "it's", 'its', 'itself', "let's", 'me', 'more', 'most', "mustn't", 'my', 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'other', 'ought', 'ours', 'ourselves', 'out', 'over', 'own',
    'same', "shan't", 'she', "she'd", "she'll", "she's", 'should', "shouldn't", 'so', 'some', 'such', 'than', 'that', "that's", 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'there', "there's", 'these', 'they', "they'd", "they'll", "they're", "they've", 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was', "wasn't", 'we', "we'd", "we'll", "we're", "we've", 'were', "weren't", 'what', "what's", 'when', "when's", 'where', "where's", 'which', 'while', 'who', "who's", 'whom', 'why', "why's", 'with', "won't", 'would', "wouldn't", 'you', "you'd", "you'll", "you're", "you've", 'your', 'yours', 'yourself', 'yourselves'
];

// Function to filter stop words from a search query
function filterStopWords(query) {
    const trimmed = query.trim().toLowerCase();
    // If the query is only 'and' or only 'or', treat as stop word
    if (trimmed === 'and' || trimmed === 'or') {
        return '';
    }
    // Split query into words, filter out stop words, and join back
    return query
        .split(/\s+/)
        .filter(word => word && !STOP_WORDS.includes(word.toLowerCase()))
        .join(' ');
}

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) {
        // Clear any previous feedback message
        var feedbackMsg = document.getElementById('searchFeedbackMsg');
        if (feedbackMsg) {
            feedbackMsg.style.display = 'none';
            feedbackMsg.textContent = '';
        }
        event.preventDefault();
    
        // Reset results visibility for new search
        searchResultsVisible = false;
    
        // 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, stopWordsOnly) {
            if (stopWordsOnly) {
                document.body.style.cursor = 'default';
                resultsWaitMsg.style.display = 'none';
                if (typeof searchResultsDiv !== 'undefined' && searchResultsDiv) {
                    searchResultsDiv.style.display = 'none';
                }
                searchResultsVisible = false; // <-- Reset here too
                return;
            }
    
            // Always show results div for valid searches
            if (typeof searchResultsDiv !== 'undefined' && searchResultsDiv) {
                searchResultsDiv.style.display = 'block';
            }
    
            displaySearchResults(results, userInput);
    
            if (!searchResultsVisible) {
                showSearchResults();
            }
            searchResultsVisible = true;
    
            resultsWaitMsg.style.display = 'none';
            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;
        }
    });

    // Helper to parse AND/OR logic in queries
    function parseQueryWithAndOr(query) {
        // Split by OR (case-insensitive)
        const orGroups = query.split(/\s+OR\s+/i);
        return orGroups.map(group => {
            // For each OR group, split by AND (case-insensitive)
            return group.split(/\s+AND\s+/i).map(term => term.trim()).filter(Boolean);
        });
    }

    // FILTERING
    function performSearch(searchQuery, callback) {
        // Detect if the query is a quoted phrase
        const isQuotedSearch = searchQuery.startsWith('"') && searchQuery.endsWith('"');
        let termToSearch;

        if (isQuotedSearch) {
            // Use the exact phrase, minus quotes
            termToSearch = searchQuery.slice(1, -1).trim().toLowerCase();
            if (!termToSearch) {
                callback([]);
                return;
            }
        } else {
            // For multi-term search, filter stop words
            const filteredQuery = filterStopWords(searchQuery);
            if (!filteredQuery) {
                if (typeof resultsWaitMsg !== 'undefined' && resultsWaitMsg) {
                    resultsWaitMsg.style.display = 'none';
                }
                if (typeof searchResultsDiv !== 'undefined' && searchResultsDiv) {
                    // Close the search results div with animation when stop words are searched
                    if (searchResultsVisible) {
                        searchResultsDiv.style.transform = 'translateX(100%)'; // Slide to the right
                        setTimeout(function() {
                            searchResultsDiv.style.display = 'none'; // Hide after animation completes
                        }, 300); // Match transition duration
                        searchResultsVisible = false;
                    } else {
                        searchResultsDiv.style.display = 'none';
                    }
                }
                document.body.style.cursor = 'default';
                var feedbackMsg = document.getElementById('searchFeedbackMsg');
                if (feedbackMsg) {
                    feedbackMsg.textContent = 'Please enter a more specific search term.';
                    feedbackMsg.style.display = 'block';
                }
                callback([], true); // Pass true to indicate stop words only
                return;
            }
            termToSearch = filteredQuery.trim().toLowerCase();
        }

        // Parse query for AND/OR logic (outside of quoted searches)
        let andOrGroups = null;
        if (!isQuotedSearch) {
            andOrGroups = parseQueryWithAndOr(termToSearch);
        }

        console.log('Performing search for query:', searchQuery);
        fetchIndexData().then(indexData => {
            const results = [];
            console.log('Normalized search term:', termToSearch);

            for (const entry of indexData) {
            // For debug: get a display title for this entry
            const entryTitle = entry.Title || (entry.Link ? entry.Link : '[No Title]');
            let debugMatchedTerms = [];
                const htmlContent = entry.Content.value;
                const parser = new DOMParser();
                const doc = parser.parseFromString(htmlContent, 'text/html');
                const text = doc.body.textContent || '';

                const titleElements = doc.querySelectorAll('.wh_publication_title .title, .title, .topictitle1, .sectiontitle');
                let termInTitle = false;
                let termInContent = false;
                let matches = 0;
                let groupMatched = false;

                if (isQuotedSearch) {
                    // Phrase match
                    const regex = new RegExp(termToSearch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
                    termInTitle = Array.from(titleElements).some(title =>
                        title.textContent.trim().toLowerCase().includes(termToSearch)
                    );
                    termInContent = text.toLowerCase().includes(termToSearch);
                    matches = (text.match(regex) || []).length;
                    // For quoted search, treat as a single group match if found
                    if (text.toLowerCase().includes(termToSearch) || Array.from(titleElements).some(title => title.textContent.trim().toLowerCase().includes(termToSearch))) {
                        groupMatched = true;
                    }
                } else {
                    // AND/OR logic
                    let maxMatches = 0;
                    let foundInTitle = false;
                    let foundInContent = false;

                    for (const andGroup of andOrGroups) {
                        // Each andGroup is an array of terms that must all be present (AND)
                        let allTermsPresent = true;
                        let groupMatches = 0;
                        let groupInTitle = false;
                        let groupInContent = false;

                        for (const word of andGroup) {
                            const regex = new RegExp(`\\b${word}\\b`, 'gi');
                            const inTitle = Array.from(titleElements).some(title =>
                                title.textContent.trim().toLowerCase().includes(word)
                            );
                            const inContent = text.toLowerCase().includes(word);

                            // For AND, all terms must be present in either title or content
                            if (!inTitle && !inContent) {
                                allTermsPresent = false;
                                break;
                            }

                            if (inTitle) groupInTitle = true;
                            if (inContent) groupInContent = true;
                            groupMatches += (text.match(regex) || []).length;
                        }

                        if (allTermsPresent) {
                            groupMatched = true;
                            if (groupMatches > maxMatches) maxMatches = groupMatches;
                            if (groupInTitle) foundInTitle = true;
                            if (groupInContent) foundInContent = true;
                            debugMatchedTerms.push(andGroup.join(' AND '));
                        }
                    }

                    termInTitle = foundInTitle;
                    termInContent = foundInContent;
                    matches = maxMatches;
                    // Debug: Log which AND/OR group(s) matched for this entry
                    if (debugMatchedTerms.length > 0) {
                        console.log(`[DEBUG] (AND/OR) Matched group(s) [${debugMatchedTerms.join('] OR [')}] in:`, entryTitle);
                    }
                    groupMatched = debugMatchedTerms.length > 0; // At least one group matched
                }

                // Check if the search result is within a nav or meta element or its children
                const isWithinNav = isTermInParentElement(doc, termToSearch, 'nav');
                const isWithinMeta = isTermInParentElement(doc, termToSearch, 'meta');

                // Proceed only if term is found in title or content and not in nav/meta
                if (groupMatched && (termInTitle || termInContent) && !isWithinNav && !isWithinMeta) {
                    if (matches && matches > 0) {
                        entry.relevanceScore = matches;

                        // Boost relevance score if term is in a title element
                        if (termInTitle) {
                            entry.relevanceScore += 10;
                        }

                        results.push(entry);
                    }
                }
            }

            // Sort results by relevance score in descending order
            results.sort((a, b) => b.relevanceScore - a.relevanceScore);

            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];
    }

    const sortByTypeBtn = document.getElementById('sortByTypeBtn');
    if (sortByTypeBtn) {
        sortByTypeBtn.addEventListener('click', function (event) {
            event.preventDefault();
            sortResultsByType();
        });
    }
});


// Helper function to check if the search term occurs within any level of parent 'wh_publication_toc'
function isTermInParentElement(doc, term, parentId) {
    const parentElement = doc.getElementById(parentId);
    if (parentElement && parentElement.textContent.toLowerCase().includes(term.toLowerCase())) {
        return true; // Return true if the term is found within the parent element
    }
    return false; // Return false if the term is not found within the parent element
}

function displaySearchResults(searchResults, searchTerm) {
    console.log('Displaying search results for term:', searchTerm); // Add logging for search term
    // 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 the custom modal
    if (searchResults.length === 0) {
        showCustomModal();
        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} result(s) found for <strong>${searchTerm}</strong>`;
    resultsCount.id = "resultsFound";
    searchResultsContainer.appendChild(resultsCount);

    // Sort search results based on relevance percentage in descending order
    searchResults.sort((a, b) => {
        const maxRelevanceScore = Math.max(...searchResults.map(result => result.relevanceScore), 20); // Use 20 as default if no results
        const relevancePercentageA = (a.relevanceScore / maxRelevanceScore) * 100;
        const relevancePercentageB = (b.relevanceScore / maxRelevanceScore) * 100;
        return relevancePercentageB - relevancePercentageA; // Descending order
    });

    // Loop through the sorted 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)}`;
        if (link.includes('/dev/') || link.includes('\\dev\\')) {
            link = link.replace(/^.*?[\/\\]dev[\/\\]/i, 'https://dev-documentation.wolterskluwerfs.com/');
        }
        if (link.includes('/stg/') || link.includes('\\stg\\')) {
            link = link.replace(/^.*?[\/\\]stg[\/\\]/i, 'https://stg-documentation.wolterskluwerfs.com/');
        }
        if (link.includes('/tst/') || link.includes('\\tst\\')) {
            link = link.replace(/^.*?[\/\\]tst[\/\\]/i, 'https://tst-documentation.wolterskluwerfs.com/');
        }
        if (link.includes('/prod/') || link.includes('\\prod\\')) {
            link = link.replace(/^.*?[\/\\]prod[\/\\]/i, 'https://documentation.wolterskluwerfs.com/');
        }
        if (link.includes('/tst-expere/') || link.includes('\\tst-expere\\')) {
            link = link.replace(/^.*?[\/\\]tst-expere[\/\\]/i, 'https://tst-expere-documentation.wolterskluwerfs.com/');
        }

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

        // Calculate percentage relevance (for the stars image background)
        const maxRelevanceScore = Math.max(...searchResults.map(result => result.relevanceScore), 20); // Use 20 as default if no results
        const relevancePercentage = ((result.relevanceScore / maxRelevanceScore) * 100).toFixed(3); // Format to 3 decimal places

        // Check if the "Omit < 10%" checkbox is checked
        const omitLessThanTenPercentCheckbox = document.getElementById("omitLessThanTenPercent");
        const omitLessThanTenPercent = omitLessThanTenPercentCheckbox.checked;

        // Skip results with relevance percentage below 10% if the checkbox is checked
        if (omitLessThanTenPercent && relevancePercentage < 10) {
            return; // Skip this result
        }

        // Extracting the sentence containing the search term
        const relevantSentence = extractRelevantSentence(result.Content.value, searchTerm);

        // Truncate the sentence to 100 characters with an ellipsis if necessary
        const shortDesc = relevantSentence.length > 100 ? relevantSentence.substring(0, 100) + "..." : relevantSentence;

        // Create HTML content for the search result
        const resultContent = `
            <div class="result-details">
                <p class="searchResultTitle"><a href="${link}" target="_blank">${result.Title}</a></p>
                <div class="rel-doc-container">
                    <p class="RelDocTitle">${result.Document}</p>
                    <div class="stars-container" title="Relevance: ${relevancePercentage}%">
                        <div class="stars-background">
                            <i class="bi bi-star"></i>
                            <i class="bi bi-star"></i>
                            <i class="bi bi-star"></i>
                            <i class="bi bi-star"></i>
                            <i class="bi bi-star"></i>
                        </div>
                        <div class="stars-filled" style="width: ${relevancePercentage}%">
                            <i class="bi bi-star-fill"></i>
                            <i class="bi bi-star-fill"></i>
                            <i class="bi bi-star-fill"></i>
                            <i class="bi bi-star-fill"></i>
                            <i class="bi bi-star-fill"></i>
                        </div>
                    </div>
                    <div class="hits-info">Hits: ${countTermFrequency(result.Content.value, searchTerm)}</div>
                </div>
            </div>
        `;

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

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

    // Create a footer element
    const footer = document.createElement("footer");
    footer.innerHTML = ""; // You can customize the content of the footer here
    footer.classList.add("searchResultsFooter");
    footer.id = "searchResultsFooter";

    // Append the footer to the search results container
    searchResultsContainer.appendChild(footer);
}


// Helper function to count the number of times a term appears in a string
function countTermFrequency(content, term) {
    // Extract only the text content from the HTML content
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, 'text/html');
    const textContent = doc.body.textContent || '';

    // Use the extracted text content for counting hits
    const regex = new RegExp(term, "gi");
    return textContent.match(regex)?.length || 0; // Return 0 if no matches found
}


function extractRelevantSentence(content, searchTerm) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, 'text/html');
    const textContent = doc.body.textContent || ''; // Extract text content while preserving basic formatting
  
    // Split the text content into an array of words
    const words = textContent.split(/\s+/); // Split by whitespace (including punctuation)
  
    // Find the index of the first exact match of the search term
    const termIndex = words.indexOf(searchTerm.toLowerCase());
  
    // If the search term is found
    if (termIndex !== -1) {
      let start = termIndex - 1;
      let end = termIndex + 1;
  
      // Find the beginning of the sentence before the term
      while (start >= 0 && !isSentenceEnd(words[start])) {
        start--;
      }
  
      // Find the end of the sentence after the term
      while (end < words.length && !isSentenceEnd(words[end])) {
        end++;
      }
  
      // Join the window of words back into a sentence
      const relevantSentence = words.slice(Math.max(0, start + 1), end).join(" ");
  
      // Return the extracted sentence
      return relevantSentence.trim();
    }
  
    // If no exact match is found, return an empty string
    return "";
  }
  
  function isSentenceEnd(word) {
    return word.includes(".") || word.includes("?") || word.includes("!");
  }
    

function toggleResultsInfo() {
    // Toggle the visibility of the resultsInfo div
    $('#resultsInfo').toggle();
}

// Function to close the resultsInfo div
function closeResultsInfo() {
    // Hide the resultsInfo div
    $('#resultsInfo').hide();
}

document.getElementById('sortByTermFrequencyBtn').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent the default behavior of the link
    sortByTermFrequency();
});

document.getElementById('sortByDocumentType').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent the default behavior of the link
    sortByDocumentType();
});

document.getElementById('omitLtTenPercent').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent the default behavior of the link
    removeResultsBelowTenPercent();
});


// Function to sort results by term frequency
function sortByTermFrequency() {
    // Get the search results container
    var container = document.getElementById('searchResultsContainer');

    // Get the search results footer
    var footer = document.getElementById('searchResultsFooter');

    // Get all search result elements
    var results = container.querySelectorAll('.search-result');

    // Convert NodeList to array for sorting
    var resultsArray = Array.from(results);

    // Sort the array of search result elements based on relevance
    resultsArray.sort(function(a, b) {
        // Get the relevance values from the stars-container elements
        var relevanceA = parseFloat(a.querySelector('.stars-container').getAttribute('title').match(/\d+\.\d+/)[0]);
        var relevanceB = parseFloat(b.querySelector('.stars-container').getAttribute('title').match(/\d+\.\d+/)[0]);

        // Sort in descending order
        return relevanceB - relevanceA;
    });

    // Re-append the sorted elements to the container
    resultsArray.forEach(function(result) {
        container.appendChild(result);
    });

    // Move the footer to the bottom of the container
    container.appendChild(footer);
}


function sortByDocumentType() {
    // Get the search results container
    var container = document.getElementById('searchResultsContainer');

    // Get the search results footer
    var footer = document.getElementById('searchResultsFooter');

    // Get all search result elements
    var results = container.querySelectorAll('.search-result');

    // Convert NodeList to array for sorting
    var resultsArray = Array.from(results);

    // Sort the array of search result elements based on the RelDocTitle
    resultsArray.sort(function(a, b) {
        var titleA = a.querySelector('.RelDocTitle').textContent.trim().toLowerCase();
        var titleB = b.querySelector('.RelDocTitle').textContent.trim().toLowerCase();

        // Define sorting logic
        if (titleA.includes('release notes') || titleA.includes('changelog')) {
            return 1; // Move items with "Release Notes" or "Changelog" to the end
        } else if (titleB.includes('release notes') || titleB.includes('changelog')) {
            return -1; // Move items with "Release Notes" or "Changelog" to the end
        } else {
            return titleA.localeCompare(titleB); // Sort alphabetically
        }
    });

    // Re-append the sorted elements to the container
    resultsArray.forEach(function(result) {
        container.appendChild(result);
    });

    // Move the footer to the bottom of the container
    container.appendChild(footer);
}

function removeResultsBelowTenPercent() {
    // Get the search results container
    var container = document.getElementById('searchResultsContainer');

    // Get all search result elements
    var results = container.querySelectorAll('.search-result');

    // Iterate through each search result
    results.forEach(function(result) {
        // Get the relevance value from the stars-container element
        var relevance = parseFloat(result.querySelector('.stars-container').getAttribute('title').match(/\d+\.\d+/)[0]);

        // Check if relevance is less than 10%
        if (relevance < 10) {
            // Remove the search result
            result.remove();
        }
    });
}


//#region Search Options
// Get the search options button
const searchOptionsBtn = document.getElementById('searchOptionsBtn');

// Get the custom search options container
const customSearchOptions = document.getElementById('customSearchOptions');

// Add event listener to toggle the display
searchOptionsBtn.addEventListener('click', function() {
    // Toggle the display of custom search options
    if (customSearchOptions.style.display === 'none') {
        customSearchOptions.style.display = 'block';
    } else {
        customSearchOptions.style.display = 'none';
    }
});
//#endregion


//#region Whole Word match
// Get references to the checkboxes
const wholeWordMatchCheckbox = document.getElementById('wholeWordMatch');
const wholeWordMatch2Checkbox = document.getElementById('wholeWordMatch2');

// Add event listeners to synchronize the toggling behavior
wholeWordMatchCheckbox.addEventListener('change', function() {
    wholeWordMatch2Checkbox.checked = this.checked;
});

wholeWordMatch2Checkbox.addEventListener('change', function() {
    wholeWordMatchCheckbox.checked = this.checked;
});

// Add event listener to the wholeWordMatch checkbox
document.getElementById('wholeWordMatch').addEventListener('change', function() {
    // Get the search term from the search input field
    const searchTerm = document.querySelector('.form-control').value.trim().toLowerCase();

    // Get all search result elements
    const results = document.querySelectorAll('.search-result');

    // Iterate through each search result
    results.forEach(result => {
        // Get the title and content of the search result
        const title = result.querySelector('.searchResultTitle').textContent.trim().toLowerCase();
        const content = result.querySelector('.result-details').textContent.trim().toLowerCase();

        // Check if the wholeWordMatch checkbox is checked
        const wholeWordMatchChecked = document.getElementById('wholeWordMatch').checked;

        // If wholeWordMatch is checked and the result doesn't match the search term exactly, hide it
        if (wholeWordMatchChecked && !isWholeWordMatch(title, searchTerm) && !isWholeWordMatch(content, searchTerm)) {
            result.style.display = 'none';
        } else {
            result.style.display = 'block';
        }
    });
});

document.getElementById('wholeWordMatch2').addEventListener('change', function() {
    // Get the search term from the search input field
    const searchTerm = document.querySelector('.form-control').value.trim().toLowerCase();

    // Get all search result elements
    const results = document.querySelectorAll('.search-result');

    // Iterate through each search result
    results.forEach(result => {
        // Get the title and content of the search result
        const title = result.querySelector('.searchResultTitle').textContent.trim().toLowerCase();
        const content = result.querySelector('.result-details').textContent.trim().toLowerCase();

        // Check if the wholeWordMatch checkbox is checked
        const wholeWordMatchChecked = document.getElementById('wholeWordMatch').checked;

        // If wholeWordMatch is checked and the result doesn't match the search term exactly, hide it
        if (wholeWordMatchChecked && !isWholeWordMatch(title, searchTerm) && !isWholeWordMatch(content, searchTerm)) {
            result.style.display = 'none';
        } else {
            result.style.display = 'block';
        }
    });
});

// Helper function to check if a term is a whole word match
function isWholeWordMatch(text, term) {
    // Create a regular expression pattern to match the whole word
    const regex = new RegExp("\\b" + term + "\\b", "gi"); // \b represents a word boundary

    // Check if the term is found in the text
    return text.match(regex) !== null;
}
//#endregion

// Function to re-sort search results by document type
function sortResultsByType() {
    // 1. Crawl the landing page for section mappings
    const sectionMap = {};
    const sectionDivs = document.querySelectorAll('[id$="Section"]');
    sectionDivs.forEach(sectionDiv => {
        // Find the section name (from the <h2> or similar)
        let sectionHeader = sectionDiv.querySelector('h2, h3, .section-title');
        let sectionName = sectionHeader ? sectionHeader.textContent.trim() : sectionDiv.id;
        // Find all document titles in this section
        let docLinks = sectionDiv.querySelectorAll('ul > li > a');
        docLinks.forEach(link => {
            let title = link.textContent.trim();
            if (title) sectionMap[title.toLowerCase()] = sectionName;
        });
    });


    // 2. Parse the search results in searchResultsDiv
    const resultsDiv = document.getElementById('searchResultsContainer');
    if (!resultsDiv) return;

    // Get all result items (assuming each result has a class 'search-result')
    const resultItems = Array.from(resultsDiv.querySelectorAll('.search-result'));

    // 3. Group results by section
    const grouped = {};
    const otherSection = "Other";
    // List of words to ignore in matching (can be expanded)
    const IGNORED_WORDS = ['guide', 'manual', 'user', 'the', 'a', 'an', 'to', 'of', 'and', 'for', 'by', 'on', 'in', 'with', 'reference', 'documentation'];

    function tokenizeTitle(title) {
        return title
            .toLowerCase()
            .replace(/[^a-z0-9 ]/gi, ' ') // Remove punctuation
            .split(/\s+/)
            .filter(word => word && !IGNORED_WORDS.includes(word));
    }

    resultItems.forEach(item => {
        // Find the parent title from <p class="RelDocTitle">
        const relDocTitleElem = item.querySelector('p.RelDocTitle');
        let parentTitleRaw = relDocTitleElem ? relDocTitleElem.textContent.trim() : null;
        let foundSection = null;
    
        if (parentTitleRaw) {
            // Special case: Changelog or Release Notes always go to Release Notes section
            if (/changelog|release notes/i.test(parentTitleRaw)) {
                foundSection = "Release Notes";
            } else {
                // Split on line breaks and colons, trim each part, and try to match
                const possibleTitles = parentTitleRaw
                    .split(/[\n\r:]+/)
                    .map(s => s.trim())
                    .filter(Boolean);
    
                let bestScore = 0;
                let bestSection = null;
    
                for (const possibleTitle of possibleTitles) {
                    const parentTokens = tokenizeTitle(possibleTitle);
    
                    for (const [docTitle, section] of Object.entries(sectionMap)) {
                        const docTokens = tokenizeTitle(docTitle);
                        // Count overlap
                        const overlap = parentTokens.filter(token => docTokens.includes(token));
                        if (overlap.length > bestScore) {
                            bestScore = overlap.length;
                            bestSection = section;
                        }
                    }
                }
                foundSection = bestSection;
            }
        }
    
        const section = foundSection ? foundSection : otherSection;
        if (!grouped[section]) grouped[section] = [];
        grouped[section].push(item);
    });

    // 4. Clear and re-render grouped results with section headers
    resultsDiv.innerHTML = '';
    Object.keys(grouped).forEach(section => {
        // Create a container for each section
        const sectionContainer = document.createElement('div');
        sectionContainer.className = 'results-section-container';

        // Section header (clickable for expand/collapse)
        const header = document.createElement('h3');
        header.textContent = section;
        header.className = 'results-section-header collapsible-header';
        header.style.cursor = 'pointer';

        // Section content (folded by default)
        const content = document.createElement('div');
        content.className = 'results-section-content';
        content.style.display = 'none'; // collapsed by default

        // Add results to content
        grouped[section].forEach(item => {
            content.appendChild(item);
        });

        // Toggle expand/collapse on header click
        header.addEventListener('click', function () {
            const expanded = content.style.display !== 'none';
            content.style.display = expanded ? 'none' : '';
            header.classList.toggle('expanded', !expanded);
        });        

        sectionContainer.appendChild(header);
        sectionContainer.appendChild(content);
        resultsDiv.appendChild(sectionContainer);
    });

}

// Function to show the custom modal
function showCustomModal() {
    const modal = document.getElementById('customModal');
    const timerBar = document.getElementById('timerBar');
    modal.style.display = 'block';
    timerBar.style.width = '100%';

    let width = 100;
    const interval = setInterval(() => {
        width -= 2; // Decrease width by 2% every 100ms
        timerBar.style.width = width + '%';
        if (width <= 0) {
            clearInterval(interval);
            modal.style.display = 'none';
        }
    }, 100);
}