jQuery(function () {
    let currencySymbol;
    let isoCode;

    function initSliders(isoCode, currencySymbol) {
        let depositSlider = document.querySelector(".deposit-slider");
        let usageTimeSlider = document.querySelector(".usage-time-slider");
        let suffix;
        switch (isoCode.toUpperCase()) {
            case "IT":
                suffix = "Giorni";
                break;
            default:
                suffix = "Days";
        }
        noUiSlider.create(depositSlider, {
            range: {
                min: 250,
                max: 5000
            },
            step: 50,
            start: 250,
            pips: {
                mode: 'range',
                density: 3,
                format: wNumb({
                    prefix: currencySymbol
                })
            },
            connect: 'lower',
            tooltips: [wNumb({
                decimals: 0,
                prefix: currencySymbol
            })]
        });

        noUiSlider.create(usageTimeSlider, {
            range: {
                min: 1,
                max: 30
            },
            step: 1,
            start: 1,
            pips: {
                mode: 'range',
                density: 3,
                format: wNumb({
                    suffix: " " + suffix
                })
            },
            connect: 'lower',
            tooltips: [wNumb({
                decimals: 0,
                suffix: " " + suffix
            })]
        });

        depositSlider.noUiSlider.on('update', function (e) {
            calculateProfit(parseInt(depositSlider.noUiSlider.get()), parseInt(usageTimeSlider.noUiSlider.get()));
        });

        usageTimeSlider.noUiSlider.on('update', function (e) {
            calculateProfit(parseInt(depositSlider.noUiSlider.get()), parseInt(usageTimeSlider.noUiSlider.get()));
        });
    }

    function calculateProfit(depositVal, usageTimeVal) {
        // let depositVal = parseInt(depositSlider.noUiSlider.get());
        // let usageTimeVal = parseInt(usageTimeSlider.noUiSlider.get());
        let multiplier = 1 + 0.136 * usageTimeVal;
        let potentialPayout = Math.round(depositVal * multiplier);
        $('.potential-payout-sum').text(potentialPayout.toString());
    }

    function updateNames(peopleArr) {
        let randIndex = Math.floor(Math.random() * (peopleArr.length - 1));
        let randPersonObj = peopleArr[randIndex];
        let fullName = randPersonObj.name;
        let nameSpan = $('.name');
        $('.city').text(randPersonObj.region);
        let wrapper = $('.notification-wraper');
        $('.notification-body').find('img').attr('src', randPersonObj.photo);
        wrapper.find('.user-profit-sum').text((Math.floor(Math.random() * 1000 + 100).toString()));
        nameSpan.text(fullName);
        wrapper.fadeIn(300);
        setTimeout(function () {
            wrapper.fadeOut(300);
            setTimeout(function () {
                updateNames(peopleArr);
            }, 5000);
        }, 2500);
    }

    document.addEventListener('visitorsLocated', function (e) {
        isoCode = e.detail.client.location.countryIsoCode.toLowerCase();
        $('.flag').attr('src', 'img/flags/4x3/' + isoCode + ".svg");
        let country = e.detail.client.location.country;

        switch (e.detail.countryIsoCode) {
            case 'GB': currencySymbol = '£'; break;
            case 'BE': currencySymbol = '€'; break;
            case 'EL': currencySymbol = '€'; break;
            case 'LT': currencySymbol = '€'; break;
            case 'PT': currencySymbol = '€'; break;
            case 'BG': currencySymbol = '€'; break;
            case 'ES': currencySymbol = '€'; break;
            case 'LU': currencySymbol = '€'; break;
            case 'RO': currencySymbol = '€'; break;
            case 'CZ': currencySymbol = '€'; break;
            case 'FR': currencySymbol = '€'; break;
            case 'HU': currencySymbol = '€'; break;
            case 'SI': currencySymbol = '€'; break;
            case 'DK': currencySymbol = '€'; break;
            case 'HR': currencySymbol = '€'; break;
            case 'MT': currencySymbol = '€'; break;
            case 'SK': currencySymbol = '€'; break;
            case 'DE': currencySymbol = '€'; break;
            case 'IT': currencySymbol = '€'; break;
            case 'NL': currencySymbol = '€'; break;
            case 'FI': currencySymbol = '€'; break;
            case 'EE': currencySymbol = '€'; break;
            case 'CY': currencySymbol = '€'; break;
            case 'AT': currencySymbol = '€'; break;
            case 'SE': currencySymbol = '€'; break;
            case 'IE': currencySymbol = '€'; break;
            case 'LV': currencySymbol = '€'; break;
            case 'PL': currencySymbol = '€'; break;
            case 'ZA': currencySymbol = 'R'; break;
            default: currencySymbol = '$'; break;
        }

        initSliders(isoCode, currencySymbol);


        var url = "/uinames/api/?amount=50&ext",
            region = ['Great Britain', 'United Kingdom'].indexOf(country) > -1 ? 'England' : country;
        console.log(country);

        $.ajax({
            method: "GET",
            url: url + "&region=" + region,
            success: function (data) {
                updateNames(data);
                updateTable(data);
            },
        })
    });

    function updateTable(peopleArr) {

        let fx_array = [
            'EUR',
            'USD',
            'CHF',
            'GBP',
            'JPY',
            'AUD',
            'CAD',
            'NZD'
        ];

        let crypto_array = [
            'BTC',
            'LTC',
            'BCH',
            'XRP',
            'EOS',
            'BNB'
        ];

        let countries_arr = [
            "DE",
            "ES",
            "MX",
            "GR",
            "CH",
            "FR",
            "AU",
            "SI",
            "LV",
            "PA",
            "ZA",
            "SE"
        ];

        // crypto
        let tr = $("<tr></tr>");
        let cryptoRandIndex1 = Math.floor(Math.random() * 5);
        let cryptoRandIndex2 = Math.floor(Math.random() * 7);
        let currencyAsset = crypto_array[cryptoRandIndex1] + "/" + fx_array[cryptoRandIndex2];
        let currencyTd = $("<td>" + "<button>" + currencyAsset + "</button>" + "</td>");
        // Flag

        let randFlagIndex = Math.floor(Math.random() * (countries_arr.length - 1));
        let flagTd = $('<td class="table-img"><img alt="Flag" src="img/flags/4x3/' + isoCode + '.svg"></td>');
        // console.log("flag", isoCode);
        // Name
        let randIndex = Math.floor(Math.random() * (peopleArr.length - 1));
        // console.log(randIndex);
        let randPersonObj = peopleArr[randIndex];
        let randPersonFullName = randPersonObj.name + " " + randPersonObj.surname[0] + ".";
        let nameTd = $("<td>" + randPersonFullName + "</td>");

        // Earn
        let randProfit = Math.floor(100 + Math.random() * 2900).toString();
        let sumTd = $("<td><button>" + currencySymbol + randProfit + "</button></td>");

        // Time
        let time = new Date();
        let hh = time.getHours();
        let mins = time.getMinutes();
        let ss = time.getSeconds();
        time = hh.toString().padStart(2, "0") + ":" + mins.toString().padStart(2, "0") + ":" + ss.toString().padStart(2, "0");
        let timeTd = $('<td>' + time + '</td>');
        tr.append(flagTd, nameTd, sumTd, currencyTd, timeTd);
        $('table tbody').prepend(tr);
        $('table tbody tr').last().remove();


        setTimeout(function () {
            updateTable(peopleArr);
        }, 2500);
    }

    function incrementTotalProfits() {
        let sum = parseInt($('.total-profit-sum').text().replace(/,/g, ""));
        sum += Math.floor(Math.random() * 9000 + 1000);
        let newSumStr = [];
        let threeDigits;

        while (sum > 0) {
            threeDigits = Math.floor(sum % 1000).toString().padStart(3, '0');
            ;
            sum = Math.floor(sum / 1000);
            newSumStr.push(threeDigits);
        }

        newSumStr.reverse();
        newSumStr = newSumStr.join(',');

        $('.total-profit-sum').text(newSumStr);

        setTimeout(function () {
            incrementTotalProfits();
        }, 5000)

    }

    function incrementActiveUsers() {
        let sum = parseInt($('.users-count').text().replace(/,/g, ""));
        sum++;
        let newSumStr = [];
        let threeDigits;

        while (sum > 0) {
            threeDigits = Math.floor(sum % 1000).toString();
            sum = Math.floor(sum / 1000);
            newSumStr.push(threeDigits);
        }

        newSumStr.reverse();
        newSumStr = newSumStr.join(',');

        $('.users-count').text(newSumStr);
        setTimeout(function () {
            incrementActiveUsers();
        }, 5000)
    }

    incrementTotalProfits();
    incrementActiveUsers();

    $(".form-scroll-btn").click(function () {
        $([document.documentElement, document.body]).animate({
            scrollTop: $(".form-header").offset().top
        }, 1000);
    });
});
