(function() {
    'use strict';

    var isActivationKey = function(event) {
        var key = event.key || event.keyCode;

        if ('Enter' === key || ' ' === key || 13 === key || 32 === key) {
            return true;
        }

        return false;
    };

    document.addEventListener('DOMContentLoaded', function() {
        var toolbar = document.querySelector('.wpr-nav-menu-toolbar');

        if (!toolbar) {
            return;
        }

        var linkNodes = toolbar.querySelectorAll('.wpr-nav-menu-link[data-wpr-target]');
        
        Array.prototype.forEach.call(linkNodes, function(node) {
            var target = node.getAttribute('data-wpr-target');

            if (!target) {
                return;
            }

            var handleNavigation = function(event) {
                if ('keydown' === event.type && !isActivationKey(event)) {
                    return;
                }

                if ('keydown' === event.type) {
                    event.preventDefault();
                }

                window.location.href = target;
            };

            node.addEventListener('click', handleNavigation);
            node.addEventListener('keydown', handleNavigation);
        });

        var forms = [];
        var hiddenFields = [];

        var form = document.getElementById('update-nav-menu');
        var locationsForm = document.getElementById('menu-locations');

        if (form) {
            forms.push(form);
        }

        if (locationsForm) {
            forms.push(locationsForm);
        }

        Array.prototype.forEach.call(forms, function(formElement) {
            var hidden = formElement.querySelector('input[name="wpr_menu_language"]');

            if (!hidden) {
                hidden = document.createElement('input');
                hidden.type = 'hidden';
                hidden.name = 'wpr_menu_language';
                formElement.appendChild(hidden);
            }

            hiddenFields.push(hidden);
        });

        var dropdownWrapper = toolbar.querySelector('.wpr-nav-menu-toolbar__select');
        var dropdown = toolbar.querySelector('.wpr-nav-menu-dropdown');
        var isCreatingMenu = '1' === toolbar.getAttribute('data-is-creating-menu');
        var fallbackLang = toolbar.getAttribute('data-fallback-language') || '';
        var selectedLang = toolbar.getAttribute('data-current-menu-language') || '';
        var preferredSelection = toolbar.getAttribute('data-selected-language') || '';

        if (dropdown) {
            fallbackLang = dropdown.getAttribute('data-fallback') || fallbackLang;

            if (dropdown.getAttribute('data-selected')) {
                selectedLang = dropdown.getAttribute('data-selected') || selectedLang;
            }
        } else if (!selectedLang && preferredSelection) {
            selectedLang = preferredSelection;
        }

        var ensureHiddenValue = function(value) {
            if (!hiddenFields.length) {
                return;
            }

            Array.prototype.forEach.call(hiddenFields, function(field) {
                if (value) {
                    field.value = value;
                } else if (fallbackLang) {
                    field.value = fallbackLang;
                } else {
                    field.value = '';
                }
            });
        };

        ensureHiddenValue(selectedLang);

        if (dropdownWrapper) {
            dropdownWrapper.classList.add('wpr-nav-menu-language-control');
        }

        var menuNameField = document.getElementById('menu-name');

        if (menuNameField && dropdownWrapper && isCreatingMenu) {
            var languageContainer = document.createElement('div');

            languageContainer.className = 'wpr-nav-menu-language-field';
            languageContainer.appendChild(dropdownWrapper);

            if (menuNameField.parentNode) {
                menuNameField.parentNode.insertBefore(languageContainer, menuNameField.nextSibling);
                menuNameField.parentNode.classList.add('wpr-nav-menu-language-enabled');
            }
        } else if (!isCreatingMenu && dropdownWrapper && dropdownWrapper.parentNode) {
            dropdownWrapper.parentNode.removeChild(dropdownWrapper);
        }

        var actionsWrapper = toolbar.querySelector('.wpr-nav-menu-toolbar__actions');

        if (actionsWrapper && !actionsWrapper.querySelector('.wpr-nav-menu-toolbar__select')) {
            if (actionsWrapper.parentNode) {
                actionsWrapper.parentNode.removeChild(actionsWrapper);
            }
        }

        if (dropdown) {
            var label = dropdown.querySelector('.wpr-nav-menu-dropdown__label');
            var list = dropdown.querySelector('.wpr-nav-menu-dropdown__list');
            var options = list ? list.querySelectorAll('.wpr-nav-menu-dropdown__option') : [];
            var placeholder = dropdown.getAttribute('data-placeholder') || '';

            var closeList = function() {
                if (!list || list.hasAttribute('hidden')) {
                    return;
                }

                list.setAttribute('hidden', 'hidden');
                dropdown.classList.remove('is-open');
            };

            var openList = function() {
                if (!list) {
                    return;
                }

                list.removeAttribute('hidden');
                dropdown.classList.add('is-open');
            };

            var toggleList = function() {
                if (!list) {
                    return;
                }

                if (dropdown.classList.contains('is-open')) {
                    closeList();
                } else {
                    openList();
                }
            };

            var updateSelection = function(code, text) {
                selectedLang = code || '';
                dropdown.setAttribute('data-selected', selectedLang);

                Array.prototype.forEach.call(options, function(option) {
                    if (option.getAttribute('data-value') === selectedLang && '' !== selectedLang) {
                        option.classList.add('is-selected');
                    } else {
                        option.classList.remove('is-selected');
                    }
                });

                if (label) {
                    var newText = text;

                    if (!newText) {
                        if (selectedLang) {
                            var fallbackOption = dropdown.querySelector('.wpr-nav-menu-dropdown__option[data-value="' + selectedLang + '"]');

                            if (fallbackOption) {
                                newText = fallbackOption.textContent;
                            }
                        }

                        if (!newText) {
                            newText = placeholder || '';
                        }
                    }

                    label.textContent = newText;
                }

                ensureHiddenValue(selectedLang);
            };

            if (label) {
                label.addEventListener('click', function() {
                    toggleList();
                });

                label.addEventListener('keydown', function(event) {
                    if (!isActivationKey(event)) {
                        return;
                    }

                    event.preventDefault();
                    toggleList();
                });
            }

            Array.prototype.forEach.call(options, function(option) {
                option.addEventListener('click', function() {
                    updateSelection(option.getAttribute('data-value'), option.textContent);
                    closeList();
                });

                option.addEventListener('keydown', function(event) {
                    if (!isActivationKey(event)) {
                        return;
                    }

                    event.preventDefault();
                    updateSelection(option.getAttribute('data-value'), option.textContent);
                    closeList();
                });
            });

            document.addEventListener('click', function(event) {
                if (!dropdown.contains(event.target)) {
                    closeList();
                }
            });

            document.addEventListener('keydown', function(event) {
                var key = event.key || event.keyCode;

                if ('Escape' === key || 27 === key) {
                    closeList();
                }
            });

            if (selectedLang) {
                var selectedOption = dropdown.querySelector('.wpr-nav-menu-dropdown__option[data-value="' + selectedLang + '"]');

                if (selectedOption) {
                    updateSelection(selectedLang, selectedOption.textContent);
                } else {
                    updateSelection('', '');
                }
            } else {
                updateSelection('', '');
            }
        }
    });
})();
