import { athenaConfig, athenaConfigOptions } from '../../global/athena-config.js';
import { handleHtml, addNoResults, handleRenderSearchSuggestions, handleShowMoreLess    } from '../../global/helpers/athena-global-helper.js';
import { setProductPrice } from '../../global/helpers/athena-price-helper.js';
import { fetchAutocomplete } from '../ajax/ajax.js';
import didYouMean from "../../global/did-you-mean/did-you-mean.js";

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

/**
 * Show or Remove Sidebar based of the number of elements
 */
function handleShowSidebar() {

    //Handle Show Sidebar when Layout three
    if(athenaConfig.layoutType === 'athena-l3') {
        const leftSidebar = document.querySelector('.autocomplete-l3__left-sidebar-filters-container');
        const rightSidebar = document.querySelector('.autocomplete-l3__right_sidebar');
        const content = document.querySelector('.autocomplete-l3__content');

        if(rightSidebar) {
            if(rightSidebar.children.length === 0) {
                rightSidebar.classList?.add('athena-helper-hide');
                content.classList?.add('athena-custom-width-no-right-sidebar');
            }
        }

        if(leftSidebar) {
            if(leftSidebar.children.length === 0) {
                leftSidebar?.parentElement?.classList.add('athena-helper-hide');
                content.classList?.add('athena-custom-width-no-left-sidebar');
            }
        }
    }

    //Handle Show Sidebar when not layout three
    if(athenaConfig.layoutType !== 'athena-l3') {
        const leftContainer = document.querySelector('.athena-autocomplete__left-container');
        const searchAreaOverlay = document.querySelector('.searchareaOverlay');

        if(leftContainer.children.length === 0) {
            leftContainer?.classList.add('athena-helper-hide');
            searchAreaOverlay?.classList.add('athena-ac-right__as-main');
        } else {
            leftContainer?.classList.remove('athena-helper-hide');
            searchAreaOverlay?.classList.remove('athena-ac-right__as-main');
        }
    }
}

/**
 * Handle Recreate Inner Elements
 */
function handleRecreateInnerElements() {
    //Container Element Selected Based on the layout type selected
    const mainElement = document.querySelector('.athena-autocomplete__flex-container');
    const searchAutocomplete = document.querySelector('#search_autocomplete');

    searchAutocomplete.append(handleHtml(`
        <div class="product-info-sidebar-autocomplete" id="product-info-sidebar-autocomplete">
            <div class="product-info-close-button-autocomplete"></div>
            <div class="product-info-content-autocomplete"></div>
        </div>
    `, '.product-info-sidebar-autocomplete'));
    mainElement.prepend(handleHtml(`<div class="athena-autocomplete__left-container"></div>`, '.athena-autocomplete__left-container'));
    mainElement.append(handleHtml(`<div class="athena-autocomplete__right-container"></div>`, '.athena-autocomplete__right-container'));
}

/**
 * Remove Search Tabs with Response Count of 0
 *
 * @param response
 */
function handleSearchTabsCount(response) {
    if(!response) {
        return;
    }

    const count = response.count;
    const preselected = response.preselected;
    const checkAllCount = Object.values(count).every(item => item === 0);

    const searchTabs = document.querySelectorAll('.athena-tab');
    searchTabs.forEach(searchTab => {

        //If in response all counts are 0 don`t display anything
        if(checkAllCount) {
            searchTab?.classList.remove('show-search-tabs');
            searchTab?.classList.add('athena-helper-hide');
            return;
        }

        //Check weather to show or hide search tabs
        for (const countKey in count) {
            const value = count[countKey];

            if(value === 0) {
                if(searchTab?.classList[1]?.includes(countKey)) {
                    searchTab?.classList.add('athena-helper-hide');
                }
            } else {
                if(searchTab?.classList[1]?.includes(countKey)) {
                    searchTab?.classList.remove('athena-helper-hide');
                }
            }
        }
    });

    //Show preselected values
    if(!checkAllCount) {
        const preselectedElement = document.querySelector(`.athena-tabs-${preselected}`);
        preselectedElement?.classList.add('athena-helper-show');

        const preselectedElementInput = document.querySelector(`.athena-tabs-radio-${preselected}`);
        if(preselectedElementInput) preselectedElementInput.checked = 'checked';
    }
}

