let priceCount = 1;

$(document).ready(function(){

    function checkScreenSize() {
        if ($(window).width() >= 1024) {
            $('nav .more').next().removeAttr('style');
        }
    }

    $(window).on('resize', checkScreenSize);

    function scrollEvents() {
        // Header Controller
        if ($('html').scrollTop() > 260 && !$('header').hasClass('shownav')) {
            $('header').removeClass('hidenav')
            $('header').addClass('fixnav')
            setTimeout(() => {
                $('header').addClass('shownav')
            }, 1);
        }else if($('html').scrollTop() < 220 && $('header').hasClass('shownav')){
            $('header').addClass('hidenav')
            $('header').removeClass('shownav')
            setTimeout(() => {
                $('header').removeClass('hidenav')
                $('header').removeClass('fixnav')
            }, 300);
        }


        // Parallax Effect
        var windowHeight = $(window).height();
        var scrollPosition = $(window).scrollTop();

        $('[data-speed]').each(function() {
            var elementOffset = $(this).offset().top;
            var elementHeight = $(this).outerHeight();
            
            // Element ekran içinde göründüğünde parallax efektini uygula
            if (scrollPosition + windowHeight > elementOffset && scrollPosition < elementOffset + elementHeight) {
                var speed = parseFloat($(this).data('speed'));
                var yPos = -((scrollPosition - elementOffset) * speed);
                var bgPosition = 'center ' + -yPos + 'px';
                
                if ($(window).width() <= 768) {
                    $(this).css('background-position', 'center');
                }else{
                    $(this).css('background-position', bgPosition);
                }
            }
        });        
    }

    $(window).on('scroll', scrollEvents);
    scrollEvents()

    
    $('nav .more').on('click', function(e) {
        if ($(window).width() < 1024) {
            e.preventDefault();
            var $nextElement = $(this).next();
    
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $nextElement.slideUp(200, function() {
                    $nextElement.removeClass('open');
                });
            } else {
                if (!$(this).parent().parent().prev().hasClass('open')) {
                    $('nav .more.open').removeClass('open').next().slideUp(200, function() {
                        $(this).removeClass('open');
                    });
                }else{
                    $(this).parent().parent().find('.more.open').removeClass('open').next().slideUp(200, function() {
                        $(this).removeClass('open');
                    });
                }
                $(this).addClass('open');
                $nextElement.slideDown(200, function() {
                    $nextElement.addClass('open');
                });
            }
        }
    });


    // NAVBAR TOGGLE BTN
    $('#left-nav-toggle').on('click', function() {
        $('html').toggleClass('active')
        $(this).toggleClass('active')
        if ($('body').hasClass('transition')) {
            setTimeout(() => {
                $('body').removeClass('transition')
            }, 500);
        }else{
            $('body').addClass('transition')
        }
    })




    // ORDER ANIMATION
    function updateCountPosition(arr, count) {
        if (count == arr.length) {
            return
        }

        arr[count].style.transform = `translateY(-${arr[count].dataset.order * 45}px)`

        setTimeout(() => {
            count++
            updateCountPosition(arr, count)
        }, 100);
    }
    
    let countAreas = document.querySelectorAll('.count-area')

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                updateCountPosition(entry.target.querySelectorAll('[data-order]'), 0)
                observer.unobserve(entry.target);
            }
        });
    });

    countAreas.forEach(countArea => {
        observer.observe(countArea);
    })



    //------------------------------------------\\
    //------------- CUSTOM DROPDOWN ------------\\
    //------------------------------------------\\

    // input'a tıklandığında dropdown açılır
    let currentDropdown;

    // dropdown açıkken dışarıya tıklanırsa dropdown kapanır
    document.addEventListener('click', (e) => {
        if (currentDropdown) {
        if (!e.composedPath().includes(currentDropdown[0])) {
            currentDropdown.removeClass('active')
        }
        }
    })

    $('.custom-dropdown .c-input').click(function() {
        if ($(this).parent().hasClass('active')) {
            $(this).parent().removeClass('active')
        }else{
            $(this).parent().addClass('active')
            setTimeout(() => {
                currentDropdown = $(this).parent()
            }, 50);
        }
    });

    // dropdown içindeki span'lardan biri tıklandığında dropdown kapanır ve seçilen span'ın içeriği input değeri olarak atanır
    $('.custom-dropdown .dropdown span').click(function() {
        var value = $(this).html();
        let customInput = $(this).parent().parent().children().eq(0)
        customInput.html(value)
        currentDropdown.removeClass('active')
        if ($(this).hasClass('null')) {
            customInput.addClass('null')
        }else{
            customInput.removeClass('null')
        }
    });
    


    

    


    
    // DYNAMIC TAB AREA
    $('[data-tab-id]').click(function() {
        var tabId= $(this).attr('data-tab-id');
        var tabName = $(this).attr('data-tab-name');
        var content = $('[data-content-name="' + tabName + '"]');

        $('[data-tab-id="' + tabId + '"]').removeClass('active');
        setTimeout(() => {
            $(this).addClass('active');
        }, 200);

        $('[data-content-id="' + tabId + '"]').removeClass('active');
        setTimeout(() => {
            $('[data-content-id="' + tabId + '"]').addClass('hidden-area');
            content.addClass('active');
            content.removeClass('hidden-area');
        }, 200);
    });
    



    // REQUIRED FIELD CONTROL
    $('[required]').on('blur', function() {
        var $this = $(this);
        if ($this.val() === '') {
          $this.removeClass('green').addClass('red');
        } else {
          $this.removeClass('red').addClass('green');
        }
    });

    $('#new-password-area input').prop('required', false);
    $('#new-account-cb').on('change', function() {
        if ($(this).is(':checked')) {
          $('#new-password-area').slideDown(200);
          $('#new-password-area input').prop('required', true);
        } else {
          $('#new-password-area').slideUp(200);
          $('#new-password-area input').prop('required', false);
        }
    });










    // CART CONTROLLER
    $('body').on('click', '.products > div .remove', function(e) {
        var parentElement = $(this).parent().parent();

        if (parentElement.siblings().length === 0) {
            let freeControl = parentElement.closest('.free-control');
            freeControl.addClass('free');
        }
        parentElement.remove();
    })

    // Delete Product In Basket
    $('body').on('click', '.basket-products > div button', function(e) {
        var deletedProduct = $(this).parent().parent();

        if (deletedProduct.siblings().length === 0) {
            let freeControl = deletedProduct.closest('.free-control');
            freeControl.addClass('free');
        }
        deletedProduct.remove();
    })
    
    
    
    
    
})



