let colorPrimary = '#29C0D5';
let colorSuccess = '#50C879';
let colorDanger = '#EF4D57';
let colorWarning = '#F1C735';
let progressSize = 144;

let breakpointSm = 576;
let breakpointMd = 768;
let breakpointLg = 992;
let breakpointXl = 1250;
let breakpoint2xl = 1600;

$(function () {

    let selectedStart = null;
    let selectedEnd = null;

    // Prevent language dropdown from closing when clicking options
    $(document).on('click', '.dropdown.prevent-auto-close .dropdown-menu', function (e) {
        e.stopPropagation();
    });

    function initPicker(input) {
        const $input = $(input);

        $input.daterangepicker({
            autoUpdateInput: false,
            autoApply: true,
            startDate: selectedStart || moment(),
            endDate: selectedEnd || moment(),
            locale: {
                format: 'DD MMM, YYYY',
                cancelLabel: 'Clear'
            }
        });

        $input.on('apply.daterangepicker', function (ev, picker) {
            selectedStart = picker.startDate;
            selectedEnd = picker.endDate;

            $('#date_from').val(selectedStart.format('DD MMM, YYYY'));
            $('#date_to').val(selectedEnd.format('DD MMM, YYYY'));
        });

        $input.on('cancel.daterangepicker', function () {
            $('#date_from, #date_to').val('');
            selectedStart = null;
            selectedEnd = null;
        });


        $input.trigger('click');

    }

    $('#date_from, #date_to').on('focus', function () {
        $(this).data('daterangepicker')?.remove();
        initPicker(this);
    });

    $(".country-code-container").each(function () {

        let container = $(this);

        container.find(".dropdown a").on("click", function (e) {
            e.preventDefault();
            let selectedValue = $(this).data("value");
            let selectedImgSrc = $(this).find("img").attr("src");
            let selectedText = $(this).text().trim();
            container.find("#country").val(selectedValue);
            container.find("button.dropdown-toggle").html(`<img alt="" src="${selectedImgSrc}" /> ${selectedText} <i class="icon icon-chevron-down"></i>`);
        });

        let autoSelectCountry = () => {
            let selectedIndex = container.find("#country option:selected").index() + 1;
            let selectedHTML = container.find(`.choose-country-list a:nth-child(${selectedIndex})`).html();
            selectedHTML = selectedHTML + `<i class="icon icon-chevron-down"></i>`;
            container.find("button.dropdown-toggle").html(selectedHTML);
        }

        autoSelectCountry();
    });

    $(".flatpickr").flatpickr();

    $(".flatpickr-date-time").flatpickr({
        enableTime: true
    });

    $(".flatpickr-daterange").flatpickr({
        mode: "range",
        locale: {
            ...flatpickr.l10ns.ar,
            rangeSeparator: "                              "
        }
    });


    $(".activate-inputs input").on("keyup", function () {

        if ($(this).val()) {
            $(this).next().focus();
            $(this).next().select();
        }

        if ($(this).index() == $(".activate-inputs input").length - 1) {

            if ($(this).val()) {

                let activateCode = '';

                $(this).blur();

                $(".activate-inputs input").each(function () {
                    activateCode += $(this).val();
                });

                $("#activate-code-input").val(activateCode);

                setTimeout(() => {
                    alert("last item submit your form")
                    location.href = "http://localhost/kamashka/homepage.php?authModal=3";
                }, 200);
            }
        }
    });

    if ($('.activate-inputs').length > 0) {
        focusFirstInputInPinCode();
    }

    function initSelect2() {

        $('.select2').each(function () {

            let placeholderVar = $(this).attr("data-placeholder") ? $(this).attr("data-placeholder") : 'select';

            $('.select2').select2({
                placeholder: placeholderVar,
            });

        })

    }

    initSelect2();



    toggleMobileMenu();
    toggleMobileSearch();
    updateSelectedInterests();

    if ($('.products-swiper').length > 0) {
        initProductsSwiper();
    }

    if (window.innerWidth > breakpointLg) {
        initPinningProductDetails();
    }

    if ($('.upload-with-thumbnails-container').length > 0) {
        uploadImagesWithThumbnails();
    }



    // initProductsThumbsSwiper();


});





