let categoryContainer = [];
let firstLink = '';
let slotsContainer = [];
let getAllSlotsRequested = false;
let hash = window.location.hash.substring(1);
let [category] = hash.split('_');
let getAllSlotsParameters = {
    category: category || 'AllGames',
    provider: '',
    searchText: '',
    sort: 'default',
    page: 1
};
$(document).ready(function () {
    getProviders();
    

    $(window).on('hashchange', function () {
        getProviders();
    });

});
function handleHashChange() {
    let hash = window.location.hash.substring(1);
    let [category, providerName] = hash.split('_');
    if (category) {
        getAllSlotsParameters.category = category;
    } else {
        getAllSlotsParameters.category = 'AllGames';
    }

    if (providerName) {

        let provider = categoryContainer.find(p => p.ActionName === providerName);
        let providerId = provider ? provider.ID : '';
        getAllSlotsParameters.provider = providerId;

    }
    else {
        getAllSlotsParameters.provider = '';
    }

    $('.games-menu__link').removeClass('active');
    $(`.games-menu__link[data-action="${getAllSlotsParameters.category}"]`).addClass('active');

    const blockBarTitle = $(`.games-menu__link[data-action="${getAllSlotsParameters.category}"]`).first().find('.personal-categories__item__title').text();
    $('#block__title-bar-text').text(blockBarTitle);

    if ($('.category-filter__link').hasClass('category-filter__link--active')) {
        $('.category-filter__link').removeClass('category-filter__link--active');
    }
    $('.category-filter__button').html(`${globalFilters}`);

    $('#slotcontainer').empty();
    $('#slotcontainer1').empty();
    $('#searchSlots').val('');
    $('#slotcontainer').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');
    $('#slotcontainer1').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');

    resetSorts();

    getAllSlots();

    getProviders();
}

//getAllSlots();

$(document).ready(function () {
    handleHashChange();

    $(window).on('hashchange', function () {
        handleHashChange();
    });
});


$(document).on('click', '.games-menu__link', function (e) {
    e.preventDefault();
    let category = $(this).attr('data-action');
    //let currentHash = window.location.hash.substring(1);

    let hash = category

    if (window.location.hash.substring(1) !== hash) {
        window.location.hash = '#' + hash;
    }


    $('.games-menu__link').removeClass('active');
    $(this).addClass('active');

    const blockBarTitle = $(this).first().find('.personal-categories__item__title').text();
    $('#block__title-bar-text').text(blockBarTitle);

    if ($('.category-filter__link').hasClass('category-filter__link--active')) {
        $('.category-filter__link').removeClass('category-filter__link--active');
    }
    $('.category-filter__button').html(`${globalFilters}`);

    getAllSlotsParameters.category = category;
    getAllSlotsParameters.searchText = '';
    getAllSlotsParameters.page = 1;

    $('#slotcontainer').empty();
    $('#slotcontainer1').empty();
    $('#searchSlots').val('');
    $('#slotcontainer').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');
    $('#slotcontainer1').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');

    resetSorts();

    //getAllSlots();
});


$(document).on('click', '.category-filter__link', function (e) {
    e.preventDefault();
    let providerId = $(this).attr('data-id');
    //let providerName = $(this).attr('data-name').replace(/\s+/g, '');
    let providerName = $(this).attr('data-action');
    let currentHash = window.location.hash.substring(1);
    let category = currentHash.split('_')[0] || 'AllGames';
    let hash = `${category}_${providerName}`;

    if (window.location.hash.substring(1) !== hash) {
        window.location.hash = '#' + hash;
    }

    let changedSlotsTitle = $(this).attr('data-name');
    $('.slots__title').empty();
    $('.slots__title').html(changedSlotsTitle);

    $('.category-filter__link').removeClass('category-filter__link--active');

    $(this).addClass('category-filter__link--active');

    $('.category-filter__button').html($(this).find('span').html());

    //getAllSlotsParameters.provider = providerId;
    getAllSlotsParameters.searchText = '';
    getAllSlotsParameters.page = 1;

    $('#slotcontainer').empty();
    $('#slotcontainer1').empty();
    $('#searchSlots').val('');
    $('#slotcontainer').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');
    $('#slotcontainer1').append('<div class="loader-container game-loader"><span class="loader5"></span></div>');

    resetSorts();
});



let searchSlotsTimeout;

$(document).on('keyup', '#searchSlots', function (e) {
    e.preventDefault();
    e.stopPropagation();

    const textValue = $(this).val().toLowerCase();

    if (textValue.length > 0 && textValue.length < 3) {
        return;
    }

    clearTimeout(searchSlotsTimeout);

    searchSlotsTimeout = setTimeout(function () {
        searchSlots(textValue);
    }, 1400);
});
function searchSlots(typedText) {

    getAllSlotsParameters.searchText = typedText;
    getAllSlotsParameters.page = 1;

    $('#slotcontainer').empty();
    $('#slotcontainer').append(`<span class="loader6"></span>`);
    resetSorts();

    getAllSlots();
}


