document.addEventListener('DOMContentLoaded', function () {
    const queryParams = new URLSearchParams(window.location.search);
    const query = queryParams.get('query');
    if (query) {
        document.getElementById('search').value = query;
        handleSearchFormSubmit(new Event('submit'));
    }
});

const fuseSearchOptions = {
    // Fuse.js library for fuzzy search
    keys: [
        { name: 'name', weight: 2 },
        { name: 'folder', weight: 1 },
        { name: 'searchTerms', weight: 1 }
    ],
    threshold: 0.2, // 0 = exact, 1 = chaotic
    findAllMatches: true
};

const handleSearchFormSubmit = (event) => {
    event.preventDefault();
    const query = document.getElementById('search').value.trim().toLowerCase();

    // Update URL with query parameter
    const url = new URL(window.location);
    url.searchParams.set('query', query);
    window.history.pushState({}, '', url);

    // Remove any existing search results
    const existingResults = document.querySelector('.search-results');
    if (existingResults) {
        existingResults.remove();
    }

    const fuse = new Fuse(foldersData, fuseSearchOptions);
    const fuseResults = fuse.search(query);
    const folderMatches = fuseResults.map(result => result.item);

    // Create the search results container
    const searchResults = document.createElement('div');
    searchResults.className = 'search-results';

    if (folderMatches.length > 0) {
        const resultsList = document.createElement('ul');
        resultsList.className = 'nhsuk-list';

        folderMatches.forEach(item => {
            const listItem = document.createElement('li');
            let guidelineType = '';

            if (item.folder.includes('/gdri/')) {
                guidelineType = 'gdri';
            } else if (item.folder.includes('/wb/')) {
                guidelineType = 'wb';

            } else {
                guidelineType = 'general';
            }

            listItem.className = `nhsuk-list-item--border nhsuk-u-padding-bottom-6 nhsuk-u-padding-top-6 guideline-type-${guidelineType}`;

            // Create the heading with link
            const heading = document.createElement('h2');
            heading.className = 'nhsuk-heading-m nhsuk-u-margin-bottom-2';
            const link = document.createElement('a');
            link.href = '../../../' + item.url;
            link.textContent = item.name;
            heading.appendChild(link);

            // Create the definition list for metadata
            const dl = document.createElement('dl');
            dl.className = 'nhsuk-u-margin-top-2 nhsuk-u-margin-bottom-1 nhsuk-body-s inline';

            // Guideline type section
            const guidelineDiv = document.createElement('div');
            guidelineDiv.className = 'nhsuk-u-margin-bottom-4';

            const guidelineDD = document.createElement('dd');
            guidelineDD.textContent = 'Guideline:';

            const guidelineDT = document.createElement('dt');
            const guidelineTag = document.createElement('span');
            
            // Determine guideline type based on URL
            if (guidelineType == 'gdri') {
                guidelineTag.textContent = 'Geographical index';
                guidelineTag.className = 'nhsuk-tag nhsuk-tag--green';
            } else if (guidelineType == 'wb') {
                guidelineTag.textContent = 'Whole blood';
                guidelineTag.className = 'nhsuk-tag nhsuk-tag--red';
            } else {
                guidelineTag.textContent = 'General';
                guidelineTag.className = 'nhsuk-tag';
            }

            guidelineDT.appendChild(guidelineTag);
            guidelineDiv.appendChild(guidelineDD);
            guidelineDiv.appendChild(guidelineDT);

            // JPAC Content Type section
            const contentTypeDiv = document.createElement('div');
            const contentTypeDD = document.createElement('dd');
            const contentTypeDT = document.createElement('dt');

            contentTypeDD.textContent = 'Content type:';
            contentTypeDD.style.minWidth = '110px';
            contentTypeDT.textContent = 'Web Page';
            contentTypeDiv.appendChild(contentTypeDD);
            contentTypeDiv.appendChild(contentTypeDT);

            // Search terms
            const searchTermsDiv = document.createElement('div');

            if (item.searchTerms && item.searchTerms.length) {    
                const searchTermsDD = document.createElement('dd');
                const searchTermsDT = document.createElement('dt');
                const searchTermsList = item.searchTerms.slice(0, 10).join(", ");
                const searchTermsString = searchTermsList.replaceAll('???', "'").replaceAll('&#x27;', "'")

                searchTermsDD.textContent = 'Search terms:';
                searchTermsDD.style.minWidth = '110px';
                searchTermsDT.textContent = searchTermsString + '...';
                searchTermsDiv.appendChild(searchTermsDD);
                searchTermsDiv.appendChild(searchTermsDT);
            }

            // Assemble the definition list
            dl.appendChild(guidelineDiv);
            dl.appendChild(contentTypeDiv);

            if (item.searchTerms && item.searchTerms.length) {
                dl.appendChild(searchTermsDiv);
            }

            // Assemble the list item
            listItem.appendChild(heading);
            listItem.appendChild(dl);

            resultsList.appendChild(listItem);
        });

        searchResults.appendChild(resultsList);
    } else {
        // No results found
        const noResults = document.createElement('p');
        noResults.className = 'nhsuk-body nhsuk-u-margin-top-4';
        noResults.textContent = `No results found for "${query}".`;
        searchResults.appendChild(noResults);
    }

    // Insert the results after the form
    const form = document.getElementById('search-form-filters');
    form.parentNode.insertBefore(searchResults, form.nextSibling);

    // Update the result count in the filter details
    resultCount();
};