function toggleMobileMenu() {
    $(".toggle-mobile-menu-button").on("click", function () {
        $(".mobile-menu-popup").toggleClass("show");
        $("body").toggleClass("overflow-hidden");

    });
}


function toggleMobileSearch() {
    $(".toggle-mobile-search-button").on("click", function () {
        $(".mobile-search").toggleClass("show");
        $("body").toggleClass("overflow-hidden");

    });
}



function focusFirstInputInPinCode() {
    $('.activate-inputs .num1').focus();
}

let counterDownTwoMinutes = () => {

    let minutesLabel = document.getElementById("minutes");
    let secondsLabel = document.getElementById("seconds");
    let totalSeconds = 3;

    setInterval(setTime, 1000);

    function setTime() {
        if (totalSeconds > 0) {

            --totalSeconds;
            secondsLabel.innerHTML = pad(totalSeconds % 60);
            minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));

            if (totalSeconds == 0) {
                $(".count-down-numbers-wrapper").html(`<button href="#" class="reset-btn link-primary bold" id="resend-code"> Send code Again </button>`);
            }
        }
    }

    function pad(val) {
        var valString = val + "";
        if (valString.length < 2) {
            return "0" + valString;
        } else {
            return valString;
        }
    }

}

let circularProgress = () => {

    $(".progress-circle").each(function (i, e) {

        let progressEndValue = $(this).data("finished");

        if (progressEndValue > 99) {

            progressEndValue = 99

        }

        let fillColor = '';

        let type = $(this).data("type");

        if (type == 'danger') {

            fillColor = colorDanger

        } else if (type == 'success') {

            fillColor = colorSuccess

        } else if (type == 'warning') {

            fillColor = colorWarning

        } else {

            fillColor = colorPrimary

        }

        $(this).circleProgress({
            value: `0.${progressEndValue}`,
            lineCap: 'round',
            size: progressSize,
            fill: fillColor,
            emptyFill: "#ffffff00",
            startAngle: 11,
        });

    });

}

// change image START 
if ($('.change-image-button').length > 0) {
    $(document).on("click", ".change-image-button", function () {
        let image = $(this).parents(".image-container").find("img.image-file")[0];
        let input = $(this).parents(".image-container").find("input.file-input")[0];
        input.click();
        input.onchange = evt => {
            const [file] = input.files
            if (file) {
                image.src = URL.createObjectURL(file)
            }
        }

    });
}
// change image END


// interests START 
function updateSelectedInterests() {
    let interestsArr = [];
    $('.select-items-wrapper button.active').each(function () {
        interestsArr.push($(this).data('category-id'));
    });
    $("#my-interests-value").val(JSON.stringify(interestsArr));
}

$(document).on("click", ".select-items-wrapper button", function () {
    $(this).toggleClass("active");
    updateSelectedInterests();
});
// interests END



let allSwipers = {};