function getProviders() {
    $.ajax({
        url: `/${languageCode}/Slots/GetAllSlotPages`,
        type: 'GET',
        dataType: 'json',
        data: 'category=' + getAllSlotsParameters.category,
        async: true,
        success: function (res) {

            categoryContainer = res;
            $('#categoriesCtn').empty();
            for (let i = 0; i < res.length; i++) {

                $('#categoriesCtn').append(`
                  <div class="products-navigation-filter-list-item category-filter__link"
                        data-id="${res[i].ID}"
                        data-action="${res[i].ActionName}"
                        data-name="${res[i].SlotPageName}">
                    <div class="products-navigation-filter-list-item-left">
                      <span class="category-filter__cat-name" title="${res[i].SlotPageName}">${res[i].SlotPageName}</span>
                    </div>
                    <span class="category-filter__games-number">${res[i].Count}</span>
                  </div>
                `);
            };

            //if (CategoryContainer.length && slotsContainer.length) {
            //    startGettingGames();
            //}
        }
    });
}

$('#azsort').click(function (e) {
    e.preventDefault();

    $('.sort-filter__link').removeClass('sort-filter__link--active');
    $(this).addClass('sort-filter__link--active');

    $('#slotcontainer').empty();
    $('#slotcontainer1').empty();

    getAllSlotsParameters.sort = 'azsort';
    getAllSlotsParameters.page = 1;

    getAllSlots();
});


$('#defor').click(function (e) {
    e.preventDefault();

    $('.sort-filter__link').removeClass('sort-filter__link--active');
    $(this).addClass('sort-filter__link--active');


    $('#slotcontainer').empty();
    $('#slotcontainer1').empty();


    getAllSlotsParameters.sort = 'default';
    getAllSlotsParameters.page = 1;

    getAllSlots();
});


$(document).on('click', '.slot-button__smile', function (e) {
    e.stopImmediatePropagation();
    e.preventDefault();

    if ($(this).attr('href').indexOf('&freeplay=1') > 0) {

        if ($('#slots-modal').is(':visible')) {

            let eventType = 'addGame';

            playEvents($(this));
            addSlotInCookie(e);
            checkMultiSessionGames($(this), eventType);

        } else {

            slotPlayEvent(e, $(this));
        }
    }
    else {
        $('#login-modal').modal('show');
    }
});


$(document).on('click', '.slot_play-button', function (e) {
    e.stopImmediatePropagation();
    e.preventDefault();

    if (isAuthenticated) {

        if ($('#slots-modal').is(':visible')) {

            let eventType = 'addGame';

            playEvents($(this));
            addSlotInCookie(e);
            checkMultiSessionGames($(this), eventType);

        } else {
            slotPlayEvent(e, $(this));
        }
    } else {
        $('#login-modal').modal('show');
    }
});


$(document).on('click', '.addFav', function (e) {
    e.stopPropagation();

    if (!isAuthenticated) {
        $('#login-modal').modal('show');
        return;
    }

    var that = $(this);
    var id = $(this).attr('x_id');

    if ($(this).hasClass('snfavact')) {
        $.ajax({
            type: 'POST',
            data: 'Id=' + id,
            url: `/${languageCode}/Slots/RemoveFavSlot`,
            success: function (res) {
                that.removeClass('snfavact');
                for (var i = 0; i < slotsContainer.length; i++) {
                    if (slotsContainer[i].ID == id) {
                        slotsContainer[i].isFav = false;
                    }
                }
            }
        });
    }
    else {
        $.ajax({
            type: 'POST',
            data: 'Id=' + id,
            url: `/${languageCode}/Slots/AddFavoriteSlot`,
            success: function (res) {
                that.addClass('snfavact');
                for (var i = 0; i < slotsContainer.length; i++) {
                    if (slotsContainer[i].ID == id) {
                        slotsContainer[i].isFav = true;
                    }
                }
            }
        });
    }
});


function resetSorts() {
    $('.sort-filter__link').removeClass('sort-filter__link--active');
    $('#defor').addClass('sort-filter__link--active');
}


