(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'),
        emailMessage = select('.b-email-message'),
        emailMessageEmail = select('.b-email-message b'),
        emailMessageLink = select('.b-email-message form'),
        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('d-none');
        reg.classList.toggle('d-none');
        authTitle.classList.toggle('d-none');
        regTitle.classList.toggle('d-none');
    }

    function ToggleAuthBlock()
    {
        social.classList.toggle('d-none');
        auth.classList.toggle('d-none');
    }
    
    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;
    });
    */




    // Валидация форм
    
    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"),
        formVerEmail = document.querySelector("form#ver-email-form");
    
    // клик извне, чтобы закрыть сообщение ошибок
    document.addEventListener( 'click', (e) => {
        const withinAlertAll = e.composedPath().includes(alertAll);
            if (!withinAlertAll) {
                //alertAll.classList.add('d-none');
                alertAll.forEach(function(item){
                    item.classList.add('d-none');
                })
            }
    });
    
    
    formAuth.addEventListener("submit", function(ev) {
        ev.preventDefault();
        handleFormSubmit(formAuth, constraintsAuth);
    });
    
    formReg.addEventListener("submit", function(ev) {
        ev.preventDefault();
        handleFormSubmit(formReg, constraintsReg);
    });
    
    formVerEmail.addEventListener("submit", function(ev) {
        ev.preventDefault();
        form_submit(formVerEmail, formVerEmail.getAttribute('action'), new FormData(formVerEmail));
    });
    
    
    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') {
                if (json.redirect) {
                    window.location.href = json.redirect;
                }
                if (json.message) {
                    showErrors({'success': json.message});
                }
            }
            if (json.status == 'email_send') {
                showSendEmailMessage(json.email, json.link);
            }
            
            
        })
        .catch(error => {
            showErrors({'error': error});
        });
        
        
        return false;
    }
    

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

    function showSendEmailMessage(email,link) {
        
        social.classList.add('d-none');
        auth.classList.add('d-none');
        
        emailMessageEmail.innerText = email;
        emailMessage.classList.remove('d-none');
    }

})();