// MODAL EVENTS
let currentModal;
let lastModal;

function checkIncludeModal(e){
    if (!e.composedPath().includes(currentModal.children[0])) {
        closeModal()
    }
}

function openModal(){
    currentModal.classList.add('active')
    document.addEventListener('click', checkIncludeModal, true)
}

function closeModal(){
    currentModal.classList.remove('active')
    document.removeEventListener('click', checkIncludeModal, true)
}


let closeModalBtns = document.querySelectorAll('.close-modal')
closeModalBtns.forEach(closeModalBtn => {
    closeModalBtn.addEventListener('click', () => {
        closeModal()
    })
})

document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        if (currentModal?.classList.contains('active')) {
            closeModal()
        }
    }
});


// GALLERY MODAL CONTROLLER
let imgModalContainer = document.getElementById('img-modal-container')
let galleryImages = document.querySelectorAll('.gallery-images > img');
let selectedGallery = [];
let currentModalImgCount = 0;

let modalImg = document.getElementById('modal-img');
let modalLeftArr = document.getElementById('modal-left-arr');
let modalRightArr = document.getElementById('modal-right-arr');
let currentModalImgArea = document.getElementById('current-modal-img');
let totalModalImgArea = document.getElementById('total-modal-img');

galleryImages.forEach((galleryImage, index) => {
    galleryImage?.addEventListener('click', () => {
        selectedGallery = Array.from(galleryImages);
        currentModalImgCount = index;
        totalModalImgArea.textContent = selectedGallery.length;
        showCurrentImage()

        currentModal = imgModalContainer
        openModal()
    });
});

modalImg?.addEventListener('click', () => {
    showNextImage();
});

modalLeftArr?.addEventListener('click', () => {
    showPreviousImage();
});

modalRightArr?.addEventListener('click', () => {
    showNextImage();
});

function showCurrentImage() {
    const selectedImage = selectedGallery[currentModalImgCount];
    if(selectedGallery.length > 0){
        modalImg.src = selectedImage.src;
        currentModalImgArea.textContent = currentModalImgCount + 1;
    }
}

function showNextImage() {
    currentModalImgCount = (currentModalImgCount + 1) % selectedGallery.length;
    showCurrentImage();
}

function showPreviousImage() {
    currentModalImgCount = (currentModalImgCount - 1 + selectedGallery.length) % selectedGallery.length;
    showCurrentImage();
}




// PRODUCT DETAIL MODAL CONTROLLER
let openProductImagesBtn = document.getElementById('open-product-images')
openProductImagesBtn?.addEventListener('click', () => {
    modalImg.src = openProductImagesBtn.nextElementSibling.src;

    currentModal = imgModalContainer
    openModal()
})