$('.swiper-custom:not(.swiper-initialized)').each(function (index, element) {

    let $el = $(element);
    let swiperName = `swiper${index}`;

    let nextButtonId = $el.attr('data-next-button');
    let prevButtonId = $el.attr('data-prev-button');
    let paginationId = $el.attr('data-pagination');
    let paginationType = $el.attr('data-pagination-type') || 'bullets'; // bullets - progressbar 
    let nextButton = nextButtonId ? document.getElementById(nextButtonId) : null;
    let prevButton = prevButtonId ? document.getElementById(prevButtonId) : null;
    let paginationEl = paginationId ? document.getElementById(paginationId) : null;


    let spaceBetween = $el.attr('data-space-between') || 10;

    let perView = $el.attr('data-per-view') || 3;

    let perViewMd = $el.attr('data-per-view-md') || 2;

    let perViewSm = $el.attr('data-per-view-sm') || 1;

    let perViewXs = $el.attr('data-per-view-xs') || 1;




    let options = {
        loop: false,
        slidesPerView: perViewXs,
        spaceBetween: 5,

        navigation: {
            nextEl: nextButton || $el.parent().find('.swiper-button-next')[0],
            prevEl: prevButton || $el.parent().find('.swiper-button-prev')[0],
            clickable: true,
        },

        pagination: {
            el: paginationEl,
            type: paginationType,
            clickable: true,
        },

        breakpoints: {
            [breakpointSm]: {
                slidesPerView: perViewSm,
                spaceBetween: 10
            },
            [breakpointMd]: {
                slidesPerView: perViewMd,
                spaceBetween: 10
            },
            [breakpointXl]: {
                slidesPerView: perView,
                spaceBetween: spaceBetween
            }
        }

    }

    let swiperInstance = new Swiper(element, options);



    swiperInstance.appendSlide(`<div class="swiper-slide">new new</div>`);

    allSwipers[swiperName] = swiperInstance;
    // console.log(`Initialized ${swiperName}`);




    // console.log(allSwipers)

});







let searchHistoryMainList = [];

let searchHistoryOverlay = `<div class="search-history-overlay">  </div> `;

function bindSearchHistoryList() {

    if (localStorage.getItem("searchHistory")) {

        oldString = localStorage.getItem("searchHistory");

        searchHistoryMainList = oldString.split(",");

        searchHistoryMainList.forEach((e, i) => {
            $("#search-history-list").prepend(`<li> <a class="history-link" data-index="${i}" href="#"> <i class="icon icon-returns color-gray icon-sm"></i> ${e} </a> <i class="icon icon-remove-2 remove-history-item"></i> </li>`);
        });

    }

}

function removeSearchItem() {

    $(document).on("click", ".remove-history-item", function (e) {

        itemIndex = $(this).prev().data("index");

        searchHistoryMainList.splice(itemIndex, 1)

        localStorage.setItem("searchHistory", searchHistoryMainList);

        $(this).parent("li").remove();

    })
}

function addSearchItem(word) {


    if (!localStorage.getItem("searchHistory")) {

        localStorage.setItem("searchHistory", word);

    } else {


        oldString = localStorage.getItem("searchHistory");

        newString = oldString + `,${word}`

        searchHistoryMainList = newString.split(",")

        localStorage.setItem("searchHistory", newString);

    }

}

function showSearchHistory() {

    $("#search-history-wrapper").removeClass("d-none");

    if ($(".search-history-overlay").length === 0) {
        $("body").append(searchHistoryOverlay);
    }

    if (searchHistoryMainList.length > 0) {
        $(".clear-all-search-history-bar").css('display', 'flex')
    }


}

function hideSearchHistory() {

    if ($(window).width() < 1025) {
        $("#search-history-mobile-wrapper").addClass("d-none");
    } else {
        $("#search-history-wrapper").addClass("d-none");
        $(".search-history-overlay").remove();
    }

}

function clearAllSearchHistory() {

    searchHistoryMainList = [];

    localStorage.setItem("searchHistory", searchHistoryMainList);

    $("#search-history-list").html('')

    hideSearchHistory();

    $(".clear-all-search-history-bar").css('display', 'none');

}

$(document).on("click", "#clearAllSearchHistory", function () {
    clearAllSearchHistory()
});

$(document).ready(function () {

    removeSearchItem();

    bindSearchHistoryList();

    $("form.search-form").submit(function (event) {

        inputValue = $(this).find("input.search-input").val();

        if (!inputValue.length) { // escape submit form if empty value
            event.preventDefault();
        }

        if (!searchHistoryMainList.includes(inputValue) && inputValue !== "") {
            addSearchItem(inputValue);
        }


    });

    $(document).on("focus", ".search-input", function () {
        showSearchHistory();
    });

    $(document).on("click", ".search-history-overlay", function () {
        hideSearchHistory();
    });

    $(document).on("click", ".history-link", function () {
        $("input.search-input").val($(this).text());
        $("form.search-form").submit();
    });

});

