import { athenaConfig, athenaConfigOptions } from '../../global/athena-config.js';
import { athenaFetchApi } from '../../global/athena-fetch-api.js';
import {
    handleHtml,
    refreshElements,
    addLoaderAutocompleteInfinite,
    removeLoaderInfiniteAutocomplete,
    addLoaderAutocomplete,
    removeLoaderAutocomplete,
    addNoResults,
    handleShowMoreLess,
    delay
} from '../../global/helpers/athena-global-helper.js';
import { refreshButtonPositions, refreshRangeIndicator } from '../../global/om-range-slider/athena-om-range-slider-refresh.js';
import { OmRangeSlider } from '../../global/om-range-slider/om-range-slider.js';
import { handleResponseData } from './autocomplete-response.js';
import { setProductPrice } from '../../global/helpers/athena-price-helper.js';
import { handleMobileLayoutThree } from './autocomplete-l3-mobile-response.js';
import filterSearch from '../../global/helpers/filter-search.js';
import lazyLoading from '../../global/helpers/lazy-loading.js';

//Setting and Destruct suffixArea
athenaConfigOptions.suffixArea = 'autocomplete';
const { suffixArea } = athenaConfigOptions;

/**
 * Handle Response data for layout three
 *
 * @param data
 */
export function handleResponseDataLayoutThree(data) {

    const response = data.data;

    if(response.sections) {
        if(response.sections.popular) {
            let initPagePopularKeywords = [];
            response.sections.popular.items.forEach(item => {
                initPagePopularKeywords.push(item.name_urlencoded);
            });

            localStorage.setItem('initPageKeywords', JSON.stringify(initPagePopularKeywords));
        }
    }

    //Products
    const products = response.products;
    //Getting filters, active_filters, and collection_price
    const {
        filters,
        active_filters,
        collection_price
    } = products;
    //Appending Main Container To Athena Flex
    handleDivStructureLayoutThree();
    //Add Main content
    handleMainContent(products);
    //Handle Infinite Scroll
    athenaConfigOptions.layoutThreeInfiniteScrollPager = products?.pager.filter(pager => pager.type === 'next')[0];
    handleInfiniteScroll();
    //Handle Filters
    handleFilters(
        filters,
        active_filters,
        collection_price
    );

    numberOfActiveFilters();
    //Handle Show More
    handleShowMoreLess(
        '.autocomplete-l3__filter-children',
        '.athena-cutoff__container-filters-layout-3',
        'layout-3'
    );
    //Handle Category Response
    handleResponseData(response, 'athena-l3');
    //Toggle filters functionality
    handleToggleFilters();
    //Adding filters
    handleAddFilters('autocomplete-l3__ajax-add');
    //Removing filters
    handleRemoveFilters('autocomplete-l3__ajax-remove');
    //Closing Active Filters
    handleCloseActiveFilters();
    //Open Active Filters
    handleOpenActiveFilters();
    //Lazy Loading Images
    lazyLoading('.athena-autocomplete__image-product');
}

/**
 * Create Initial Elements for Layout Three
 */
function handleDivStructureLayoutThree() {
    const athenaFlexAc = document.querySelector('.athena-autocomplete__flex-container');
    athenaFlexAc.prepend(
        handleHtml(`
            <div class="autocomplete-l3__flex-container">
                <div class="autocomplete-l3__left_sidebar">
                    <div class="autocomplete-l3__left-sidebar-filters-container"></div>
                </div>
                <div class="autocomplete-l3__content">
                    <div class="autocomplete-l3__remove-filters"></div>
                </div>
                <div class="autocomplete-l3__right_sidebar"></div>
            </div>
        `, '.autocomplete-l3__flex-container')
    );
}

/**
 * Handle Content
 *
 * @param products
 */
