import { handleHtml } from '../../global/helpers/athena-global-helper.js';

/**
 * Reset Visual Filters Container
 */
function resetVisualFilters() {
    const visualFiltersContainer = document.querySelector('#visual-filters');

    if(visualFiltersContainer && visualFiltersContainer.hasChildNodes()) {
        while(visualFiltersContainer.hasChildNodes()) {
            visualFiltersContainer.removeChild(visualFiltersContainer.firstChild);
        }
    }
}

/**
 * Append Visual Filters
 *
 * @param visualFilters
 */
function appendVisualFilters(visualFilters) {
    //Reset Visual Filters before appending
    resetVisualFilters();
    let visualFiltersContainer =  document.querySelector('#visual-filters__container');

    //Visual Filters from Response
    const filtersArray = visualFilters.array ?? [];
    if(filtersArray.length > 0) {
        visualFiltersContainer?.classList.remove('hide-visual-search');
        //Appending Title
        const visualFiltersHeading = document.querySelector('#visual-filter__heading');
        visualFiltersHeading.innerText = `Visual Filters for ${visualFilters.title}`;

        const visualFiltersParent = document.querySelector('#visual-filters');
        filtersArray.forEach((filterArray, key) => {
            //Stringify URL params for visual filters
            const urlParams = JSON.stringify(filterArray.url_params);

            visualFiltersParent.append(
                handleHtml(`
                    <div class="${filterArray.selected ? 'visual-filter-item visual-filter-item-selected' : 'visual-filter-item'}">
                        <img 
                            src="${filterArray.visual_filter_image}"
                            class="visual-filter-image" 
                            alt="visual-filter-image"
                            data-value='${urlParams}'
                        />
                        <p class="visual-filter__paragraph">${filterArray.option_label}</p>
                        <div class="visual-filters__overlay" style="${filterArray.selected ? 'display: block;' : 'display: none;'}"></div>
                    </div>
                `, '.visual-filter-item')
            );
        });
    }else{
        visualFiltersContainer?.classList.add('hide-visual-search');
    }
}

//Exporting Visual Filters
export default appendVisualFilters;