$(document).on('change', '.payment-options .custom-radio .custom-control-input', function () {

    $('.payment-options .custom-radio.control-border').removeClass('active-border');

    $(this).closest('.control-border').addClass('active-border');
});

$('.payment-options .custom-radio .custom-control-input:checked').closest('.custom-control').addClass('active-border');


$(document).on('change', '.addresses-list .custom-control-input', function () {

    $('.addresses-list .control-border').removeClass('active-border');

    $(this).closest('.control-border').addClass('active-border');
});

$('.addresses-list  .custom-control-input:checked').closest('.custom-control').addClass('active-border');




$(document).on('change', '.target-audience-list .custom-control-input', function () {

    $('.target-audience-list .control-border').removeClass('active-border');

    $(this).closest('.control-border').addClass('active-border');
});

$('.target-audience-list  .custom-control-input:checked').closest('.custom-control').addClass('active-border');




let increaseCount = (event, b) => {
    var input = b.previousElementSibling;
    var value = parseInt(input.value, 10);

    value = isNaN(value) ? 0 : value;
    value++;
    input.value = value;
}

let decreaseCount = (event, b) => {
    var input = b.nextElementSibling;
    var value = parseInt(input.value, 10);
    if (value > 1) {
        value = isNaN(value) ? 0 : value;
        value--;
        input.value = value;
    }
}

// function initProductsSwiper() {

//     let productsThumbsSwiper = new Swiper(".products-thumbs-swiper", {
//         loop: true,
//         spaceBetween: 10,
//         slidesPerView: 5.5,
//         freeMode: true,
//         watchSlidesProgress: true,
//     });

//     let productsSwiper = new Swiper(".products-swiper", {
//         loop: true,
//         spaceBetween: 10,
//         navigation: {
//             nextEl: ".swiper-button-next",
//             prevEl: ".swiper-button-prev",
//         },
//         thumbs: {
//             swiper: productsThumbsSwiper,
//         },
//     });
// }




// function initProductsThumbsSwiper() {

//     let productsThumbsSwiper = new Swiper(".products-thumbs-swiper", {
//         loop: true,
//         spaceBetween: 10,
//         slidesPerView: 3.2,
//         freeMode: true,
//         watchSlidesProgress: true,


//         breakpoints: {
//             [breakpointSm]: {
//                 slidesPerView: 3.2,
//                 spaceBetween: 10
//             },
//             [breakpointMd]: {
//                 slidesPerView: 4.4,
//                 spaceBetween: 10
//             },
//             [breakpointXl]: {
//                 slidesPerView: 4.4,
//                 spaceBetween: 10
//             }
//         }



//     });

//     // Add click handler to slides
//     const $slides = $('.products-thumbs-swiper .swiper-slide');
//     const $mainImage = $('.img-zoom-main img');

//     // Add active class to first slide initially 
//     $slides.first().addClass('slide-active');

//     $slides.on('click', function () {
//         // Remove active class from all slides
//         $slides.removeClass('slide-active');
//         // Add active class to clicked slide
//         $(this).addClass('slide-active');

//         // Update main image src
//         const imageUrl = $(this).find('img').attr('src');
//         $mainImage.attr('src', imageUrl);
//     });

// }

function initPinningProductDetails() {
    if ($("#pin").length && $("#trigger").length) {
        var controller = new ScrollMagic.Controller();

        var scene = new ScrollMagic.Scene({
            triggerElement: "#trigger",
            duration: function () {
                return $("#trigger").outerHeight() - $("#pin").outerHeight();
            },
            triggerHook: 0,
        })
            .setPin("#pin")
            // .addIndicators({ name: "Product Gallery" }) // This helps with debugging
            .addTo(controller);

        // Update scene on window resize
        $(window).on('resize', function () {
            scene.duration($("#trigger").outerHeight() - $("#pin").outerHeight());
            scene.refresh();
        });

        // Update scene when images load
        $('.products-gallery-wrapper img').on('load', function () {
            scene.duration($("#trigger").outerHeight() - $("#pin").outerHeight());
            scene.refresh();
        });
    }
}