/**
 * Creating Top Banner Function
 *
 * @param value
 * @param from
 */
function createTopBanner(value, from) {
    const mainElement = document.querySelector(`${from === 'athena-l3' ? '.autocomplete-l3__flex-container' : '.athena-autocomplete'}`);
    const parentElement = handleHtml(`
        <div class="athena athena-autocomplete__section athena-autocomplete__section-banner athena-autocomplete__section-banner-top" id="banner_top"></div>
    `, '#banner_top');

    for (const valueKey in value) {
        const banners = value[valueKey];
        parentElement.prepend(handleHtml(`<span>${banners.html}</span>`, 'span'));
    }

    Array.from(parentElement.children).forEach(child => child?.classList.add('autocomplete__top-banner-p'));
    mainElement.prepend(parentElement);
}

/**
 * Creating Bottom Banner Function
 *
 * @param value
 * @param from
 */
function createBottomBanner(value, from) {
    const mainElement = document.querySelector(`${from === 'athena-l3' ? '.autocomplete-l3__flex-container' : '.athena-autocomplete'}`);
    const parentElement = handleHtml(`
        <div class="athena athena-autocomplete__section athena-autocomplete__section-banner athena-autocomplete__section-banner-bottom" id="banner_bottom"></div>
    `, '#banner_bottom');

    for (const valueKey in value) {
        const banners = value[valueKey];
        parentElement.prepend(handleHtml(`<span>${banners.html}</span>`, 'span'));
    }

    Array.from(parentElement.children).forEach(child => child?.classList.add('autocomplete__bottom-banner-p'));
    mainElement.append(parentElement);
}

function handleRedirectSearchSections(elementSelector) {
    const section = document.querySelector(`${elementSelector}`);

    if(!section) {
        return;
    }

    Array.from(section.children).forEach(child => {
        if(!child) {
            return;
        }

        const redirectSearchSuggestions = (
            event,
            openInNewTab = false
        ) =>
        {
            event.preventDefault();

            let title = event.target.getAttribute('title') || '';
            if(!title) {
                title = event.target.parentElement.getAttribute('title') || '';
            }

            if(!title) {
                return;
            }

            const url = `${athenaConfig.formUrl}?q=` + encodeURIComponent(title.toLowerCase());
            if(openInNewTab) {
                window.open(url, '_blank');
                return;
            }

            window.location.href = url;
        };

        child.addEventListener('click', (event) => {
            redirectSearchSuggestions(event);
        });

        child.addEventListener('mousedown', (event) => {
            if (event.button === 1) {
                redirectSearchSuggestions(event, true);
            }
        });
    });
}

/**
 * Create Search Tab
 *
 * @param item
 */
function createSearchTab(item) {

    const mainElement = document.querySelector('.athena-search-tabs');

    let checked = '';
    item.checked ? checked = 'checked' : checked = '';

    mainElement.append(
        handleHtml(`
            <div 
                class="athena-tab athena-tabs-${item.value} athena-tabs-category-${item.value}" 
                id="${item.title}"
            >
                <input 
                    type="radio" 
                    name="athena_tabs" 
                    id="${item.title}" 
                    class="athena-tabs-radio athena-tabs-radio-${item.value}" 
                    value="${item.value}" 
                    ${checked}
                />
                <label for="${item.title}">${item.title}</label>
            </div>
        `, `.athena-tabs-${item.value}`)
    );

    //Search Tab Click
    searchTabClick(item);
}

/**
 * Search Tab Function
 *
 * @param item
 */
function searchTabClick(item) {
    //Add Event Listener On Search Tabs
    const searchTabs = document.querySelector(`.athena-tabs-${item.value}`);

    searchTabs.addEventListener('click', (event) => {
        const currentInput = event.currentTarget.children[0];
        const value = document.querySelector('#search').value;
        currentInput.checked = 'checked';

        fetchAutocomplete(value);
    });
}

/**
 * Handle Search Tabs Function
 *
 * @param from
 */
