var $simpleCarousel = document.querySelector(".js-carousel--simple");

if ($simpleCarousel) {
    new Glider($simpleCarousel, {
        slidesToShow: 6,
        slidesToScroll: 4,
        draggable: true,
        dots: ".js-carousel--simple-dots",
        // arrows: {
        // 	prev: ".js-carousel--simple-prev",
        // 	next: ".js-carousel--simple-next",
        // },
    });
}

const capitalize = (str, lower = false) =>
    (lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, (match) =>
        match.toUpperCase()
    );

function nf(numero) {
    var numero = parseFloat(numero).toFixed(2).split(".");
    numero[0] = numero[0].split(/(?=(?:...)*$)/).join(".");
    return numero.join(",");
}

window.addEventListener("message", (event) => {
    if (event.data.id === 'setEstrelas') {
        window.setTimeout(() => {
            var element = document.getElementById('idestrelastop');
            var protocol = window.location.protocol;
            var host = window.location.host;
            var href = window.location.href;
            var pathname = window.location.pathname.replace(href, '');
            element.href = protocol + '//' + host + pathname + element.getAttribute('href');
        }, 1000);
    }
});

function setSize(cor) {
    var precoVariavel = $.trim($('.preco-variavel').val());
    var precosVariantes = precoVariavel == '1' ? JSON.parse($('.precos-variantes').val()) : [];
    
    $('#variation_1').empty()
    $('#variation_1').attr('disabled', false)

    $.each(variantes[cor].variations, function (index, value) {
        if (value.var1 == null || value.var1 == "") {
            $('#div-tamanhos').hide();
        }

        var variacao = value.var1 + '|' + value.var2 + '|' + value.var3;
        if (value.preco_adicional > 0 && precosVariantes[variacao]) {
            value.preco_adicional = precosVariantes[variacao].adicional;
        }

        var textValue = value.var1 ;
        if (value.quantidade <= 0) {
           textValue = value.var1 + ' Sem estoque no momento';
        } else if (!mostrarAPartirDe && value.preco_adicional > 0) {
            textValue = value.var1 + ' + R$' + (value.preco_adicional.toFixed(2)).replace('.', ',');
        }

        $('#variation_1').append($('<option>', {
            disabled: value.quantidade <= 0,
            value: value.var1.toUpperCase(),
            text: textValue.toUpperCase()
        }))
    });
}

function setPapel(cor, papel) {
    var precosVariantes = JSON.parse($('.precos-variantes').val());

    $('#variation_1').empty();
    var variacao = '|' + cor + '|' + papel;
    
    let tamanhos = Object.keys(precosVariantes).filter(function (preco) {
        return preco.indexOf(variacao) >= 0 ? preco : false;
    });

    let primeiraOpcao = null;
    $.each(tamanhos, function (index, value) {
        var dadosPreco = precosVariantes[value];
        var value = value.replace(variacao, '');
        var texto = value + (dadosPreco.precoFinal > 0 ? ' - R$' + dadosPreco.precoFinal.toFixed(2).replace('.', ',')  : '');

        if (index == 0) {
            primeiraOpcao = dadosPreco.precoFinal;
        }

        $('#variation_1').append($('<option>', {
            disabled: value.quantidade <= 0,
            value: value.toUpperCase(),
            text: texto.toUpperCase()
        }));
    });

    $('#variation_1').attr('disabled', false);
    $('#price_display').html(
        `<div class="product-page__price--variant">R$ ${nf(primeiraOpcao)}</div>`
    );
}

$(window).on('pageshow', function () {
    if ($('.preco-variavel').val() == '1' && $('#variation_2').val() && $('#variation_3').val()) {
        setPapel($('#variation_2').val(), $('#variation_3').val())
    }

    $('#variation_2').change(function () {
        var url = $(this).find('option:selected').data('img-option');
        var cor = $(this).val()
        var possuiPapel = $('#variation_3').val();
        if (cor == null || cor == '' || cor == undefined) {
            $('#variation_1').empty()
            $('#variation_1').attr('disabled', true);
            return;
        }
        
        if (typeof possuiPapel !== 'undefined') {
            $('#variation_3').change(function () {
                var papel = $(this).val();
                setPapel(cor, papel)
            });
        } else {
            setSize(cor)
        }
        $("[data-url='" + url + "']").trigger('click');
    }).trigger('change');

    if ($("#variation_2 > option").length == 2) {
        $("#variation_2 > option").each(function () {
            if ($(this).val() != '') {
                $(this).attr('selected', 'true');
                $("#variation_2").trigger('change');
            }
        });
    }
})