$(".select-reason-dropdown input").on("change", function () {
    // Get the closest dropdown container
    let dropdownContainer = $(this).closest('.dropdown');

    dropdownContainer.find(".selected-reason-text").text($(this).siblings("label").text());
    dropdownContainer.find(".other-reason-container").addClass("d-none");
    dropdownContainer.find(".other-reason-container textarea").attr("required", false);


    dropdownContainer.find(".submit-other").on("click", function () {
        $(this).parents(".dropdown").removeClass("show");
        $(this).parents(".dropdown-menu").removeClass("show");
    });

    if ($(this).val() == '') {
        dropdownContainer.find(".selected-reason-text").text($(this).siblings("label").text());
        dropdownContainer.find(".other-reason-container").removeClass("d-none");
        dropdownContainer.find(".other-reason-container textarea").attr("required", true);
    }

    if ($(this).data("auto-close") == true) {
        $(this).parents(".dropdown").removeClass("show");
        $(this).parents(".dropdown-menu").removeClass("show");
    }

});

$(document).on("click", ".select-all-products", function () {
    if ($(this).is(":checked")) {
        $(".select-product").prop("checked", true);
    } else {
        $(".select-product").prop("checked", false);
    }
});

$(document).ready(function () {
    $('#withdraw-amount').on('change keyup', function () {
        const withdrawBox = $(this).closest('.withdraw-box');
        const maxAmount = parseInt(withdrawBox.data('max-amount'));
        const minAmount = parseInt(withdrawBox.data('min-amount'));
        const amount = parseInt($(this).val());

        if (amount > maxAmount || amount < minAmount) {
            withdrawBox.addClass('invalid');
            $('#withdraw-submit').prop('disabled', true);
        } else {
            withdrawBox.removeClass('invalid');
            $('#withdraw-submit').prop('disabled', false);
        }

    });
});





// Slider Range Start       

if ($('#price-slider').length > 0) {

    const priceSlider = document.getElementById('price-slider');
    const minPrice = document.getElementById('min-price');
    const maxPrice = document.getElementById('max-price');

    noUiSlider.create(priceSlider, {
        start: [0, 1000],
        connect: true,
        range: {
            'min': 0,
            'max': 1000
        },
        step: 10
    });

    priceSlider.noUiSlider.on('update', function (values) {
        minPrice.value = Math.round(values[0]);
        maxPrice.value = Math.round(values[1]);
    });

    priceSlider.noUiSlider.on('slide', function (values) {
        // console.log(values[0], values[1]);
    });

}

// Slider Range End      





















// zoom image START     

$('.img-zoom-main').each(function () {
    const $container = $(this);
    const $img = $container.find('img');
    const $result = $container.next('.img-zoom-result');
    const $lens = $container.find('.img-zoom-lens');
    const zoom = 2.6;

    // Set background image and size on load
    $img.on('load', function () {
        $result.css({
            'backgroundImage': `url('${$img.attr('src')}')`,
            'backgroundSize': `${$img.width() * zoom}px ${$img.height() * zoom}px`
        });
    });

    // Set initial background
    $result.css({
        'backgroundImage': `url('${$img.attr('src')}')`,
        'backgroundSize': `${$img.width() * zoom}px ${$img.height() * zoom}px`
    });

    // Mouse enter/leave events
    $img.on('mouseenter', function () {
        $lens.show();
        $result.show();
        $img.on('mousemove', moveLens);
    }).on('mouseleave', function () {
        $lens.hide();
        $result.hide();
        $img.off('mousemove', moveLens);
    });

    // Variables to reduce jitter
    let lastX = 0, lastY = 0;
    let rafId = null;

    function moveLens(e) {
        const pos = getCursorPos(e);
        let x = pos.x - $lens.width() / 2;
        let y = pos.y - $lens.height() / 2;

        // Lens boundaries
        x = Math.max(0, Math.min(x, $img.width() - $lens.width()));
        y = Math.max(0, Math.min(y, $img.height() - $lens.height()));

        // Remove jitter using requestAnimationFrame
        if (rafId) cancelAnimationFrame(rafId);
        rafId = requestAnimationFrame(() => {
            $lens.css({
                'left': x + 'px',
                'top': y + 'px'
            });
            $result.css('backgroundPosition', `-${x * zoom}px -${y * zoom}px`);
        });
    }

    function getCursorPos(e) {
        const rect = $img[0].getBoundingClientRect();
        let x = e.clientX - rect.left;
        let y = e.clientY - rect.top;

        // Touch support
        if (e.touches) {
            x = e.touches[0].clientX - rect.left;
            y = e.touches[0].clientY - rect.top;
        }
        return { x: x, y: y };
    }
});