function getAllSlots() {

    $.ajax({
        url: `/${languageCode}/Slots/GetAllSlots`,
        type: 'GET',
        dataType: 'json',
        data: 'category=' + getAllSlotsParameters.category + '&provider=' + getAllSlotsParameters.provider + '&searchText=' + getAllSlotsParameters.searchText + '&sort=' + getAllSlotsParameters.sort + '&page=' + getAllSlotsParameters.page,
        async: true,
        success: function (res) {

            /*console.log('GetAllSlots: ', res);*/
            slotsContainer = res;
            $('#slotcontainer .loader6').remove();

            if (slotsContainer.length > 0) {

                displayGamesBlock();
                displayGamesList();

            } else {

                if ($('#slotcontainer .game-result-empty').length === 0) {
                    $("#slotcontainer").append(`
                        <div class="game-result-empty" style="width:100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                            <span style="font-size: 14px; color: #858C91;"> 0 ${globalResult} </span>
                        </div>
                    `).show();
                }

                if ($('#slotcontainer1 .game-result-empty').length === 0) {
                    $("#slotcontainer1").append(`
                        <div class="game-result-empty" style="width:100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                            <span style="font-size: 14px; color: #858C91;"> 0 ${globalResult} </span>
                        </div>
                    `).show();
                }
            }

            if ($('#slotcontainer .game-loader').length > 0) {
                $('#slotcontainer .game-loader').remove();
            }
            if ($('#slotcontainer1 .game-loader').length > 0) {
                $('#slotcontainer1 .game-loader').remove();
            }

            if ($('#slotcontainer .game-scroll-loader').length > 0) {
                $('#slotcontainer .game-scroll-loader').remove();
            }
            if ($('#slotcontainer1 .game-scroll-loader').length > 0) {
                $('#slotcontainer1 .game-scroll-loader').remove();
            }
        }
    });
}


function displayGamesBlock() {
    /*console.log(slotsContainer)*/
    for (let i = 0; i < slotsContainer.length; i++) {

        let isFavContent = ``;
        let imageUrl = slotsContainer[i].ImageName.startsWith("http")
            ? slotsContainer[i].ImageName
            : ('/Content/themes/v1/GameImages/' + slotsContainer[i].ImageBase + "/" + slotsContainer[i].ImageName);
        let freeplayBtn = '';
        let cashRaceFrame = '';
        let dropsAndWin = '';
        let IsHot = ''
        let IsNew = ''
        if (slotsContainer[i].Freeplay) {
            freeplayBtn = `
                <a class="circle slot-button__smile"
                    data-gameId="${slotsContainer[i].ID}"
                    data-id="${slotsContainer[i].SlotPageID}"
                    data-name="${slotsContainer[i].GameName}"
                    target="_blank"
                    href="/${languageCode}/${slotsContainer[i].RealUrl}&freeplay=1">
                    <i class="far fa-smile"></i>
                </a>
            `;
        }

        /*if (filteredGames[currentGameBlock].isInActiveTournament) {

            slotChildren.find('.cashrace_frame__container').html('<img src="/Content/img/slot-frame-desktop.png" />');
        }*/
        if (slotsContainer[i].isInActiveTournament == true) {
            cashRaceFrame = `<img src="/Content/img/slot-frame-desktop.png" />`
        }
        if (slotsContainer[i].HasIngameDropsAndWins == true) {
            dropsAndWin = `<img src="/Content/img/dropsandwins-sign.png" />`

        }

        if (slotsContainer[i].IsHot) {
            IsHot = '<span class="sn-hot-slot  hot" >HOT</span>'
        }
        if (slotsContainer[i].IsNew) {
            IsNew = '<span class="sn-hot-slot  new__item" >NEW</span>'
        }

        $('#slotcontainer').append(`
          <div class="col-6 col-sm-4 col-md-2 game-bottom-list-contaier__items slot-container__item1"
            data-sort="${slotsContainer[i].GameName}"
            data-for-search="${slotsContainer[i].GameName.toLowerCase()}">
            <div class="cashrace_frame__container">${cashRaceFrame}</div>
            ${IsHot} 
            ${IsNew}
            <div class="hot-new__container ">${dropsAndWin}</div>
            
               
            <div class="all-games-hover slots-hover" style="display: none;">

              <a role="button" class="circle favourite addFav ${slotsContainer[i].isFav ? 'snfavact' : ''}"
                 x_id="${slotsContainer[i].ID}">
                <i class="far fa-star"></i>
                <i class="fa fa-star"></i>
              </a>${isFavContent}

                <a class="slot_play-button" 
                  data-gameId="${slotsContainer[i].ID}"
                  target="_blank"
                  data-id="${slotsContainer[i].SlotPageID}"
                  href="/${languageCode}/${slotsContainer[i].RealUrl}"
                  data-name="${slotsContainer[i].GameName}"
                >
                  <i class="fa fa-play-circle"></i>
                </a>
                <div class="freeplay_container">${freeplayBtn}</div>
             </div>
              <a class="all-games-href" href="">
                <img class="all-games-images"
                  src="${imageUrl}"
                  data-image="${imageUrl}"
                  alt="${slotsContainer[i].DemoUrl}" loading="lazy"
                  onerror="if(this.src.indexOf('/content/img/nophoto.jpg') < 0) this.src = '/content/img/nophoto.jpg';">
              </a>
              <div class="all-games-names">${slotsContainer[i].GameName}</div>
                
          </div>
        `);

    }
}