const resultCount = () => {
    const countSpan = document.querySelector('.search-result-count');
    const searchResults = document.querySelector('.search-results');
    const visibleItems = Array.from(searchResults.querySelectorAll('li')).filter(li => li.offsetParent !== null);

    if (visibleItems.length) {
        countSpan.textContent = `${visibleItems.length} Results`;
    }
    else {
        countSpan.textContent = '0 Results';
    }
}

const guidelinesFilter = () => {
    checkedGuidelines = []
    const checkboxes = document.querySelectorAll('input[name="jpac_guideline"]');
    const searchResults = document.querySelectorAll(`div.search-results li`);

    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            checkedGuidelines.push(checkbox.value);
        }
    });

    if (checkedGuidelines.length) {
        searchResults.forEach(sr => {
            sr.style.display = 'none';
        })


        checkedGuidelines.forEach(item => {
            const guidelines = document.querySelectorAll(`li.guideline-type-${item}`);

            guidelines.forEach(guideline => {
                guideline.style.display = 'block';
            })
        });
    }
    else {
        searchResults.forEach(sr => {
            sr.style.display = 'block';
        })
    }
};

const guidelinesSort = () => {
    const list = document.querySelector('.search-results ul');
    const items = Array.from(list.querySelectorAll('li'));
    const sortAlphabeticalRadio = document.querySelector('input#order_by_a_to_z');

    if (sortAlphabeticalRadio.checked) {
        items.sort((a, b) => {
            const textA = a.textContent.trim().toUpperCase();
            const textB = b.textContent.trim().toUpperCase();
            return textA.localeCompare(textB);
        });

        items.forEach(li => list.appendChild(li));
    }
    else {
        handleSearchFormSubmit(new Event('submit'));
    }
    
};

const handleFilteringAndSorting = (e) => {
    e.preventDefault();

    guidelinesSort();
    guidelinesFilter();
    resultCount();
};

const clearFilters = () => {
    // Clear all filters
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(checkbox => checkbox.checked = false);

    const radios = document.querySelectorAll('input[type="radio"]');
    radios.forEach(radio => {
        if (radio.id === 'order_by_relevance') {
            radio.checked = true;
        } else {
            radio.checked = false;
        }
    });

    // Re-submit the search form
    handleSearchFormSubmit(new Event('submit'));
};