(function() {
    "use strict";


    const select = (el, all = false) => {
    el = el.trim()
    if (all) {
      return [...document.querySelectorAll(el)]
    } else {
      return document.querySelector(el)
    }
    }

    const on = (type, el, listener, all = false) => {
    let selectEl = select(el, all)
    if (selectEl) {
      if (all) {
        selectEl.forEach(e => e.addEventListener(type, listener))
      } else {
        selectEl.addEventListener(type, listener)
      }
    }
    }


    // Переключение форм внутри попапа

    let
        social = select('.b-social'),
        auth = select('.b-auth'),
        email = select('.b-email'),
        reg = select('.b-reg'),
        authTitle = select('.modal-title.auth'),
        regTitle = select('.modal-title.reg'),
        googleAuth = select('.btn-google'),
        appleAuth = select('.btn-apple'),
        closeModal = select('.modal-dialog .btn-close');
        
        
    function ToggleLoginBlock()
    {
        email.classList.toggle('m-hide');
        reg.classList.toggle('m-hide');
        authTitle.classList.toggle('m-hide');
        regTitle.classList.toggle('m-hide');
    }

    function ToggleAuthBlock()
    {
        social.classList.toggle('m-hide');
        auth.classList.toggle('m-hide');
    }
    
    on('click', '.btn-email', function(e) {
        e.preventDefault();
        ToggleAuthBlock();
    });

    on('click', '.soc-link', function(e) {
        e.preventDefault();
        ToggleAuthBlock();
    });
    
    on('click', '.soc-link2', function(e) {
        e.preventDefault();
        ToggleAuthBlock();
    });

    on('click', '.auth-link', function(e) {
        e.preventDefault();
        ToggleLoginBlock();
    });

    on('click', '.reg-link', function(e) {
        e.preventDefault();
        ToggleLoginBlock();
    });
    
    
    // Модальное окно для авторизации через соц.сети:
    let googleWin;
    var
        valueInterval = 1000,
        waitLoginInterval,
        showModalInterval;
      
    function showModalWin(e, socialAuth)
    {
        e.preventDefault();
        
        if (googleWin) {
            googleWin.close();
        }
        
        const
            width = 500,
            height = 600,
            left = window.innerWidth/2-width/2,
            top = window.innerHeight/2-height/2;
            
        googleWin = window.open(socialAuth.getAttribute('href') ,'Авторизацiя', `popup=true, width=${width}, height=${height}, top=${top}, left=${left}`);

        clearInterval(waitLoginInterval);
        waitLoginInterval = setInterval(function(){
            try {
                if (googleWin.location.href && googleWin.location.href != 'about:blank') {
                    clearInterval(waitLoginInterval);
                    googleWin.close();
                    window.location.reload();
                }
            } catch (error) {
                
            }
        }, valueInterval);
       
        clearInterval(showModalInterval);
        showModalInterval = setInterval(function(){
            if (!googleWin.window) {
                clearInterval(waitLoginInterval);
                clearInterval(showModalInterval);
                closeModal.click();
            }
        }, valueInterval);
        
        return false;
    }
        
    on('click', '.btn-google', function(e) {
        showModalWin(e, googleAuth)
    });
    
    on('click', '.btn-apple', function(e) {
        showModalWin(e, appleAuth)
    });
    
    
    /*
    on('click', '.btn-google', function(e) {
        e.preventDefault();
        
        if (googleWin) {
            googleWin.close();
        }
        
        const
            width = 500,
            height = 600,
            left = window.innerWidth/2-width/2,
            top = window.innerHeight/2-height/2;
            
        googleWin = window.open(googleAuth.getAttribute('href') ,'Продовжити з Google', `popup=true, width=${width}, height=${height}, top=${top}, left=${left}`);

        clearInterval(waitLoginInterval);
        waitLoginInterval = setInterval(function(){
            console.log('AAA 111');
            try {
                if (googleWin.location.href && googleWin.location.href != 'about:blank') {
                    clearInterval(waitLoginInterval);
                    googleWin.close();
                    window.location.reload();
                }
            } catch (error) {
                
            }
        }, valueInterval);
       
        clearInterval(showModalInterval);
        showModalInterval = setInterval(function(){
            console.log('AAA 222');
            if (!googleWin.window) {
                clearInterval(waitLoginInterval);
                clearInterval(showModalInterval);
                closeModal.click();
            }
        }, valueInterval);
        
        return false;
    });
    */

})();