function handleMainContent(products) {
    if(products.url) {
        window.location.href = products.url;
        return false;
    } else {
        //Appending Container to Main Element
        const productContainer = handleHtml(`<div class="autocomplete-l3__product-container" id="product-container"></div>`, `#product-container`);
        const content = document.querySelector('.autocomplete-l3__content');
        content.append(productContainer);

        //Prepending Header
        content.prepend(
            handleHtml(`
               <div class="athena-autocomplete__header" id="products">
                    <div class="athena-autocomplete__header-product">
                       <h4>Products</h4>
                       ${products?.amounts?.total ? `<span class="athena-autocomplete__header-total-items">Total Items: ${new Intl.NumberFormat().format(products?.amounts.total)}</span>` : ``}
                    </div>
                    <div class="athena-autocomplete-view-all">
                        <button>View All</button>
                    </div>
               </div>
            `, '#products')
        );

        document.querySelector('.athena-autocomplete-view-all button')?.addEventListener('click', function(){
            document.querySelector('.search-icon__autocomplete')?.click();
        });

        //Add Products
        handleAppendProductsLayoutThree(products?.results, productContainer);
    }
}

/**
 * Handle Append Product Elements
 *
 * @param products
 * @param productContainer
 */
function handleAppendProductsLayoutThree(products, productContainer) {
    if(products.length > 0) {
        products.forEach((item, key) => {

            //Setting Price for Products
            const priceElement = setProductPrice('product', item);
            //Search for Click Product
            const searchForClickProduct = athenaConfigOptions.searchForClickProduct;
            
            productContainer.append(
                handleHtml(`
                    <a 
                        ${item.id ? `data-element-id-${suffixArea}="${item.id}"` : ''}
                        ${item.sku ? `data-element-sku-${suffixArea}="${item.sku}"` : ''}
                        data-terms-${suffixArea}="${searchForClickProduct}"
                        class="athena-autocomplete__link athena-autocomplete__link-product athena-product-item"
                        ${item.link ? `
                            href="${item.link}"
                        ` : ''}
                    >
                        <div 
                            class="athena-autocomplete__parent athena-autocomplete__parent-product " 
                            data-name-${suffixArea}="${item.name}" 
                            data-type-${suffixArea}="product" 
                            ${item.id ? `data-id-${suffixArea}="${item.id}"` : ''}
                            data-url-${suffixArea}="${item.link}"
                        >
                        
                            <div class="athena-autocomplete__child-top athena-autocomplete__child-top-product">
                                ${item.image ? `
                                    <div class="athena-spinner-loader athena-spinner-loader-absolute"></div>
                                    <img 
                                        class="athena-autocomplete__image athena-autocomplete__image-product" 
                                        data-src="${item.image}" 
                                        alt="${item.name}"
                                        style="visibility: hidden"
                                    />
                                    <span class="find-visual-similar">Find similar style</span>
                                ` : '' }
                                
                                <!-- Discount Percentage -->
                                ${item.price && item.price.discount_percentage !== 0 && typeof item.price.discount_percentage !== 'undefined' ? `
                                    <div class="athena-autocomplete__discount-div">
                                        -${item.price.discount_percentage}%
                                    </div>
                                ` : ''}   
                            </div>   
                            
                            <div class="athena-autocomplete__child-bottom athena-autocomplete__child-bottom-product">
                                <span class="athena-autocomplete__name athena-autocomplete__name-${key}" title="${item.name}">
                                    ${item.highlighted_name ? item.highlighted_name : item.name}
                                </span>
                                
                                ${priceElement ? priceElement : ''}
                            </div> 
                        </div>
                    </a>
                    `, `.athena-autocomplete__link-product`)
            )
        });


        const container = document.querySelector('.athena-autocomplete__flex-container');
        if(!container.querySelector('.autocomplete-l3__infinite-scroll')) {
            container?.append(handleHtml(`
                <div class="autocomplete-l3__infinite-scroll" style="width: 100%; height: 5px;"></div>
            `, '.autocomplete-l3__infinite-scroll'));
        }
    } else {
        athenaConfigOptions.showNoItemsMessage = true;
    }
}

function recreateObserver(element, callback, previousObserver = null)
{
    if(previousObserver) previousObserver.unobserve(element);

    const bottomInfiniteObserver = new IntersectionObserver(callback, { threshold: 0 });
    bottomInfiniteObserver.observe(element);

    return bottomInfiniteObserver;
}

/**
 * Infinite Scroll Handle Function
 */