function handleSearchTabs(from = null) {
    const mainElement = document.querySelector('.athena-autocomplete__section-product');

    if(mainElement) {
        mainElement.prepend(handleHtml(`<div class="athena-search-tabs-container"><div id="athena-search-tabs" class="athena-search-tabs"></div></div>`, '.athena-search-tabs-container'));

        //Creating Search Tabs
        const searchTabsObject = athenaConfigOptions.searchTabsDataObject;
        searchTabsObject.forEach(searchTab => {
            createSearchTab(searchTab);
        });

        const searchTabs = document.querySelector('.athena-search-tabs');
        const cases = {
            'first-click': () => {
                if(searchTabs?.classList.contains('show-search-tabs'))
                    searchTabs?.classList.remove('show-search-tabs');

                searchTabs?.classList.add('athena-helper-hide');
            },
            'autocomplete': () => {
                if(searchTabs?.classList.contains('athena-helper-hide'))
                    searchTabs?.classList.remove('athena-helper-hide');

                searchTabs?.classList.add('show-search-tabs');
            },
            'athena-l3': () => {
                if(searchTabs?.classList.contains('show-search-tabs'))
                    searchTabs?.classList.remove('show-search-tabs');

                searchTabs?.classList.add('athena-helper-hide');
            }
        }

        //Check witch case it is
        cases[from]();
    }
}

/**
 * Add Classes to Banners
 * To prevent close on click
 */
function addClassesToBanners() {
    const banners = document.querySelectorAll('.athena-autocomplete__section-banner p');
    banners.forEach(banner => {
        if(!banner?.classList.contains('athena-autocomplete__section-banner-p')) {
            banner?.classList.add('athena-autocomplete__section-banner-p');
        }
    });
}


/**
 * Handle Response for Layout Grid and List
 *
 * @param response
 * @param from
 */