(function() {

    // Валидация форм
    
    var constraintsAuth = {
        email: {
            presence: {message: "Email не повинен бути пустим"},
            email: {message: "Перевiрте поштову адресу"}
        },
        password: {
            presence: {message: "Пароль не повинен бути пустим"},
        },
    };
    
    
    
    var constraintsReg = {
        email: {
            presence: {message: "Email не повинен бути пустим"},
            email: {message: "Перевiрте поштову адресу"}
        },
        password: {
            presence: {message: "Пароль не повинен бути пустим"},
        },
        'password_confirmation': {
            presence: {message: "Повторiть пароль"},
            equality: {
                attribute: "password",
                message: "Паролi не спiвпадають"
            }
        },
    };

    var
        alertForm = document.querySelector(".b-alerts .alert.form"),
        alertAll = document.querySelectorAll(".b-alerts .alert"),
        formAuth = document.querySelector("form#auth-form"),
        formReg = document.querySelector("form#reg-form"),
        formSet = document.querySelector("form#set-form");
    
    // клик извне, чтобы закрыть сообщение ошибок
    document.addEventListener( 'click', (e) => {
        const withinAlertAll = e.composedPath().includes(alertAll);
            if (!withinAlertAll) {
                //alertAll.classList.add('m-hide');
                alertAll.forEach(function(item){
                    item.classList.add('m-hide');
                })
            }
    });
    
    
    formAuth.addEventListener("submit", function(ev) {
        ev.preventDefault();
        handleFormSubmit(formAuth, constraintsAuth);
    });
    
    formReg.addEventListener("submit", function(ev) {
        ev.preventDefault();
        handleFormSubmit(formReg, constraintsReg);
    });
    
    if (formSet) {
        formSet.addEventListener("submit", function(ev) {
            ev.preventDefault();
            handleFormSubmit(formSet, constraintsReg);
        });
    }
    

    function handleFormSubmit(form, constraints) {
        var errors = validate(form, constraints, {fullMessages: false});
        showErrors(errors || {});
        if (!errors) {
            //form.submit();
            let action = form.getAttribute('action');
            let formData = new FormData(form);
            form_submit(form, action, formData);
        }
    }

    function form_submit(thisForm, action, formData) {
    
        let response = fetch(action, {
            method: 'POST',
            body: formData,
            headers: {'X-Requested-With': 'XMLHttpRequest'}
        })
        .then(response => {
            if( response.ok ) {
                return response.json();
            } else {
                return response.json();
                throw new Error(`${response.status} ${response.statusText} ${response.url}`); 
            }
        })
        .then(json => {
            if (json.errors) {
                var dataErrors = {};
                for (const [key, value] of Object.entries(json.errors)) {
                    dataErrors.key = value;
                }
                showErrors(dataErrors);
            }
            if (json.status == 'error') {
                showErrors({'error': json.message});
            }
            if (json.status == 'success') {
                window.location.href = json.redirect;
            }
        })
        .catch(error => {
            console.log('AAA catch error = ', error);
            showErrors({'error': error});
        });
        
        
        return false;
    }
    

    function showErrors(errors) {
        if (!Object.keys(errors).length) {
            return false;
        }
        
        var messageText = '<ul>';
        for (const [key, value] of Object.entries(errors)) {
            messageText += `<li>${value}</li>`;
        }
        messageText += '</ul>';
        alertForm.innerHTML = messageText;
        alertForm.classList.remove('m-hide');
    }

      
})();