function handleInfiniteScroll()
{
    const autocompleteL3InfiniteElement = document.querySelector('.autocomplete-l3__infinite-scroll');
    if(!autocompleteL3InfiniteElement) return;

    recreateObserver(autocompleteL3InfiniteElement, infiniteScrollHelper);

    function infiniteScrollHelper(entries)
    {
        const entry = entries[0];
        const l3Content = document.querySelector('.autocomplete-l3__content');

        if(entry.isIntersecting && !l3Content?.classList.contains('autocomplete-l3__hide')) {
            if(!athenaConfigOptions.layoutThreeInfiniteScrollPager) {
                addNoResults('.autocomplete-l3__product-container');
                return;
            }

            nextPage(athenaConfigOptions.layoutThreeInfiniteScrollPager?.url_params)
                .then(response => {
                    const pager = response?.
                        data?.
                        products?.
                        pager || null;

                    athenaConfigOptions.layoutThreeInfiniteScrollPager = pager ?
                        pager.filter(pager => pager.type === 'next')[0] :
                        null;
                });
        }
    }
}

/**
 * Determinate what filter to stay active after choosing filter
 *
 * @param activeFilters
 * @returns {*[]}
 */
function handleSaveActiveFilters(activeFilters) {
    const array = [];

    activeFilters.forEach((activeFilter, index) => {
        array[index] = activeFilter.type === 'category1' ||
        activeFilter.type === 'category2' ||
        activeFilter.type === 'category3' ?
            'category' :
            activeFilter.type;

        athenaConfigOptions.activeFiltersArray = array.filter((item, index) => array.indexOf(item) === index);
    });
}

/**
 * Handle Close Filters Function
 */
function handleCloseActiveFilters() {
    const removeFilters = document.querySelectorAll('.autocomplete-l3__ajax-remove');

    removeFilters.forEach(removeFilter => {
        removeFilter.addEventListener('click', (event) => {
            //Get filter type
            let filterType = event.target.getAttribute('data-filter-remove-type');
            filterType = filterType === 'remove-all' ? null : filterType;

            //Filter Out Array
            if(filterType) {
                athenaConfigOptions.activeFiltersArray = athenaConfigOptions.activeFiltersArray.filter(item => item !== filterType);
                if (athenaConfigOptions.activeFiltersArray.length === 0) {
                    athenaConfigOptions.activeFiltersArray = null;
                }
            } else {
                athenaConfigOptions.activeFiltersArray = null;
            }
        });
    });
}

/**
 * Handle Open Filters for Layout Three
 */
function handleOpenActiveFilters() {
    const filters = athenaConfigOptions.activeFiltersArray;
    if(filters) {
        filters.forEach(filter => {
            const filterParent = document.querySelector(`[data-filter-type="${filter}"]`);
            if(filterParent) {
                const filterChildren = filterParent.children;
                filterChildren[0]?.classList.remove('inactive');
                filterChildren[0]?.classList.add('active');
                filterChildren[1]?.classList.remove('inactive');
                filterChildren[1]?.classList.add('active');
                filterChildren[1]?.classList.add('athena-helper-show');

                //Refreshing if price-range filter is clicked
                if(filterParent.getAttribute('data-filter-type') === 'price') {
                    if(filterParent.children[0]?.classList.contains('active')) {
                        refreshButtonPositions();
                        refreshRangeIndicator();
                    } else {
                        setTimeout(() => {
                            refreshButtonPositions();
                            refreshRangeIndicator();
                        }, 100);
                    }
                }
            }

        });
    }
}