// zoom image END



// products gallery START

$(document).on("click", ".thumbs-wrapper .thumbnail", function () {
    $(".thumbs-wrapper .thumbnail").removeClass("active");
    $(this).addClass("active");

    const $mainImage = $('.img-zoom-main img');
    const imageUrl = $(this).attr('src');
    $mainImage.attr('src', imageUrl);

});

// products gallery END







// Buy these items START


$(document).ready(function () {
    // Calculate initial total
    calculateTotal();

    // Add change event listener to checkboxes 
    $('.always-bought-with-items-wrapper .custom-control-input').on('change', function () {
        calculateTotal();

    });

    function calculateTotal() {
        let total = 0;
        let ids = [];

        // Loop through checked checkboxes and sum their data-price values
        $('.always-bought-with-items-wrapper .custom-control-input:checked').each(function () {
            ids.push($(this).attr('id'));
            total += parseFloat($(this).data('price'));
        });


        // Update button text with new total
        $('.always-bought-with-item-button').text('Buy these items for ' + total.toFixed(3) + ' KWD');
        $('.always-bought-with-item-price-input').val(total);
        $('.always-bought-with-item-ids-input').val(JSON.stringify(ids));
    }
});


// Buy these items END

$(document).on('click', '#copy-link', function (e) {
    copyTextInShareModal();
});




let copyTextInShareModal = () => {
    /* Get the text field */
    let copyText = $("#store-link-input").val();

    /* Copy the text inside the text field */
    navigator.clipboard.writeText(copyText);


    alert("link-copied");

}
























