import { athenaConfig, athenaConfigOptions } from '../global/athena-config.js';
import { searchSuggestions } from './features/search-suggestions.js';
import { handleMobileLayoutThree } from './renderer/autocomplete-l3-mobile-response.js';
import {
    handleHtml,
    setAthenaUid,
    getCookie,
    delay,
    hideVisualSimilarityBox,
    hideCategoryMenu,
    checkProductClick,
    detectSpecialCharacters,
    handleRenderSearchSuggestions,
} from '../global/helpers/athena-global-helper.js';

import { fetchFirstClick, fetchAutocomplete, fetchSearchTabs } from './ajax/ajax.js';
import { hideAutocompleteBox, removeCloseButton } from './helper/ajax-helper.js';
import { visualSimilaritySearch } from './features/visual-similarity-search/visual-similarity-search.js';
import { findVisuallySimilar } from '../search/find-visualy-similar/find-visualy-similar.js';

// Demo
import { scrollToTop } from '../demo/scroll-to-top.js';
import { hideForProduction } from '../demo/hide-for-production.js';
import { athenaStory } from '../demo/athena-story.js';
import { recommenderTabs } from '../demo/recommender-tabs.js';
import { stickyHeader } from  '../demo/sticky-header.js';
import { homePage } from  '../demo/home-page.js';
import categoryNavigation from '../demo/category-navigation.js';

import escapeButtonHandle from './features/escape-button-handle.js';
import SwipeEvents from '../global/helpers/swipe-events.js';
import VoiceRecognition from './features/voice-search/voice-search.js';

/**
 * Added Close Button for search terms
 */
export function addCloseButton()
{
    const searchContainer = document.querySelector('.close-search-btn');
    searchContainer.classList.add('delete-search-terms');

    const resetInputValue = () =>
    {
        const inputValue = document.querySelector('#search');
        inputValue.value = '';
        removeCloseButton();
        handleRenderSearchSuggestions(null, null, true);
    };

    searchContainer?.removeEventListener('click', resetInputValue);
    searchContainer?.addEventListener('click', resetInputValue);
}

function search(
    valueOnTab = null,
    isTriggeredSearch = false
)
{
    athenaConfig.sendAthenaRequest = false;
    let value = document.querySelector('#search').value;
    value = valueOnTab ? valueOnTab : value;
    // Add and
    value.length === 0 ? removeCloseButton() : addCloseButton();

    if(detectSpecialCharacters(value)) {
        return;
    }

    typeof value === 'undefined' || value.length === 0 ?
        fetchFirstClick() :
        !isTriggeredSearch && fetchAutocomplete(value);
}


export function openAutocomplete(checkUrlParams = true)
{
    if(checkUrlParams) {
        const urlParams = new URLSearchParams(window.location.search);
        if(urlParams.size > 0) {
            return;
        }
    }

    const athenaAutocomplete = document.querySelector('#search_autocomplete');
    const backgroundOverlay = document.querySelector('.overlay-background');

    if (!athenaAutocomplete.classList.contains('athena-helper-show')) {
        const productInfoSidebarLandingElement = document.querySelector('#product-info-sidebar-landing');
        productInfoSidebarLandingElement?.classList.remove('product-info-sidebar-active');
        document.body.classList.remove('product-info-sidebar-active-body');

        hideVisualSimilarityBox();
        hideCategoryMenu();

        athenaConfigOptions.voiceRecognition?.disable();

        setTimeout(() => {
            backgroundOverlay?.classList.add('background-overlay');
            search();
        }, 100);
    }
}