function handlePriceRange() {
    OmRangeSlider.init();
    const priceRange = document.querySelector('#price-range-slider');

    if(priceRange) {
        const startButton = document.querySelector('.om-sliderrange-button-start');
        const endButton = document.querySelector('.om-sliderrange-button-end');

        let priceFrom = '';
        let priceTo = '';

        let enableRequest = false;

        document.addEventListener("rangechange", event => {
            priceFrom = event.detail[0];
            priceTo = event.detail[1];
        });

        startButton?.addEventListener('mousedown', () => {
            enableRequest = true;
        });

        startButton?.addEventListener('touchstart', () => {
            enableRequest = true;
        },{ passive: true });

        endButton?.addEventListener('mousedown', () => {
            enableRequest = true;
        });

        endButton?.addEventListener('touchstart', () => {
            enableRequest = true;
        }, { passive: true });

        window.addEventListener('touchend', () => {
            if(enableRequest) {
                if(isNaN(priceFrom) || isNaN(priceTo)) {
                    return;
                }

                const value = document.querySelector('#search')?.value;
                handlePrepareUrlPriceRange(value);

                enableRequest = false;
            }
        }, { passive: true });

        window.addEventListener('mouseup', () => {
            if(enableRequest) {
                if(isNaN(priceFrom) || isNaN(priceTo)) {
                    return;
                }

                const value = document.querySelector('#search').value;
                handlePrepareUrlPriceRange(value);

                enableRequest = false;
            }
        });

        /**
         * Prepare Url
         *
         * @param value
         */
        function handlePrepareUrlPriceRange(value) {
            priceFrom = parseFloat(priceFrom).toFixed(2);
            priceTo = parseFloat(priceTo).toFixed(2);

            if(priceFrom === 'NaN' && priceTo === 'NaN') {
                return;
            }

            //Forming query
            let queryOptions = athenaConfigOptions.queryOptions['query'];
            if(typeof queryOptions === 'undefined') {
                queryOptions = {
                    'query': {
                        'q': value,
                        'price': `${priceFrom}-${priceTo}`
                    }
                }

                athenaConfigOptions.queryOptions = queryOptions;
                queryOptions = queryOptions['query'];
            } else {
                queryOptions['price'] = `${priceFrom}-${priceTo}`;
                athenaConfigOptions.queryOptions['query'] = queryOptions;
            }

            fetchFilteredDataLayoutThree(queryOptions);
        }
    }
}

/**
 * Handle Filters Function
 *
 * @param filters
 * @param activeFilters
 * @param collectionPrice
 */