$(document).ready(function () {
    var precoVariavel = $.trim($('.preco-variavel').val());
    var precosVariantes = precoVariavel == '1' 
        ? JSON.parse($('.precos-variantes').val())
        : [];

    function setSizeMultiplo(cor, idProduto) {
        $(`.variation_1[data-produto="${idProduto}"]`).empty()
        $(`.variation_1[data-produto="${idProduto}"]`).attr('disabled', false)
        variantesProduto = $(`.variation_2[data-produto="${idProduto}"]`).data('variantes');
        
        $.each(variantesProduto[cor].variations, function (index, value) {
            if (value.var1 == null || value.var1 == "") {
                $('#div-tamanhos').hide();
            }
            var textValue = value.var1 ;
            if (value.quantidade <= 0) {
               textValue = value.var1 + ' Sem estoque no momento';
            }
            $(`.variation_1[data-produto="${idProduto}"]`).append($('<option>', {
                disabled: value.quantidade <= 0,
                value: value.var1.toUpperCase(),
                text: textValue.toUpperCase()
            }))
        })
    }

    $('.variation_2').change(function () {
        var url = $(this).find('option:selected').data('img-option');
        var cor = $(this).val()
        var idProduto = $(this).data('produto');

        if (cor == null || cor == '' || cor == undefined) {
            $(`.variation_1[data-produto="${idProduto}"]`).empty()
            $(`.variation_1[data-produto="${idProduto}"]`).attr('disabled', true);
            return;
        }
        setSizeMultiplo(cor, idProduto)
        $("[data-url='" + url + "']").trigger('click');
    }).trigger('change');


    var firstImage = $(".glider-slide").first().attr("href");
    $("#montink-innerzoom img").attr("src", firstImage);
    initInnerZoom();

    function verificarDisponibilidadeEstoque(produtoId, tamanho) {
        // $('#variation_2 option').attr('disabled', false);

        var disabled = produtosIndisponiveis[produtoId] && produtosIndisponiveis[produtoId][tamanho];

        $.each(disabled, function () {
            var value = this.split('-').join(' ');
            value = capitalize(value);
            value = value.replace('estonada', 'estonad');
            value = value.replace('estonado', 'estonad');

            var option = $('#variation_2 option[value^="' + value + '"]');
            option.text();
            option.attr('disabled', true);
            option.text(value + ' (Sem estoque no momento)');
        });
    }

    $('#variation_1').on('change', function () {
        verificarDisponibilidadeEstoque(produtoId, $(this).val());
    });

    var corUnica = $('#variation_2').is('input[type="hidden"]');
    if (corUnica) {
        $('#variation_1').find('option').each(function () {
            var tamanho = $(this).attr('value');
            var cor = $('#variation_2').val();
            cor = cor.replace('estonada', 'estonad');
            cor = cor.replace('estonado', 'estonad');

            var semEstoque = (
                produtosIndisponiveis[produtoId] &&
                produtosIndisponiveis[produtoId][tamanho] &&
                produtosIndisponiveis[produtoId][tamanho].indexOf(cor) !== -1
            );

            if (semEstoque) {
                $(this).attr('disabled', true);
                $(this).text($(this).text() + ' (Sem estoque no momento)');
                $(this).prop('selected', false);
            }
        });
    }

    $("#btn-denunciar").on("click", function (event) {
        $("#img_denunciada").attr("src", firstImage);
    });

    $(".glider-slide").on("click", function (event) {
        event.preventDefault();
        $("#montink-innerzoom img").attr("src", $(this).attr("href"));
        initInnerZoom();
    });

    $(window).on("resize", function () {
        initInnerZoom();
    });

    if (typeof produtoId !== 'undefined') {
        verificarDisponibilidadeEstoque(produtoId, $('#variation_1').val());
    }

    if (precoVariavel == '1') {
        var textoOriginal = $.trim($('#price_display').html());
        $('#variation_1, #variation_2, #variation_3').change(function () {
            var var1 = $.trim($('#variation_1').val());
            var var2 = $.trim($('#variation_2').val());
            var var3 = $.trim($('#variation_3').val());
            var index = var1 + '|' + var2 + '|' + var3;

            if (precosVariantes[index]) {
                $('#price_display').html(
                    `<div class="product-page__price--variant">R$ ${nf(precosVariantes[index].precoFinal)}</div>`
                );
            } else {
                $('#price_display').html(textoOriginal);
            }
        });
    }
});
function initInnerZoom() {
    if ($("#montink-innerzoom img").length == 0) {
        return;
    }

    $("#montink-innerzoom img").imagezoomsl({
        loadopacity: 0.1,
        innerzoom: true,
        stepzoom: .5,
        zoomrange: [2, 8],
        zoomstart: 1,
        magnifierborder: "none",
        descarea: ".galery-montink",
        magnifycursor: "zoom-in",
    });
}
