var SYRUS_CHAT_FIRST_TIME_OPENED = false;

jQuery(document).ready(() => {

    if(jQuery('#syrus-chat-container').length > 0)
        initSyrusChatContainer();

});

function initSyrusChatContainer() {

    jQuery('#syrus-chat-container .chat-toggle, #syrus-chat-container .close-button').on('click', () => {
        jQuery('#syrus-chat-container .chat-container').toggle();

        if(!SYRUS_CHAT_FIRST_TIME_OPENED) {
            setTimeout(() => {
                jQuery('#syrus-chat-container .message-container.loading-container').remove();
                jQuery('#syrus-chat-container .message-container').show();
            }, WA_SETTINGS.message_delay ? WA_SETTINGS.message_delay : 1000);
        }

        SYRUS_CHAT_FIRST_TIME_OPENED = true;
    });

    if(isMobileDevice() && WA_SETTINGS.popup_delay_mobile) {
        setTimeout(() => {
            if(!isWhatsappAlreadyClosed()) {
                let d = new Date();
                d.setTime(d.getTime() + (2 * 60 * 60 * 1000));
                let expires = "expires=" + d.toUTCString();
                document.cookie = "whatsapp_closed=1;" + expires + ";path=/";
                jQuery('#syrus-chat-container .chat-toggle').click();
            }
        }, WA_SETTINGS.popup_delay_mobile);
    }

}

function isMobileDevice() {
    const userAgent = navigator.userAgent.toLowerCase();
    const isMobileUserAgent = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/.test(userAgent);
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    const isPortraitScreen = screenWidth < screenHeight;
  
    return isMobileUserAgent || isPortraitScreen;
}

function isWhatsappAlreadyClosed() {
    let name = "whatsapp_closed=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');

    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();

        if (c.indexOf(name) === 0)
            return c.substring(name.length, c.length) === "1";
    }

    return false;
}