let uploadImagesWithThumbnails = () => {

    document.getElementsByClassName('upload-with-thumbnails')[0].addEventListener('change', function (event) {
        let file = event.target.files[0];
        let fileReader = new FileReader();


        if (file.type.match('image')) {

            fileReader.onload = function () {

                let div = document.createElement("div");
                div.classList.add("one-thumbnail");
                div.classList.add("is-loading");


                let loadingDiv = document.createElement("div");
                loadingDiv.classList.add("loading-container");

                let loadingDiv2 = document.createElement("div");
                loadingDiv2.classList.add("loader");

                loadingDiv.append(loadingDiv2);

                let img = document.createElement('img');
                img.src = fileReader.result;
                img.setAttribute("asset_id", 1);

                let icon = document.createElement('a');
                icon.classList.add("icon", "icon-remove");

                div.append(img);
                div.append(icon);
                div.append(loadingDiv);
                document.getElementsByClassName('thumbnails-wrapper')[0].appendChild(div);

            };
            fileReader.readAsDataURL(file);
        } else {
            fileReader.onload = function () {
                var blob = new Blob([fileReader.result], { type: file.type });
                var url = URL.createObjectURL(blob);
                var video = document.createElement('video');
                var timeupdate = function () {
                    if (snapImage()) {
                        video.removeEventListener('timeupdate', timeupdate);
                        video.pause();
                    }
                };
                video.addEventListener('loadeddata', function () {
                    if (snapImage()) {
                        video.removeEventListener('timeupdate', timeupdate);
                    }
                });
                var snapImage = function () {
                    var canvas = document.createElement('canvas');
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                    var image = canvas.toDataURL();
                    var success = image.length > 100000;
                    if (success) {

                        let div = document.createElement("div");
                        div.classList.add("one-thumbnail");
                        div.classList.add("is-loading");


                        let loadingDiv = document.createElement("div");
                        loadingDiv.classList.add("loading-container");

                        let loadingDiv2 = document.createElement("div");
                        loadingDiv2.classList.add("loader");

                        loadingDiv.append(loadingDiv2);


                        var img = document.createElement('img');
                        img.src = image;
                        img.setAttribute("asset_id", 1);

                        let icon = document.createElement('a');
                        icon.classList.add("icon", "icon-remove");

                        div.append(img);
                        div.append(icon);
                        div.append(loadingDiv);
                        document.getElementsByClassName('thumbnails-wrapper')[0].appendChild(div);

                        URL.revokeObjectURL(url);
                    }
                    return success;
                };
                video.addEventListener('timeupdate', timeupdate);
                video.preload = 'metadata';
                video.src = url;
                // Load video in Safari / IE11
                video.muted = true;
                video.playsInline = true;
                video.play();
            };
            fileReader.readAsArrayBuffer(file);
        }

        setTimeout(() => {
            if ($(".thumbnails-wrapper").children().length >= 3) {
                $(".upload-btn").addClass("d-none");
                $(".upload-btn-disabled").removeClass("d-none");
                $(".max-limit").removeClass("d-none");
            }


            if ($(".thumbnails-wrapper").children().length == 1) {
                $(".thumbnails-wrapper").children(".one-thumbnail").first().addClass("default");

                $("#primary-asset-id").val($(".thumbnails-wrapper").children(".one-thumbnail").first().children("img").attr("asset_id"));
            }
        }, 100);

    });

    $(document).on("click", ".upload-btn", function () {
        $("#upload").click();
    });

    $(document).on("click", ".one-thumbnail .icon-remove", function (event) {
        event.preventDefault();

        if ($(this).parent().hasClass("default")) {
            setTimeout(() => {
                // console.log($(".one-thumbnail:nth-child(1)").children("img").click());
            }, 200);
        }

        $(this).parent().remove();
        $(".upload-btn").removeClass("d-none");
        $(".upload-btn-disabled").addClass("d-none");
        $(".max-limit").addClass("d-none");
    });

    $(document).on("click", ".one-thumbnail img", function (event) {
        $(".one-thumbnail").removeClass("default");
        $(this).parent().addClass("default");
        $("#primary-asset-id").val($(this).attr("asset_id"));
    });

}

$(document).ready(function () {
    $('.radio-with-side-content .custom-radio.side-content input').on('change', function () {
        $(".radio-with-side-content .custom-radio.side-content input").siblings('.side-content-wrapper').hide();
        $(this).siblings('.side-content-wrapper').show();
    });
});







$(document).ready(function () {
    function toggleLocationTabs() {
        if ($('#map-switch').is(':checked')) {
            $('#map-tab').show();
            $('#select-tab').hide();
        } else {
            $('#map-tab').hide();
            $('#select-tab').show();
        }
    }
    $('#map-switch').on('change', toggleLocationTabs);
    toggleLocationTabs();
});

$(document).ready(function () {

    $('.js-data-example-ajax').select2({
        placeholder: 'placeholder',
        ajax: {
            url: 'https://api.github.com/search/repositories',
            dataType: 'json'
        }
    });

});


$(document).ready(function () {

    $('.upload-input').on('change', function (event) {

        const input = event.target;

        const thumbnail = $(input).siblings('label').find('.upload-thumbnail');

        const sideContent = $(input).siblings('label').find('.upload-side');

        const pdfPreview = $(input).siblings('label').find('.pdf-preview');

        if (input.files && input.files[0]) {

            const file = input.files[0];

            const fileType = file.type;

            if (fileType.startsWith("image/")) {

                const reader = new FileReader();

                reader.onload = function (e) {

                    sideContent.remove();

                    pdfPreview.addClass('d-none');

                    thumbnail.removeClass('d-none');

                    thumbnail.attr('src', e.target.result);

                }

                reader.readAsDataURL(file);

            } else {


                sideContent.remove();

                pdfPreview.removeClass('d-none');

                thumbnail.addClass('d-none');



            }

        }

    });

});




