function handleFilters(
    filters,
    activeFilters,
    collectionPrice
) {
    if(activeFilters.length > 0) {
        const autocompleteContainer = document.querySelector('.autocomplete-l3__content');
        autocompleteContainer.prepend(
            handleHtml(`
                  <div class="autocomplete-l3__filters-container-parent">
                     <div class="autocomplete-l3__filters-container"></div>
                  </div>
            `, '.autocomplete-l3__filters-container-parent')
        );

        activeFilters.forEach(activeFilter => {
            const urlParams = encodeURIComponent(JSON.stringify(activeFilter.url_params));
            //Get Filter Type
            const activeFilterType =
                activeFilter.type === 'category1' ||
                activeFilter.type === 'category2' ||
                activeFilter.type === 'category3' ?
                    'category' :
                    activeFilter.type;

            const autocompleteFilterContainer = document.querySelector('.autocomplete-l3__filters-container');
            autocompleteFilterContainer.prepend(
                handleHtml(`
                    <div 
                        data-value="${urlParams !== 'undefined' && urlParams}"
                        data-filter-remove-type="${activeFilterType}"
                        class="autocomplete-l3__ajax-remove"
                    >
                        <span 
                            class="autocomplete-l3__ajax-remove-span" 
                            data-filter-remove-type="${activeFilterType}"
                        >
                            ${activeFilter.name} : ${activeFilter.label}
                        </span>
                    </div>
                `, '.autocomplete-l3__ajax-remove')
            );
        });

        if(activeFilters.length > 1) {
            const val = document.querySelector('#search').value;
            const clearAllQuery = encodeURIComponent(`{"q":"${val}"}`);

            const autocompleteFilterContainer = document.querySelector('.autocomplete-l3__filters-container');
            autocompleteFilterContainer.prepend(
                handleHtml(`
                    <div
                        data-value="${clearAllQuery}"
                        data-filter-remove-type="remove-all"
                        class="autocomplete-l3__ajax-remove autocomplete-l3__ajax-remove-all"
                    >
                        <span 
                            class="autocomplete-l3__ajax-remove-span" 
                            data-filter-remove-type="remove-all"
                        >
                            Clear All
                        </span>
                    </div>
                `, '.autocomplete-l3__ajax-remove-all')
            );
        }

        //Save Active Filters in Global Array for later use
        handleSaveActiveFilters(activeFilters);

        //Adding max height when element has active filters
        const productContainer = document.querySelector('.autocomplete-l3__product-container');
        productContainer?.classList.add('athena-custom-max-height');
    }

    if(filters.length > 0) {
        //Appending Filter Header
        const leftSidebar = document.querySelector('.autocomplete-l3__left_sidebar');
        const leftSidebarContainer = document.querySelector('.autocomplete-l3__left-sidebar-filters-container');

        filters.forEach(filter => {
            if(filter.type !== 'price') {
                if(filter.array) {
                    //Get Filter Type
                    const filterType =
                        filter.type === 'category1' ||
                        filter.type === 'category2' ||
                        filter.type === 'category3' ?
                            'category' :
                            filter.type;

                    leftSidebarContainer.append(
                        handleHtml(`
                            <div class="autocomplete-l3__filters" data-filter-type="${filterType}">
                               <p class="autocomplete-l3__filter-title inactive">${filter.title}</p>
                               <div id="autocomplete-l3__filter-children-${filterType}" class="inactive autocomplete-l3__filter-children" style="display: none;">
                                   <div class="autocomplete-l3__filter-children-container"></div>
                               </div>
                            </div>
                        `, '.autocomplete-l3__filters')
                    );

                    filter.array.forEach(element => {
                        const urlParams = encodeURIComponent(JSON.stringify(element.url_params));

                        const filterParent = document.querySelector(`#autocomplete-l3__filter-children-${filterType} .autocomplete-l3__filter-children-container`);
                        filterParent?.append(
                            handleHtml(`
                                    <div
                                        data-value="${urlParams !== 'undefined' && urlParams}"
                                        data-search-value="${element.option_label}"
                                        class="autocomplete-l3__ajax-add ${element.selected ? 'selected-filter' : ''}"
                                    >
                                        ${element.hax_code !== null && element.type_id !== '0' ? `
                                            <div style="display: flex; align-items: center">
                                                <span class="autocomplete-l3__filter-color" style="display: block; width: 28px; height: 28px; margin-right: 6px; border: 1px solid #030329; border-radius: 4px; ${element.type_id === '1' ? `background: ${element.hax_code}` : `background: url(${element.hax_code})`}">
                                                </span>
                                                <span class="autocomplete-l3__filter-color-label autocomplete-l3__filter-span">${element.option_label}</span>
                                            </div>
                                            <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="autocomplete-l3__checkbox"/>
                                            <span class="checkmark"></span>
                                        `: `
                                            <span class="autocomplete-l3__filter-span">
                                                ${element.option_label}
                                            </span>   
                                            <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="autocomplete-l3__checkbox"/>
                                            <span class="checkmark"></span>
                                        `}
                                    </div>
                           `, '.autocomplete-l3__ajax-add')
                        );
                    });

                    filterSearch(
                        filter.type,
                        filter.array,
                        '.autocomplete-l3__left-sidebar-filters-container',
                        '.autocomplete-l3__filter-children',
                        ['.autocomplete-l3__filter-span'],
                        '.autocomplete-l3__ajax-add',
                        filter.title
                    );

                    const filterChildren = document.querySelectorAll('.autocomplete-l3__filter-children');
                    if (!filterChildren) {
                        return;
                    }

                    filterChildren.forEach(filterChild => {
                        const count = filterChild.querySelector('.autocomplete-l3__filter-children-container')?.children.length;
                        if(typeof count !== 'undefined') {


                            if(filterChild.closest('.autocomplete-l3__filters')?.getAttribute('data-filter-type') === 'velicina'){

                                if(count <= athenaConfigOptions.showMoreCutoffItemsSize) {
                                    return;
                                }

                                if (!filterChild?.querySelector('.athena-cutoff__container')) {
                                    filterChild?.append(
                                        handleHtml(`
                                        <div class="athena-cutoff__container athena-cutoff__container-filters-layout-3">
                                            <span class="athena-cutoff__button athena-cutoff__show-more-button athena-helper-show">${athenaConfigOptions.showMoreButtonName}</span>
                                            <span class="athena-cutoff__button athena-cutoff__show-less-button">${athenaConfigOptions.showLessButtonName}</span>
                                            <span class="icon-arrow"></span>
                                        </div>
                                    `, '.athena-cutoff__container')
                                    );
                                }

                            }else{
                                if(count <= athenaConfigOptions.showMoreCutoffItems) {
                                    return;
                                }

                                if (!filterChild?.querySelector('.athena-cutoff__container')) {
                                    filterChild?.append(
                                        handleHtml(`
                                        <div class="athena-cutoff__container athena-cutoff__container-filters-layout-3">
                                            <span class="athena-cutoff__button athena-cutoff__show-more-button athena-helper-show">${athenaConfigOptions.showMoreButtonName}</span>
                                            <span class="athena-cutoff__button athena-cutoff__show-less-button">${athenaConfigOptions.showLessButtonName}</span>
                                            <span class="icon-arrow"></span>
                                        </div>
                                    `, '.athena-cutoff__container')
                                    );
                                }

                            }

                        }
                    });

                }
            } else {
                leftSidebarContainer.append(
                    handleHtml(`
                        <div class="autocomplete-l3__filters" data-filter-type="price">
                           <p class="autocomplete-l3__filter-title inactive">${filter.title}</p>
                           <div id="autocomplete-l3__filter-children-price" class="inactive autocomplete-l3__filter-children" style="display: none;"></div>
                        </div>
                    `, '.autocomplete-l3__filters')
                );

                const filterParent = document.querySelector(`#autocomplete-l3__filter-children-${filter.type}`);

                if(collectionPrice.highest_price === 0 && collectionPrice.lowest_price === 0) {
                    const content = document.querySelector('.autocomplete-l3__content');

                    leftSidebar?.classList.add('athena-helper-hide');
                    content?.classList.add('athena-custom-width-full');
                }

                if(collectionPrice.highest_price === collectionPrice.lowest_price) {
                    document.querySelector('[data-filter-type="price"]')?.classList.add('athena-helper-hide');
                    return;
                }

                if(collectionPrice.highest_price > 0 && collectionPrice.lowest_price >= 0) {
                    filterParent.append(
                        handleHtml(`
                        <div class="autocomplete-l3__ajax-add autocomplete-l3__price_range">
                            <input
                                type="range"
                                multiple="multiple"
                                min="${collectionPrice.lowest_price}"
                                max="${collectionPrice.highest_price}"
                                unit="${athenaConfig.priceRangeUnit}"
                                unitPlacement="${athenaConfig.priceRangePlacement}"
                                value=""
                                id="price-range-slider"  
                                minAll="${collectionPrice.lowest_price_with_filters}"
                                maxAll="${collectionPrice.highest_price_with_filters}"
                            />
                        </div>
                `, '.autocomplete-l3__ajax-add')
                    );
                    //Price Range Handle
                    handlePriceRange();
                }
            }
        });
    }
}

