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 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 folderMatches = foldersData.filter(item =>
        item.name.toLowerCase().includes(query) ||
        item.folder.toLowerCase().includes(query)
    );

    // 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';

            // 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 contentTypeDDLabel = document.createElement('dd');
            contentTypeDDLabel.className = 'nhsuk-u-font-weight-bold';
            contentTypeDDLabel.textContent = 'JPAC Content Type:';

            const contentTypeDT = document.createElement('dt');
            contentTypeDT.textContent = 'Web Page';

            contentTypeDiv.appendChild(contentTypeDDLabel);
            contentTypeDiv.appendChild(contentTypeDT);

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

            // 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}". Try searching for terms like "red book", "malaria", "bone marrow", "a to z", etc.`;
        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'));
};