function initAbsoluteSlider(sliderId, startValue) {

    let slider = document.getElementById(sliderId);

    noUiSlider.create(slider, {
        start: [startValue],
        connect: [true, false],
        range: {
            'min': 0,
            'max': 100
        }
    });

    let handle = slider.querySelector('.noUi-handle-lower');
    let valueElement = document.createElement('div');
    valueElement.className = 'handle-value';
    handle.appendChild(valueElement);

    slider.noUiSlider.on('update', function (values) {
        valueElement.textContent = Math.round(values[0]);
    });

}

$(document).on('shown.bs.modal', '#target-audience-details-modal', function () {

    $(".see-all-data-wrapper").each(function () {
        let wrapper = $(this).find(".data-wrapper");
        let button = $(this).find(".see-all-data-button");
        let realHeight = wrapper.css("height", "auto").height();

        wrapper.css("height", "40px");

        if (realHeight <= 40) {
            button.hide();
        }
    });

})

$(document).on('click', '.see-all-data-button', function () {

    let wrapper = $(this).parents(".see-all-data-wrapper").find(".data-wrapper");

    if (wrapper.hasClass("expanded")) {
        wrapper.removeClass("expanded").css("height", "40px");
        $(this).html(`See more <i class="icon-chevron-down icon icon-xs"></i>`);
    } else {
        wrapper.addClass("expanded").css("height", "auto");
        $(this).html(`See less <i class="icon-chevron-top icon icon-xs"></i>`);
    }

});




let uploadSingleImage = (event) => {

    $(document).on("click", ".upload-single-image-btn", function () {

        let singleImage = $(this).siblings(".single-image");

        let singleImageInput = $(this).siblings(".single-image-input");

        singleImageInput.click();

        $(this).siblings(".single-image-input")[0].addEventListener('change', function (event) {

            let file = event.target.files[0];
            let fileReader = new FileReader();

            fileReader.onload = function () {
                singleImage.get(0).src = fileReader.result;

            };

            fileReader.readAsDataURL(file);

        });
    })
}

$(document).ready(function () {
    uploadSingleImage();
});




$('#toggle-password').on('click', function () {
    let $input = $('#password-input');
    let $icon = $(this);
    if ($input.attr('type') === 'password') {
        $input.attr('type', 'text');
        $icon.removeClass('icon-eye').addClass('icon-eye-locked');
    } else {
        $input.attr('type', 'password');
        $icon.removeClass('icon-eye-locked').addClass('icon-eye');
    }
});

$(document).ready(function () {

    $(document).on("click", ".close-ticket-asset-thumbnail", function () {
        $(".ticket-asset-thumbnail-wrapper").remove();
    });

    $("#open-ticket-asset-file").on("click", function () {
        $("#ticket-asset-file").click();
    });

    $("#ticket-asset-file").change(function () {


        if ($(".ticket-asset-thumbnail-wrapper")) {
            $(".ticket-asset-thumbnail-wrapper").remove();
        }

        let file = event.target.files[0];
        let fileReader = new FileReader();

        fileReader.onload = function () {

            let html = `<div class="ticket-asset-thumbnail-wrapper">
                        <i class="icon icon-remove1 close-ticket-asset-thumbnail"></i>
                        <img src="${fileReader.result}" class="ticket-asset-thumbnail img-fluid">
                    </div>`

            $(".ticket-wrapper").append(html);
        };

        fileReader.readAsDataURL(file);
    })




});








$(document).ready(function () {
    $('#delete-reason-select').on('change', function () {
        if ($(this).val() === 'other') {
            $('.other-wrapper').show();
        } else {
            $('.other-wrapper').hide();
        }
    });
});