function numberOfActiveFilters(){
    let selectedFiltersContainer = document.querySelectorAll('.autocomplete-l3__filters');
    if(selectedFiltersContainer.length){
        selectedFiltersContainer.forEach(function(element){

            let selectedNumber = 0;
            let selectedFilter = element.querySelectorAll('.autocomplete-l3__checkbox')
            if(selectedFilter.length){
                selectedFilter.forEach(function(elementInner){
                    if(elementInner.checked){
                        selectedNumber++;
                    }
                })
            }
            if(selectedNumber){
                element.closest('.autocomplete-l3__filters')?.querySelector('.autocomplete-l3__filter-title')?.append(
                    handleHtml(`
                        <span class="athena-active-filter-number">
                            (${selectedNumber})
                        </span>
                    `, '.athena-active-filter-number')
                );
            }
        })
    }

}

/**
 * Toggle Filters Function
 */
function handleToggleFilters() {
    const filters = document.querySelectorAll('.autocomplete-l3__filters');

    filters.forEach(filter => {
        filter.addEventListener('click', (event) => {
            const target = event.target;
            const filterType = event.currentTarget.getAttribute('data-filter-type');
            const filterParent = document.querySelector(`[data-filter-type="${filterType}"]`);

            if(target?.classList.contains('autocomplete-l3__filter-title')) {
                //Refreshing if price-range filter is clicked
                if(filterParent.getAttribute('data-filter-type') === 'price') {
                    setTimeout(() => {
                        refreshButtonPositions();
                        refreshRangeIndicator();
                    }, 100);
                }

                Array.from(filterParent.children).forEach((child, index) => {
                    if(child?.classList.contains('inactive')) {
                        child?.classList.remove('inactive');
                        child?.classList.add('active');
                        if(index !== 0) child?.classList.add('athena-helper-show');
                    } else {
                        child?.classList.remove('active');
                        child?.classList.add('inactive');
                        if(index !== 0) child?.classList.remove('athena-helper-show');
                    }
                });
            }
        });
    });
}

/**
 * Add Filters Fetch
 *
 * @param element
 */
function handleAddFilters(element) {
    handleFetchFilters(element);
}

