/**
 * Editor script nav menu
 *
 * @package woostify
 */

/* global  Woostify Builder Nav Menu*/
;(function ($) {  

    'use strict';

    function actionMegaMenuLayoutSettings(element) {
        var offCanvasWrapper = element;

        if ( !offCanvasWrapper ) {
            return;
        }

        document.addEventListener('click', function (e) {
            var target = e.target;
            var offcanvas = target.closest('.woostify-offcanvas-wrapper');
            if ( !offcanvas ) {
                return;
            }

            var megaMenuContent = target.closest('.woostify-mega-menu-content');
            
            if ( !megaMenuContent && offCanvasWrapper.classList.contains('active') ) {
                offCanvasWrapper.classList.remove('active');
                offCanvasWrapper.querySelector('.woostify-mega-menu-content').innerHTML = '<div class="woostify-megamenu-loading-wrapper"><div class="spinner-loading"></div></div>';
            }

        });

        var megaMenuCloseBtn = offCanvasWrapper.querySelector('.mega-menu-close');
        var megaMenuContent = offCanvasWrapper.querySelector('.woostify-mega-menu-content');

        if (megaMenuCloseBtn.length != 0) {
            megaMenuCloseBtn.addEventListener('click', function (e) {
                e.preventDefault();
                offCanvasWrapper.classList.remove('active');
                megaMenuContent.innerHTML = '<div class="woostify-megamenu-loading-wrapper"><div class="spinner-loading"></div></div>';

            });
        }

        var saveOptions = offCanvasWrapper.querySelector('.save-options');
        if (saveOptions.length != 0) {

            saveOptions.addEventListener('click',function (e) {
                var button = this,
                menuId     = button.getAttribute('data-menu-id'),
                menuItem   = offCanvasWrapper.querySelectorAll( '[name*=woostify_menu_item_megamenu_]' ),
                values     = {};
                var nonce  = document.querySelector('#menu-item-'+menuId).querySelector('.woostify-nonce-field').value;
                
                if ( menuItem.length ) {
                    menuItem.forEach( function( el ) {
                        let value = el.value;
                        values[ el.name ] = value.replace(/&/g, encodeURIComponent('&'));
                    } );
                }
                
                button.classList.add('loading');
    
                // Request.
                var request = new Request(
                    ajaxurl,
                    {
                        method: 'POST',
                        body: 'action=woostify_save_mega_menu_options&menu_ajax_nonce=' + nonce + '&menu_item_id=' + menuId + '&options=' + JSON.stringify(values),
                        credentials: 'same-origin',
                        headers: new Headers(
                            {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                            }
                        )
                    }
                );

                fetch(request).then(
                    function (res) {
                        if (200 !== res.status) {
                            console.log('Status Code: ' + res.status);
                            return;
                        }

                        res.json().then(
                            function (r) {
                                
                                if (!r.success) {
                                    return;
                                }

                                button.classList.remove('loading');
                                
                                if ('' !== r.data) {
                                    // console.log( r.data );
                                }
                            }
                        )
                    }
                ).finally(function () {
                    button.classList.remove('loading');
                });

            });
        }
        
    }

    function selectMegaMenuContentSRC(element) {
        var offCanvasWrapper = element;
        var woostifySelectInput = offCanvasWrapper.querySelector('.woostify-select-input');
        var woostifyContntSRC = offCanvasWrapper.querySelectorAll('.woostify-content-src');

        if ( ! woostifySelectInput ) {
            return;
        }

        woostifySelectInput.addEventListener('change', function (e) {
            var type = e.target.value;
            woostifyContntSRC.forEach(function (ele) {
                if ( ele.classList.contains('woostify-'+type) ) {
                    ele.classList.remove('woostify-hidden');
                }else{
                    ele.classList.add('woostify-hidden');
                }
            });

        });
    }

    function checkboxMegaMenuDisable(element) {
        var offCanvasWrapper = element;
        var checkbox = offCanvasWrapper.querySelectorAll('.woostify-switch');
        var megamenuWidth = offCanvasWrapper.querySelector('.woostify-settings_menu_item_megamenu_width');
        if ( checkbox.length > 0 ) {
            checkbox.forEach(function (ele) {
                ele.addEventListener('change', function (e) { 
                    e.preventDefault();
                    if(this.checked == true){
                        this.value = 'on';
                        megamenuWidth.classList.remove('woostify-hidden');
                    }else{
                        this.value = 'off';
                        megamenuWidth.classList.add('woostify-hidden');
                    }
                });
                
            });
        }
    }

    function loadMegaMenuLayoutSettings() {
        var offCanvasWrapper = document.querySelector('.woostify-offcanvas-wrapper');

        document.addEventListener('click', function (e) {
            if (e.target.matches(".woostify-megamenu-opts-btn")) {
                var menuItem = e.target.closest(".menu-item");
                
                var menuDepth = menuItem.classList.value;
                if (menuDepth.includes('menu-item-depth-')) {
                    var menuDeptId = menuDepth.split('menu-item-depth-')[1].split('')[0];
                    var menuName = e.target.getAttribute("data-menu-title");
                    var menuId = e.target.getAttribute("data-menu-id");
                    var navId = document.querySelector("#nav-menu-meta-object-id").getAttribute("value");
                    var nonce = menuItem.querySelector('.woostify-nonce-field').value;

                    if (menuDeptId && menuName && menuId && navId) {
                       
                        offCanvasWrapper.setAttribute('data-menu-id',menuId);

                        // Request.
                        var request = new Request(
                            ajaxurl,
                            {
                                method: 'POST',
                                body: 'action=woostify_load_mega_menu_layout_settings&menu_ajax_nonce=' + nonce + '&menu_id=' + menuId + '&menu_depth=' + menuDeptId + '&menu_name' + menuName + '&nav_id' + navId,
                                credentials: 'same-origin',
                                headers: new Headers(
                                    {
                                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                                    }
                                )
                            }
                        );

                        fetch(request).then(
                            function (res) {
                                if (200 !== res.status) {
                                    console.log('Status Code: ' + res.status);
                                    return;
                                }
    
                                res.json().then(
                                    function (r) {
                                        
                                        if (!r.success) {
                                            return;
                                        }
                                        
                                        if ('' !== r.data) {
                                            var megaMenuContent = offCanvasWrapper.querySelector('.woostify-mega-menu-content');
                                            megaMenuContent.innerHTML = r.data;
                                            checkboxMegaMenuDisable( offCanvasWrapper );
                                            actionMegaMenuLayoutSettings( offCanvasWrapper );
                                            selectMegaMenuContentSRC( offCanvasWrapper );
                                            searchTemplate( offCanvasWrapper );
                                        }
                                    }
                                )
                            }
                        );

                        if (!offCanvasWrapper.classList.contains("active")) {
                            offCanvasWrapper.classList.add("active");
                        }

                    }
                }

            }

        });
        
    }

    function searchTemplate(element) {  
        var menuId = element.getAttribute('data-menu-id');
        var nonce  = document.querySelector('#menu-item-'+menuId).querySelector('.woostify-nonce-field').value;
        var inputTemplate = element.querySelector('.woostify-input-template');

        if (!inputTemplate) {
            return;
        }

        inputTemplate.addEventListener('input', function (e) {  
      
            var q = e.target.value;

            // Request.
            var request = new Request(
                ajaxurl,
                {
                    method: 'POST',
                    body: 'action=woostify_get_posts_list&menu_ajax_nonce=' + nonce + '&menu_item_id='+ menuId + '&q=' + q,
                    credentials: 'same-origin',
                    headers: new Headers(
                        {
                            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                        }
                    )
                }
            );
    
            fetch(request).then(
                function (res) {
                    if (200 !== res.status) {
                        console.log('Status Code: ' + res.status);
                        return;
                    }
    
                    res.json().then(
                        function (r) {
                   
                            if (!r.success) {
                                return;
                            }
  
                            if ('' !== r.data) {
                                var templates = (r.data[0].children.length != 0 )? r.data[0].children : '';
             
                                autocomplete(inputTemplate, templates);

                            }
                        }
                    )
                }
            );
        });

    }


    function autocomplete(autocomplete_input, suggestions) {
        var currentOption;
        var total_autocomplete = document.getElementsByClassName('autocomplete-input').length;

        autocomplete_input.parentNode.style.position = "relative";
        autocomplete_input.classList.add('autocomplete-input');
        autocomplete_input.setAttribute('data-autocomplete-list-id', "autocomplete-list-" + (total_autocomplete + 1));
        autocomplete_input.setAttribute('autocomplete', "off");

        var $this = autocomplete_input;
        var string_to_match = $this.value.toLowerCase();
        var autocomplete_list_id = $this.getAttribute('data-autocomplete-list-id');
        
        removeLists();

        if (string_to_match) {
            currentOption = -1;
            var regex = new RegExp( '(' + string_to_match + ')', 'gi' );

            var autocomplete_list = document.createElement("DIV");
            autocomplete_list.setAttribute("id", autocomplete_list_id);
            autocomplete_list.setAttribute("class", "autocomplete-list");

            var autocomplete_items = document.createElement("DIV");
            autocomplete_items.setAttribute("class", "list-group list-group-flush autocomplete-items");
            if (suggestions != '') {
                suggestions.forEach(function(suggestion) {
                    var id = suggestion.id;
                    var text = suggestion.text;
                    if (text.toLowerCase().includes(string_to_match)) {
                        var autocomplete_item = document.createElement("DIV");
                        autocomplete_item.setAttribute('class', 'list-group-item list-group-item-action');
                        autocomplete_item.setAttribute("data-autocomplete-text", text);
                        autocomplete_item.innerHTML = text.replace(regex, "<b>$1</b>" );
    
                        autocomplete_item.addEventListener("click", function(e) {
                            e.preventDefault();
                            $this.value = this.getAttribute("data-autocomplete-text");
                            $this.nextElementSibling.value = id;
                            autocomplete_items.remove();
                        });
    
                        autocomplete_items.appendChild(autocomplete_item);
                    }
                });
            }

            autocomplete_list.appendChild(autocomplete_items);
            $this.parentNode.appendChild(autocomplete_list);
        }

        autocomplete_input.addEventListener("keydown", function(e) {
            var autocomplete_list_id = autocomplete_input.getAttribute('data-autocomplete-list-id');
            var autocomplete_list = document.getElementById(autocomplete_list_id);

            if ( autocomplete_list ) {
                var autocomplete_items = autocomplete_list.querySelector('.autocomplete-items').getElementsByTagName("div");
                
                if (e.keyCode == 40) {
                    currentOption++;
                    selectItem(autocomplete_items);
                } else if (e.keyCode == 38) {
                    currentOption--;
                    selectItem(autocomplete_items);
                } else if (e.keyCode == 13) {
                    e.preventDefault();
                    if (currentOption > -1) {
                        if (autocomplete_items) {
                            autocomplete_items[currentOption].click();
                        }
                    }
                }
            }
        });

        function selectItem(autocomplete_items) {
            if (autocomplete_items) {
                Array.from(autocomplete_items).forEach(autocomplete_item => {
                    autocomplete_item.classList.remove("active");
                });
                
                currentOption = currentOption >= autocomplete_items.length ? 0 : currentOption;
                currentOption = currentOption < 0 ? autocomplete_items.length - 1 : currentOption;

                if( autocomplete_items[currentOption] ){
                    autocomplete_items[currentOption].classList.add("active");
                }
            }
        }

        function removeLists(element) {
            var autocomplete_lists = document.getElementsByClassName("autocomplete-list");
            Array.from(autocomplete_lists).forEach(autocomplete_list => {
                if (element != autocomplete_list && element != autocomplete_input) {
                    autocomplete_list.remove();
                }
            });
        }

        document.addEventListener("click", function(e) {
            removeLists(e.target);
        });
    }

    

    document.addEventListener(
        'DOMContentLoaded',
        function() {
    
            loadMegaMenuLayoutSettings();

        }
    );
    
    
})(jQuery);