export function handleResponseData(response, from) {

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

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

    const searchForClickProduct = athenaConfigOptions.searchForClickProduct;
    const promises = [];

    //Recreate Elements
    handleRecreateInnerElements();

    if(from === 'first-click') {
        handleRenderSearchSuggestions(null, null, true);
        athenaConfigOptions.searchForm?.setAttribute('true-autocomplete-text', '');
    }

    Object.entries(response).forEach((res)  => {
        //Generating Response key and value;
        const responseKey = res[0];
        const value = res[1];

        //Set True Autocomplete Text on Autocomplete
        if(
            responseKey === 'true_autocomplete_keyword' && from === 'autocomplete' ||
            responseKey === 'true_autocomplete_keyword' && from === 'athena-l3'
        ) {
            handleRenderSearchSuggestions(value ? value : '', document.querySelector('#search').value);
            athenaConfigOptions.searchForm?.setAttribute('true-autocomplete-text', value ? value : '');
        }
    
        const promise = new Promise(resolve => {
                if(value) {
                    Object.entries(value).forEach(valueData => {
                        const key = valueData[0];
                        const data = valueData[1];

                        if(
                            key === 'product' &&
                            data.items.length === 0 &&
                            from !== 'athena-l3'
                        ) {
                            athenaConfigOptions.showNoItemsMessage = true;
                        } else if(
                            key === 'product' &&
                            data.items.length > 0 &&
                            from !== 'athena-l3'
                        ) {
                            athenaConfigOptions.showNoItemsMessage = false;
                        }

                        if (data.items) {

                            if (data.items.length > 0) {

                                let title = data.title;
                                let items = data.items;

                                //Container Element Selected Based on the layout type selected
                                const mainElement = athenaConfig.layoutType === 'athena-l3' && from === 'athena-l3' ?
                                    document.querySelector('.autocomplete-l3__right_sidebar') :
                                    document.querySelector(`.athena-autocomplete__flex-container ${key === 'product' ?
                                        '.athena-autocomplete__right-container' :
                                        '.athena-autocomplete__left-container'
                                    }`);

                                if(from === 'athena-l3' && key === 'product') {
                                    return;
                                } else {
                                    if(data.type === 'section_b'){
                                        mainElement.append(
                                            handleHtml(`
                                            <div class="${from === 'athena-l3' ? 'autocomplete-l3__section ': ''}athena athena-autocomplete__section athena-autocomplete__section-${key}${items.length > athenaConfigOptions.showMoreCutoffItemsAutocompleteBrands ? '': ' athena-autocomplete__section-no-cutoff'}">
                                                <div class="athena-autocomplete__header" id="${key}">
                                                    <h4>${title}</h4>
                                                </div>
                                                <div class="athena-autocomplete__container-${key}"></div>
                                                ${key !== 'product' && items.length > athenaConfigOptions.showMoreCutoffItemsAutocompleteBrands ? `
                                                    <div class="athena-cutoff__container athena-cutoff-autocomplete">
                                                        <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>
                                                ` : ``}
                                            </div> 
                                        `, `.athena-autocomplete__section-${key}`)
                                        );
                                    }else{
                                        mainElement.append(
                                            handleHtml(`
                                            <div class="${from === 'athena-l3' ? 'autocomplete-l3__section ': ''}athena athena-autocomplete__section athena-autocomplete__section-${key}${items.length > athenaConfigOptions.showMoreCutoffItemsAutocomplete ? '': ' athena-autocomplete__section-no-cutoff'}">
                                                <div class="athena-autocomplete__header" id="${key}">
                                                    <h4>${title}</h4>
                                                </div>
                                                <div class="athena-autocomplete__container-${key}"></div>
                                                ${key !== 'product' && items.length > athenaConfigOptions.showMoreCutoffItemsAutocomplete ? `
                                                    <div class="athena-cutoff__container athena-cutoff-autocomplete">
                                                        <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>
                                                ` : ``}
                                            </div> 
                                        `, `.athena-autocomplete__section-${key}`)
                                        );
                                    }
                                }

                                let trackSelectorClass = '';

                                if (key === 'product') {
                                    trackSelectorClass = 'athena-product-item';
                                    const athenaAutocomplete = document.querySelector('.athena-search-autocomplete:first-of-type');
                                    !items ? athenaAutocomplete?.classList.add('no-product-content') : athenaAutocomplete?.classList.remove('no-product-content');
                                }

                                if (items.length > 0) {

                                    const sectionElement = document.querySelector(`.athena-autocomplete__container-${key}`);

                                    items.forEach(item => {
                                        //Setting Price for Products
                                        const priceElement = setProductPrice(key, item);

                                        sectionElement.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-${key} ${trackSelectorClass}"
                                                        ${item.link ? `
                                                            href="${item.link}"
                                                        ` : ''}
                                                    >
                                                        <div 
                                                            class="athena-autocomplete__parent athena-autocomplete__parent-${key}" 
                                                            data-name-${suffixArea}="${item.name}" 
                                                            data-type-${suffixArea}="${key}" 
                                                            ${item.id ? `data-id-${suffixArea}="${item.id}"` : ''}
                                                            data-url-${suffixArea}="${item.link}"
                                                        >
                                                            <div class="athena-autocomplete__child-top athena-autocomplete__child-top-${key}">
                                                                ${item.image ? `
                                                                    <img 
                                                                        class="athena-autocomplete__image athena-autocomplete__image-${key}" 
                                                                        src="${item.image}" 
                                                                        alt="${item.name}"
                                                                    />
                                                                   
                                                                    <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-${key}">
                                                                <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-${key}`)
                                        );
                                    });

                                }
                            }
                        }
                    });
                }
                //Resolving Promise
                resolve();
                //Push to Promise Array
                promises.push(promise);
        });

        Promise.all(promises)
            .then(() => {
                //Create Top Banner
                if(responseKey === 'banners' && value.top) {
                    createTopBanner(value.top, from);
                }

                //Create Bottom Banner
                if(responseKey === 'banners' && value.bottom) {
                    createBottomBanner(value.bottom, from);
                }
        });
    });

    //Handle Search Tabs Functionality
    handleSearchTabs(from);

    if(athenaConfig.layoutType !== 'athena-l3') handleSearchTabsCount(response.tabs);

    //Handle Show Sidebar Based on the Elements Rendered
    handleShowSidebar();

    //Add Classes To Banners
    addClassesToBanners();

    //Handle Redirect Recent Searches Section
    handleRedirectSearchSections('.athena-autocomplete__container-recent_searches');

    //Handle Redirect Popular Searches Section
    handleRedirectSearchSections('.athena-autocomplete__container-popular');

    //Add No Results
    addNoResults('.athena-autocomplete__container-product');

    //Handle Show More
    handleShowMoreLess(
        '.athena-autocomplete__section',
        '.athena-cutoff-autocomplete',
        'autocomplete'
    );

    //Handle Did you mean
    didYouMean(
        response?.did_you_mean,
        document.querySelector('.athena-autocomplete__wrapper') ?? null,
        from
    );
}