/**
 * Remove Filters Fetch
 *
 * @param element
 */
function handleRemoveFilters(element) {
    handleFetchFilters(element);
}

/**
 * Handle Fetch Filters
 *
 * @param element
 */
function handleFetchFilters(element) {
    const filters = document.querySelectorAll(`.${element}`);

    filters.forEach(filter => {
        filter.addEventListener('click', (event) => {
            const queryOptions = JSON.parse(decodeURIComponent(event.currentTarget.getAttribute('data-value')));
            if(!queryOptions) {
                return;
            }

            athenaConfigOptions.queryOptions['query'] = queryOptions;
            fetchFilteredDataLayoutThree(queryOptions);
        });
    });
}

/**
 * Recreate Node Elements to Remove Event Listeners
 *
 * @param element
 * @param withChildren
 */
function recreateNode(element, withChildren) {
    const currentTopPosition = element.scrollTop;

    if (withChildren) {
        element.parentNode.replaceChild(element.cloneNode(true), element);
    } else {
        const newElement = element.cloneNode(false);
        while (element.hasChildNodes()) newElement.appendChild(element.firstChild);
        element.parentNode.replaceChild(newElement, element);
        newElement.scrollTop = currentTopPosition;
    }
}

/**
 * Show Next Page Infinite scroll
 *
 * @param queryOptions
 */
function nextPage(queryOptions) {
    //Activate Loader
    addLoaderAutocompleteInfinite();
    const backgroundOverlayAutocomplete = document.querySelector('.background-overlay-autocomplete');
    backgroundOverlayAutocomplete?.classList.add('autocomplete-overlay')

    //Forming Data Object
    const data = {
        'service': 'search/autocomplete',
        'athenaUid': athenaConfigOptions.athenaUid,
    }

    if(athenaConfig.isCustomerLoyalty) {
        data['customer_group_id'] = athenaConfigOptions.customerGroupID;
    }

    //Additional Queries
    for (const key in queryOptions) {
        if(key !== 'service') data[key] = queryOptions[key];
    }

    return athenaFetchApi(data, true)
        .then(response => {
            setTimeout(() => {
                //Getting Response products and container
                const data = response.data;
                const products = data.products;
                const productContainer = document.querySelector('.autocomplete-l3__product-container');
                //Appending Products
                handleAppendProductsLayoutThree(products.results, productContainer);

                const athenaLoader = document.querySelector('.athena-spinner-loader-infinite');
                document.querySelector('.background-overlay-autocomplete')?.classList.add('autocomplete-overlay');

                //Removing Loader and other elements
                athenaLoader?.remove();

                //Remove all event listeners before initialising infinite scroll again
                recreateNode(productContainer);

                removeLoaderInfiniteAutocomplete();
                backgroundOverlayAutocomplete?.classList.remove('autocomplete-overlay');

                //Lazy Loading Images
                lazyLoading('.athena-autocomplete__image-product');
            }, 300);

            return response;
        });
}

/**
 * Fetch Autocomplete For Filters
 *
 * @param queryOptions
 */
function fetchFilteredDataLayoutThree(queryOptions) {
    //Activate Spinner
    addLoaderAutocomplete();

    const backgroundOverlayAutocomplete = document.querySelector('.background-overlay-autocomplete')
    backgroundOverlayAutocomplete?.classList.add('autocomplete-overlay')

    let res = queryOptions['q'].replace('<>', '');
    athenaConfigOptions.searchForClickProduct += res + ',';

    //Forming Data Object
    const data = {
        'service': 'search/autocomplete',
        'athenaUid': athenaConfigOptions.athenaUid,
    }

    if(athenaConfig.isCustomerLoyalty) {
        data['customer_group_id'] = athenaConfigOptions.customerGroupID;
    }

    //Adding All query Options for data
    for (const key in queryOptions) {
        if(key !== 'service') data[key] = queryOptions[key];
    }

    athenaFetchApi(data, true)
        .then(response => {
            refreshElements();
            handleResponseDataLayoutThree(response);
            //Handle Mobile display for layout three
            handleMobileLayoutThree();
            //Deactivate Spinner
            backgroundOverlayAutocomplete?.classList.remove('autocomplete-overlay');
            //Remove Loader
            removeLoaderAutocomplete();
        });
}