export default function autocomplete(isSPA) {
    function initiateAutocomplete() {
        /**
         * Create Elements Function
         */
        function initElements() {
            const athenaAutocomplete = document.querySelector('.athena-autocomplete');
            const athenaSearchAutocomplete = document.querySelector('.athena-search-autocomplete');

            athenaAutocomplete.prepend(
                handleHtml(`
                <div class="athena-no-result" style="display: none;">
                     Sorry, no results for <span id="athena-no-result-query"></span>
                </div>
            `, '.athena-no-result')
            );

            window.addEventListener('finishedConfiguration', () => {
                athenaSearchAutocomplete.classList.add(athenaConfig.layoutType);
            });

            athenaConfigOptions.searchForm.setAttribute('action', athenaConfig.formUrl);
        }

        /**
         * Focus Search Event on ctrl + k keyword
         */
        function focusSearchEvent() {
            document.addEventListener('keydown', (event) => {
                if (event.ctrlKey && event.key === 'k') {
                    event.preventDefault();
                    const searchInput = document.querySelector('#search');
                    searchInput.focus();
                }
            });
        }

        /**
         * Make Clickable Navbar
         *
         * This function is for demo purpose only
         * nothing to do with the functionality of
         * rest of the code can be removed!
         */
        function navBarClickable() {
            const navbarIcon = document.querySelector('.navbar__icon');
            if(!navbarIcon) {
                return;
            }

            navbarIcon.addEventListener('click', () => {
                window.location.href = `${window.location.origin}`;
            });
        }

        /**
         * Submit Form with Button Click
         */
        function submitWithButtonClick() {
            const form = document.querySelector('#search_mini_form');
            const searchIcon = document.querySelector('.search-icon__autocomplete');

            searchIcon.addEventListener('click', (event) => {
                const value = document.querySelector('#search').value;

                if (detectSpecialCharacters(value)) {
                    event.preventDefault();
                    return;
                }

                if (!value.trim()) {
                    event.preventDefault();
                    return;
                }

                form.submit();
            });
        }

        athenaConfigOptions.voiceRecognition = VoiceRecognition.getInstance();

        /**
         * Initial Setup Function
         */
        function initialSetup() {
            //Get or Set Athena UID
            athenaConfigOptions.athenaUid = localStorage.getItem('_athena-uid') ?
                localStorage.getItem('_athena-uid') :
                setAthenaUid();
            //Get Athena Customer Cookie
            athenaConfigOptions.customerCookie = getCookie('athena_customer_cookie');
            //Initialize Search Suggestions
            searchSuggestions();
            //Initialize Visual Similarity Search
            visualSimilaritySearch();
            //Initialize Voice Recognition
            athenaConfigOptions.voiceRecognition
                ?.initialize()
                .then(() => athenaConfigOptions.voiceRecognition?.addVoiceRecognitionListener('#startButton'));
            //Initialize Search Tabs Based on the Layout Selected
            fetchSearchTabs();
            //Init Elements
            initElements();
            //Handle Document Click Listener
            document.addEventListener('click', handleDocumentClick);
            //Handle Submit and Mobile
            if (athenaConfig.layoutType === 'athena-l3') {
                //Handle Submit Function
                athenaConfigOptions.searchForm.addEventListener('keydown', handleSubmit);
                //Adding Resize for Mobile View
                handleMobileLayoutThree(athenaConfigOptions.activeFiltersArray);
            }
            //Adding focus on ctrl + k key combination
            focusSearchEvent();
            //Make navbar Clickable
            navBarClickable();
            //Submit Form With Button Click
            submitWithButtonClick();
            //Handle Escape Button
            escapeButtonHandle();
            //Swipe left to active Search with Tab on Mobile
            const swiperEventsInstance = new SwipeEvents('#search');
            swiperEventsInstance.onRight(function () {
                searchWithTab();
            });
            swiperEventsInstance.run();

            // Demo
            if(!athenaConfig.isDemo){
                hideForProduction();
            }
            if(athenaConfig.isDemo){
                homePage();
                categoryNavigation();
                scrollToTop();
                athenaStory();
                window.setTimeout(function(){
                    recommenderTabs();
                }, 300)
                stickyHeader();
            }

            if(athenaConfig.findVisualSimilarityEnable){
                findVisuallySimilar();
                document.body.classList.add('find-visual-similar-body')
            }


        }

        //INIT Needed Elements And API Calls
        initialSetup();

        /**
         * Use Tab To Search when Placeholder
         * and True Autocomplete is Active
         */
        function searchWithTab() {
            let valueOnTab = '';

            if (searchInput.value.length === 0) {
                valueOnTab = searchInput.getAttribute('placeholder');
                valueOnTab = valueOnTab.split(' ');
                valueOnTab = valueOnTab[valueOnTab.length - 1];

                if (!valueOnTab) {
                    return valueOnTab;
                }

                const filteredValue = athenaConfigOptions.suggestedKeywords.filter(suggestedKeyword => suggestedKeyword?.content.includes(valueOnTab));
                if (filteredValue.length > 0) valueOnTab = filteredValue[0].content;
            }

            if (searchInput.value.length > 0) {
                const trueAutocompleteText = athenaConfigOptions.searchForm?.getAttribute('true-autocomplete-text');
                if (!!trueAutocompleteText) valueOnTab = trueAutocompleteText;
            }

            //Check if before value is same as after value exit function
            if (valueOnTab === athenaConfigOptions.valueOnTabBefore) {
                return;
            }

            athenaConfigOptions.valueOnTabBefore = valueOnTab;
            searchInput.value = valueOnTab;
            searchInput.focus();

            search(valueOnTab);
        }

        /**
         * Disable Search on Same Value
         *
         * @param event
         */
        function disableSearchOnSameValue(event) {
            //Disable Search Input on same values
            const value = event.target.value;
            const currentSearchValue = athenaConfigOptions.currentSearchValue;
            athenaConfigOptions.preventRequestSearch = currentSearchValue === value;
        }

        //INIT Search Functionality
        const searchInput = document.querySelector('#search');
        searchInput.addEventListener('keyup', delay((event) => {
                //Capturing search value on keyup
                athenaConfigOptions.currentSearchValue = event.target.value;

                if (
                    event.keyCode === 13 ||
                    event.keyCode === 37 ||
                    event.keyCode === 38 ||
                    event.keyCode === 39 ||
                    event.keyCode === 40
                ) {
                    if (event.keyCode === 13) {
                        hideAutocompleteBox();
                    }
                    return false;
                }

                //Disable sending requests when its same input
                if (athenaConfigOptions.preventRequestSearch) {
                    return false;
                }

                search();
            }, 500)
        );

        //Keydown Event for Search on TAB
        searchInput.addEventListener('keydown', delay((event) => {
            //Remove Search Suggestion
            handleRenderSearchSuggestions(null, null, true);
            //disable Search on same value
            disableSearchOnSameValue(event);
            //Trim start before Search
            event.target.value = event.target.value.trimStart();

            if (event.keyCode === 9) {
                searchWithTab();
            }
        }, 100));

        /**
         * Handle Submit Function
         *
         * @param event
         */
        function handleSubmit(event) {
            if (event.key !== 'Enter') {
                return;
            }

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

            if (!value.trim()) {
                event.preventDefault();
                return;
            }

            if(detectSpecialCharacters(value)) {
                event.preventDefault();
                return;
            }

            if (athenaConfigOptions.queryOptions['query']) {
                const value = document.querySelector('#search').value;
                const queries = athenaConfigOptions.queryOptions['query'];

                // Construct the base URL without encoding the entire URL
                finalQuery = `${athenaConfig.formUrl}?q=` + encodeURIComponent(value);

                // For each query, append to URL without encoding the key or value
                for (const queryKey in queries) {
                    if (queryKey !== 'service' && queryKey !== 'q') {
                        finalQuery += `&${queryKey}=${queries[queryKey]}`;
                    }
                }

                window.location.href = finalQuery;
            } else {
                // Construct the base URL without encoding the entire URL
                finalQuery = `${athenaConfig.formUrl}?q=` + encodeURIComponent(value);
                window.location.href = finalQuery;
            }

            event.preventDefault();
        }

        /**
         * Check weather to avoid class or not
         * Returns true or false based on the clicked element on autocomplete
         *
         * @param tarClass
         * @returns {boolean}
         */
        function checkAvoidClasses(tarClass) {
            if(typeof tarClass === 'undefined') return true;

            const avoidClasses = [
                /**
                 * /___/ Avoiding closing recommenders
                 */
                'blaze-prev',
                'blaze-next',
                'blaze-track',
                'active',
                'athena-xai__recommendation-grid-container',
                /**
                 * /___/ Avoiding closing did you mean
                 */
                'athena-autocomplete__wrapper',
                'did-you-mean-query__item-layout-3',
                'did-you-mean-query__separator-layout-3',
                'did-you-mean__title-layout-3',
                'did-you-mean__x-layout-3',
                'did-you-mean-question__mark-layout-3',
                /**
                 * /___/ Avoiding closing cutoff distance
                 */
                'icon-arrow',
                'arrow-reverse',
                'athena-cutoff__container',
                'athena-cutoff__show-more-button',
                'athena-cutoff__show-less-button',
                'athena-cutoff__button',
                'athena-helper-show',
                'athena-search-tabs-container',
                'product-info-bottom-sidebar-container',
                'product-info-value-attribute',
                'product-info-key-attribute',
                'product-info-pil',
                'product-info-top-sidebar-container',
                'product-info-sidebar-image',
                'product-info-pi-container',
                'athena-autocomplete__image',
                'athena-autocomplete__name',
                'athena-price',
                'athena-autocomplete__child-bottom',
                'athena-autocomplete__discount-div',
                'product-info-close-button-autocomplete',
                'product-info-key',
                'product-info-value',
                'product-info-parent',
                'product-info-sidebar-container',
                'athena-price-container',
                /**
                 * /___/ Avoiding closing autocomplete on normal autocomplete
                 */
                'audio-search_inner-bottom-container',
                'audio-search-rounded',
                'audio-search__inner-container',
                'athena-input-element-filters',
                'athena-search__filter-container',
                'athena-autocomplete__flex-container',
                'athena-autocomplete__left-container',
                'athena-autocomplete__container-product',
                'athena-autocomplete__left-container',
                'athena-autocomplete__right-container',
                'athena-autocomplete__section-banner-p',
                'athena-search-tabs',
                'mobile-filters-button',
                'autocomplete__top-banner-p',
                'autocomplete__bottom-banner-p',
                'inactive',
                'audio-search__inner-container',
                'audio-search-heading',
                'audio-search_inner-bottom-container',
                'audio-search-icon-text',
                'audio-search__waveform',
                'audio-search__canvas',
                'audio-search-text-bottom',
                /**
                 * /___/ Avoiding closing autocomplete on VSS
                 */
                'cropper-line',
                'cropper-point',
                'cropper-crop-box',
                'cropper-face',
                'cropper-container',
                'cropper-drag-box',
                'cancel-crop-button',
                'ok-crop-button',
                /**
                 * /___/ Avoiding closing autocomplete on VSS
                 */
                'visual-similarity__camera-button-left',
                'visual-similarity__video-container',
                'visual-similarity__camera-button-right',
                'visual-similarity__camera-button',
                'visual-similarity-input',
                'visual-similarity__browse-image-container',
                'visual-similarity__drop-inner-container',
                'visual-similarity__paste-url-search-label',
                'visual-similarity__paste-url-search-container',
                'visual-similarity__paste-url-paste-icon',
                'visual-similarity__input',
                'visual-similarity__paste-url-input-container',
                'visual-similarity-info__container',
                'visual-similarity__dropped-image-container',
                'visual-filter-drag_drop-p',
                'visual-similarity__button-container',
                'visual-similarity__svg-container',
                'visual-similarity__drop-container',
                'visual-similarity-search__container',
                'visual-similarity__p',
                'visual-similarity__close_button',
                'visual-similarity__drop-inner-parent-container',
                'visual-similarity-search',
                'visual-similarity__paste-url-error-message',
                'visual-similarity__paste-url-x-icon',
                'visual-similarity__upload-container',
                'visual-similarity__camera-container',
                /**
                 * /___/ Avoiding closing autocomplete on OMRange
                 */
                'om-sliderrange-display',
                'om-mid-price-show-container',
                'om-min-price-range__show-span',
                'om-min-price-range__span',
                'om-min-price-range__div',
                'om-sliderrange-range',
                'om-sliderrange-range-indicator',
                'om-slider-range-left-circle-parent',
                'om-slider-range-right-circle-parent',
                'om-slider-range-left-circle',
                'om-slider-range-right-circle',
                /**
                 * /___/ Avoiding closing autocomplete on Layout Three
                 */
                'sidebar-autocomplete-layout-three',
                'content-autocomplete-layout-three',
                'autocomplete-l3__flex-container',
                'autocomplete-l3__checkbox',
                'autocomplete-l3__filters',
                'autocomplete-l3__ajax',
                'autocomplete-l3__ajax-add',
                'autocomplete-l3__ajax-remove',
                'autocomplete-l3__ajax-remove-span',
                'autocomplete-l3__filter-title',
                'autocomplete-l3__left_sidebar',
                'autocomplete-l3__filter-children',
                'autocomplete-l3__filters-container',
                'autocomplete-l3__filters-container-parent',
                'autocomplete-l3__right_sidebar',
                'autocomplete_l3_go_back_container',
                'autocomplete_l3__go_back_button',
                'autocomplete-l3__mobile-buttons-container',
                'autocomplete-l3__left-sidebar-filters-container',
                'autocomplete-l3__content',
                'autocomplete-l3__filter-color-label',
                'autocomplete-l3__product-container',
                'autocomplete-l3__filter-color',
                'autocomplete-l3__filter-span',
                'checkmark',
                'athena-filter__search-icon',
                /**
                 * /___/ Avoiding closing for camera functionality
                 */
                'capture-image',
                'cancel-capture-image',
                'back-camera-select',
                'front-camera-select',
                /**
                 * /___/ Avoiding closing Category Menu
                 */
                'category-navigation-container',
                'category-level-menu',
                'category-name',
                'category-item-arrow',
                /**
                 * /___/ Avoiding closing on PDP Tabs
                 */
                'pdp-tabs',
                'pdp-tab-name',
                'pdp-tab-content',
                'tabs-attributes',
                'tabs-category',
                'show-more-popup',
                'athena-xai__recommendation-title',
                'blaze-track',
                'pdp-tab-name-landing',
                'show-more-landing',
                'product-popup-overlay',
                'tabs-attributes-landing',
                'pdp-tab-content-landing',
                'athena-recommendation__product-item',
                'athena-product-item-link',
                'athena-product-item-photo',
                'athena-product-image-photo',
                'athena-product-item-details',
                'athena-page-product-link',
                'athena-product-name',
                'pdp-tabs-landing',
                /**
                 * /___/ Avoiding closing on Search Suggestion
                 */
                'athena-search-suggestion__container',
                'athena-search-suggestion__text',
                'athena-search-suggestion__tab-button'
            ];

            return avoidClasses.filter((avoidClass) => avoidClass.includes(tarClass)).length > 0;
        }

        /**
         * Handle Document Click Event
         *
         * @param event
         */
        function handleDocumentClick(event) {
            const tar = event.target.id;
            const tarClass = event.target.classList[0];
            const tagName = event.target.tagName;
            const eventType = event.type;
            const tarParentClass = event.target.parentElement?.classList[0];
            const athenaAutocomplete = document.querySelector('#search_autocomplete');
            const backgroundOverlay = document.querySelector('.overlay-background');

            checkProductClick(event);

            //Check if there is a need to close autocomplete box or not
            const avoidClass = checkAvoidClasses(tarClass ? tarClass : tarParentClass);
            if (avoidClass) return;

            if (
                tar === 'search'
                || tar === 'search_autocomplete'
                || tarClass === 'athena'
                || tarClass === 'pe-7s-search'
                || tagName === 'H4'
                || eventType === 'touchmove'
                || tarParentClass === 'athena-autocomplete'
                || tarParentClass === 'athena-tab'
                || tarParentClass === 'athena-search-tabs'
            ) {
                if (!athenaAutocomplete?.classList.contains('athena-helper-show')) {
                    const productInfoSidebarLandingElement = document.querySelector('#product-info-sidebar-landing');
                    productInfoSidebarLandingElement?.classList.remove('product-info-sidebar-active');
                    document.body.classList.remove('product-info-sidebar-active-body');
                    hideVisualSimilarityBox();
                    hideCategoryMenu();

                    athenaConfigOptions.voiceRecognition?.disable();

                    if(athenaConfig.sendAthenaRequest){
                        search(null, false);
                    }else{
                        search(null, true);
                    }

                    setTimeout(() => {
                        backgroundOverlay?.classList.add('background-overlay');
                        !athenaAutocomplete?.classList.contains('athena-helper-show') && athenaAutocomplete?.classList.add('athena-helper-show');
                    }, 100);

                    document.querySelector('.athena-mobile-close-button')?.classList.add('active-mobile-close');
                }
            } else {
                if (
                    tar === 'startButton' ||
                    tarClass === 'button-start-search' ||
                    tarClass === 'audio__image' ||
                    tar === 'visual-similarity__camera-button' ||
                    tarClass === 'visual-similarity__camera-button' ||
                    tarClass === 'edit-button__visual-similarity-search' ||
                    tarClass === 'category-navigation-btn' ||
                    tarClass === 'category-navigation-opener' ||
                    tarClass === 'continuous-voice-search' ||
                    tarClass === 'continuous-voice-icon'
                )
                    return;

                backgroundOverlay?.classList.remove('background-overlay');
                document.body.classList.remove('athena-disable-scroll');
                athenaConfigOptions.activeFiltersArray = null;

                athenaConfigOptions.voiceRecognition?.disable();

                hideAutocompleteBox();
                hideVisualSimilarityBox();
                hideCategoryMenu();
                document.dispatchEvent(athenaConfigOptions.cameraCloseEvent);
                document.querySelector('.athena-mobile-close-button')?.classList.remove('active-mobile-close');

                const productInfoAutocompleteElement = document.querySelector('#product-info-sidebar-autocomplete');
                productInfoAutocompleteElement?.classList.remove('product-info-sidebar-autocomplete-active');
            }
        }
    }

    isSPA ?
        document.addEventListener('SPAContentLoaded', () => initiateAutocomplete()) :
        document.addEventListener('DOMContentLoaded', () => initiateAutocomplete());
}
