var capiClass = new function () {
    this.baseUrl = 'https://my.capibox.com';
    this.token = '84c5298b-fb30-4a7e-97b7-ca6f54cc396c';
    this.debugMode = '0';

    this.makeid = (length) => {
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        const charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() *
                charactersLength));
        }
        return result;
    }

    const uuidKey = 'capi_key';
    const lUuid = localStorage.getItem(uuidKey);
    if (lUuid) {
        this._uuid = lUuid;
    } else {
        this._uuid = this.makeid(16);
        localStorage.setItem(uuidKey, this._uuid);
    }
    // setTimeout(() => {
    //     try {
    //         // @ts-ignore
    //         window.fbq('trackCustom', 'CapiboxExternalId', {}, {external_id: this._uuid});
    //     } catch (e) {
    //
    //     }
    // }, 500);


    this.defaultRequestOptions = () => {
        return {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            referrerPolicy: 'unsafe-url'

        }
    };

    this.sendRequest = (email, orderId) => {
        if (email || orderId) {
            const requestOptions = {
                ...this.defaultRequestOptions(),
                body: JSON.stringify({
                    email,
                    fbc: this.getCookieByName('_fbc'),
                    fbp: this.getCookieByName('_fbp'),
                    externalId: this._uuid,
                    token: this.token,
                    orderId,
                })
            };

            fetch(this.baseUrl + '/app/public/add', requestOptions).then(() => {
            });

            if (this.debugMode === '1') {
                this.sendLog(email, orderId, 'NA OK', {'type': 'front_email_lead'})
            }
        }
    }

    this.sendLog = (email, orderId, eventId, extraData) => {
        const requestOptions = {
            ...this.defaultRequestOptions(),
            body: JSON.stringify({
                email,
                fbc: this.getCookieByName('_fbc'),
                fbp: this.getCookieByName('_fbp'),
                externalId: this._uuid,
                token: this.token,
                orderId,
                eventId,
                extraData
            })
        };

        fetch(this.baseUrl + '/app/public/log', requestOptions).then(() => {
        });
    }

    this.start = () => {
        const emailFields = document.getElementsByName('email');
        if (emailFields.length > 0) {
            emailFields[0].onblur = () => {
                this.sendRequest(emailFields[0].value)
            };
        }
        const emailFields2 = document.getElementsByName('fl_builder_email');
        if (emailFields2.length > 0) {
            emailFields2[0].onblur = () => {
                this.sendRequest(emailFields2[0].value)
            };
        }
        const emailFields3 = document.getElementsByName('fl-subscribe-form-email');
        if (emailFields3.length > 0) {
            emailFields3[0].onblur = () => {
                this.sendRequest(emailFields3[0].value)
            };
        }

        const emailFields4 = document.getElementsByTagName('input');
        if (emailFields4.length > 0) {
            for (var i = 0; i < emailFields4.length; i++) {
                var f = emailFields4[i];
                if (!!f.id && f.id.indexOf('form-input') === 0) {
                    f.onblur = (e) => {
                        var val = e.target;
                        if (!!val.value && val.value.indexOf('@') >= 0) {
                            this.sendRequest(val.value);
                        }
                    };
                }
            }
        }

        // WIX
        const isThankYou = document.querySelectorAll('*[data-hook="ThankYouPageAppDataHook.root"]');
        if (isThankYou.length > 0) {
            const pathName = window.location.pathname;
            const pathNameArr = pathName.split('/');
            this.sendRequest('', pathNameArr[pathNameArr.length - 1]);
        }
    }
    this.getCookieByName = (name) => {
        const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        if (match) {
            return match[2];
        } else {
            return '';
        }
    }
}
setTimeout(() => {
    capiClass.start();
}, 1000);

var capiboxFbq = function (type, options, extraOptions) {
    try {
        var eventId = capiClass.makeid(16);
        window.fbq('track', type, {...options}, {external_id: capiClass._uuid, event_id: eventId});
        const requestOptions = {
            ...capiClass.defaultRequestOptions(),
            body: JSON.stringify({
                fbc: capiClass.getCookieByName('_fbc'),
                fbp: capiClass.getCookieByName('_fbp'),
                externalId: capiClass._uuid,
                eventId: eventId,
                token: capiClass.token,
                type: type,
            })
        };
        fetch(capiClass.baseUrl + '/app/public/set', requestOptions).then(() => {
        });

        if (capiClass.debugMode === '1') {
            capiClass.sendLog('', '', eventId, {
                'type': 'front_fbq',
                'user_type': type,
                'options': options,
                'extraOptions': extraOptions
            })
        }
    } catch (e) {

    }
}

var capiboxWixFbq = function (type, options, extraOptions) {
    try {
        var path = window.location.pathname.split('/');
        var orderId = path[path.length - 1];
        var eventId = capiClass.makeid(16);
        window.fbq('track', type, {...options}, {external_id: capiClass._uuid, event_id: eventId}
        );
        const requestOptions = {
            ...capiClass.defaultRequestOptions(),
            body: JSON.stringify({
                fbc: capiClass.getCookieByName('_fbc'),
                fbp: capiClass.getCookieByName('_fbp'),
                externalId: capiClass._uuid,
                eventId: eventId,
                token: capiClass.token,
                type: type,
                orderId: orderId
            })
        };
        fetch(capiClass.baseUrl + '/app/public/set', requestOptions).then(() => {
        });

        if (capiClass.debugMode === '1') {
            capiClass.sendLog('', '', eventId, {
                'type': 'front_fbq',
                'user_type': type,
                'options': options,
                'extraOptions': extraOptions
            })
        }
    } catch (e) {

    }
}