function displayGamesList() {

    for (let i = 0; i < slotsContainer.length; i++) {

        $('#slotcontainer1').append(`
            <div class="col-6 col-sm-3 game-bottom-list-contaier__items-list"
                  data-sort="${slotsContainer[i].GameName}"
                  data-for-search="${slotsContainer[i].GameName.toLowerCase()}"
            >
              <a data-id="${slotsContainer[i].SlotPageID}"
                  data-gameId="${slotsContainer[i].ID}"
                  class="sn-listview-block1 slotwindow"
                  data-name="${slotsContainer[i].GameName}"
                  href="/${languageCode}/${slotsContainer[i].RealUrl}"
              >
                <img src="/Content/themes/v1/ProviderImages/${slotsContainer[i].imageUrl}" loading="lazy"
                      onerror="if(this.src.indexOf('/Content/ProviderImages/default.png') < 0) this.src = '/Content/ProviderImages/default.png';"
                      alt="${slotsContainer[i].DemoUrl}"
                >
                ${slotsContainer[i].GameName}
              </a>
            </div>
         `);
    }
};


function slotPlayEvent(slotEvent, slotThis) {

    let gameName = slotThis.attr('data-name');

    $('.inner-slot-name').text(gameName);

    if ((slotThis.attr('href').includes("StartPragmaticPlay"))) {
        slotThis.attr('data-width', "1024");
        slotThis.attr('data-height', "576");
    }

    onPlayButtonClicked(slotEvent, slotThis);

    if (typeof addSlotInCookie === 'function') {
        addSlotInCookie(slotEvent);
    }

    $('#searchSlots').val('');
    filterEvent = slotThis;

    if ($('.openInMaxSize').hasClass('active')) {

        let providerName = CategoryContainer.filter(i => i.ID == slotThis.attr('data-id'));

        $('.sameProviderGamesName').text(`${providerName[0].SlotPageName} ${globalSlots}`);

        if (provideSlotsVisible) {

            provideSlotsVisible = false;
            getGames(filterEvent, '');

        } else if (($('.tryNew__container').find(slotThis).length > 0)) {

            providerSlotsNewVisible = false;
            getGames(filterEvent, '');
        }

    } else if (provideSlotsVisible && ($('.openInDualTab').hasClass('active') || $('.openInQuadTab').hasClass('active'))) {
        let eventType = 'addGame';

        provideSlotsVisible = false;
        checkMultiSessionGames(filterEvent, eventType);
    }
}
$('#searchSlots').on('blur', function () {
    $('meta[name="viewport"]').attr('content', 'width=device-width, initial-scale=1.0');
});
$(window).scroll(function (e) {
    const slotContainerBlockScrollFromBottom = $('#slotcontainer').offset().top - document.body.scrollTop + $('#slotcontainer').height();
    const slotContainerListScrollFromBottom = $('#slotcontainer1').offset().top - document.body.scrollTop + $('#slotcontainer1').height();
    const windowScrollFromBottom = $(window).scrollTop() + + $(window).height();

    /*console.log($('#slotcontainer .loader5').length);
    console.log($('#slotcontainer1 .loader5').length);
    console.log(!$('#slots-modal').is(':visible')); 
    console.log($('#slotcontainer .loader5').length);*/
    if ($('#slotcontainer .loader5').length <= 0
        && $('#slotcontainer1 .loader5').length <= 0
        && !$('#slots-modal').is(':visible')
        && $('#slotcontainer .loader6').length <= 0) {

        if ((windowScrollFromBottom >= slotContainerBlockScrollFromBottom) && $('.blockView').hasClass('slot-tabs--active')) {

            if ($('#slotcontainer .game-scroll-loader').length > 0) {
                return
            }
            if (slotsContainer.length > 20) {
                $('#slotcontainer').append('<div class="game-scroll-loader" style="width:100%; height: 100%; display: flex; align-items: center; justify-content: center;"><span class="loader5"></span></div>');

                getAllSlotsParameters.page += 1;
                getAllSlots();
            }
        }

        if ((windowScrollFromBottom >= slotContainerListScrollFromBottom) && $('.listView').hasClass('slot-tabs--active')) {

            if ($('#slotcontainer1 .game-scroll-loader').length > 0) {
                return
            }
            if (slotsContainer.length > 20) {
                $('#slotcontainer1').append('<div class="game-scroll-loader" style="width:100%; height: 100%; display: flex; align-items: center; justify-content: center;"><span class="loader5"></span></div>');

                getAllSlotsParameters.page += 1;
                getAllSlots();
            }
        }
    }
});