import { openAutocomplete } from '../autocomplete.js';

export default function()
{
    const autocompleteElements = {
        searchAutocomplete: document.querySelector('#search_autocomplete'),
        visualSimilarityAutocomplete: document.querySelector('#visual_similarity_search'),
    };

    document.querySelector('.athena-mobile-close-button')?.classList.remove('active-mobile-close');

    function closeAutocompleteTab(autocompleteElements)
    {
        let includes = false;
        autocompleteElements.forEach(autocompleteElement => {
            if(autocompleteElement?.classList.contains('athena-helper-show')) {
                includes = true;
            }
        });

        autocompleteElements.forEach(autocompleteElement => {
            if(includes) {
                autocompleteElement?.classList.remove('athena-helper-show');
                includes = false;
            } else {
                openAutocomplete(false);
            }
        });

        if(includes) {
            document.querySelector('.athena-mobile-close-button')?.classList.remove('active-mobile-close');
        } else {
            setTimeout(() => {
                document.querySelector('.athena-mobile-close-button')?.classList.add('active-mobile-close');
            },100);
        }
    }

    function handleEscapeKey(key)
    {
        const {
            searchAutocomplete,
            visualSimilarityAutocomplete
        } = autocompleteElements;

        if(!document.body.classList.contains('active-athena-stories-recommender')){
            if (key === 'Escape'){
                closeAutocompleteTab([searchAutocomplete, visualSimilarityAutocomplete]);
            }
        }
    }

    function handleEscapeOnMobile()
    {
        const {
            searchAutocomplete,
            visualSimilarityAutocomplete,
        } = autocompleteElements;


        const athenaMobileCloseButton = document.querySelector('.athena-mobile-close-button');
        athenaMobileCloseButton.addEventListener('click', () => closeAutocompleteTab([searchAutocomplete, visualSimilarityAutocomplete]));
    }

    if (window.matchMedia('(max-width: 768px)').matches) {
        handleEscapeOnMobile();
    } else {
        document.addEventListener('keydown', (event) => handleEscapeKey(event.key));
    }
}