const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000,
  timerProgressBar: true,
  didOpen: (toast) => {
    toast.addEventListener('mouseenter', Swal.stopTimer)
    toast.addEventListener('mouseleave', Swal.resumeTimer)
  }
});


document.addEventListener('DOMContentLoaded', function(e) {
    Event.listen('cartsUpdatedFromSidebar', event => {
      showProductShowButton();
    })

    let pageURL = new URL(location);
    if (pageURL.searchParams.has('sorting')) {
        document.getElementById('SortBy').value = pageURL.searchParams.get('sorting');
    }

    let productPerPageSelect = document.getElementById('show-product-count-select');
    
    if (pageURL.searchParams.has('perPage')) {
        productPerPageSelect.value = pageURL.searchParams.get('perPage');
    } else {
        if (productPerPageSelect) {
            productPerPageSelect.value = 32;
        }
    }
});


function subscribeUserToNewsletter(event) {
    event.preventDefault();

    $.ajax({
        method: event.target.method,
        url: event.target.action,
        data: Object.fromEntries(new FormData(event.target).entries()),
        success: (response) => {
            Swal.fire('Üstünlikli goşuldy', '', 'success');
        },
        error: (exception) => {
          Swal.fire('Üstünlikli goşuldy', '', 'success')  ;
        }
    });  
}

function loginAction(event) {
    event.preventDefault();

    // let phoneINPUT = document.getElementById('PopupCustomerPhoneContainer');
    let verificationINPUT = document.getElementById('PopupCustomerVerificationCodeContainer');

    $.ajax({
        method: event.target.method,
        url: window.Lara.routes.auth.twoFactor,
        data: Object.fromEntries(new FormData(event.target).entries()),
        success(response) {
            console.log({response});

            if (response.message == 'Login') {
                window.location.reload(true);
            }

            if (response.message != 'success') {
                return;
            }

            verificationINPUT.classList.remove('d-none');
            verificationINPUT.setAttribute('required', 'required');
        },
        error(exception) {
            console.log({exception});
          // Swal.fire('Üstünlikli goşuldy', '', 'success')  ;
        },
        done(data) {
            console.log({a: data});
        }
    });
}

function updateLikeCount() {
    let wishlistCount = document.getElementById('wishlist-count');
    // let sidebarWishlistCount = document.getElementById('sidebar-wishlist-count');

    $.ajax({
        method: 'POST',
        url: window.Lara.routes.products.likeCount,
        data: {_token: document.querySelector('meta[name=csrf-token]').getAttribute('value')},
        success: (response) => {
            wishlistCount.innerText = response.count;
        },
        error: (exception) => {
            console.log({exception});
        }
    });   
}

function toggleProductLike(event, elem, id) {
    event.preventDefault();

    if (! window.Lara.auth.status) {
        return;
    }

    let formData = {
        id: id,
        _token: document.querySelector('meta[name=csrf-token]').getAttribute('value'),
    };

    $.ajax({
        method: 'POST',
        url: window.Lara.routes.products.like,
        data: formData,
        success: (response) => {
            if (response.attached) {
                document.getElementById(id + '-favourite-icon-dislike')?.classList.add('d-none');
                document.getElementById(id + '-favourite-icon-like')?.classList.remove('d-none');

                Toast.fire({
                  icon: 'success',
                  title: window.Lara.translations.favouries.liked
                })
            } else {
                document.getElementById(id + '-favourite-icon-dislike')?.classList.remove('d-none');
                document.getElementById(id + '-favourite-icon-like')?.classList.add('d-none');

                Toast.fire({
                  icon: 'info',
                  title: window.Lara.translations.favouries.unliked
                })
            }

            Event.fire('likesUpdated');
        },
        error: (exception) => {
            console.log({exception});
        }
    });
}

function toggleLikeProductShowButton(event, product_id) {
    let addToLikeButtonMessage = document.getElementById('add-to-like-button-message');
    let addedToLikeButtonMessage = document.getElementById('added-to-like-button-message');

    toggleProductLike(event, event.target, product_id);

    if (addToLikeButtonMessage.classList.contains('d-none')) {
        addToLikeButtonMessage.classList.remove('d-none');
        addToLikeButtonMessage.classList.add('d-flex');
        addedToLikeButtonMessage.classList.remove('d-flex');
        addedToLikeButtonMessage.classList.add('d-none');
    } else {
        addToLikeButtonMessage.classList.add('d-none');
        addToLikeButtonMessage.classList.remove('d-flex');
        addedToLikeButtonMessage.classList.add('d-flex');
        addedToLikeButtonMessage.classList.remove('d-none');
    }
}

function addToCart(product_id, with_count) {
    if (! window.Lara.auth.status) {
        return;
    }

    let quantity = with_count ? document.getElementById('product-quantity')?.value : null;
        
    product_id = window.Lara.productOnCart ? window.Lara.productOnCart : product_id;

    let formData = {
        product_id: product_id,
        _token: document.querySelector('meta[name=csrf-token]').getAttribute('value'),
        quantity: quantity
    };

    $.ajax({
        method: 'POST',
        url: window.Lara.routes.carts.add,
        data: formData,
        success: (response) => {
            Event.fire('cartsUpdated');
        },
        error: (exception) => {
            if (exception.status == 422) {
                if (validationMessage = exception.responseJSON.data.validations['product_out_of_stock_count']) {
                    alert(validationMessage);
                }
            }
        }
    });
}

function removeCartItem(product_id) {
    if (! window.Lara.auth.status) {
        return;
    }

    let formData = {
        product_id: product_id,
        _token: document.querySelector('meta[name=csrf-token]').getAttribute('value'),
    };

  fetch(window.Lara.routes.carts.remove, {
    method: 'POST',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json'
    },
    credentials: 'same-origin',
    body: JSON.stringify(formData)
  }).then(response => response.json())
    .then(data => {
      Event.fire('cartsUpdated');
    });
}

function updateCart(product_id, increment_by_one) {
    if (! window.Lara.auth.status) {
        return;
    }

    let quantity = new Number(document.getElementById('product-quantity')?.value);

    if (increment_by_one || quantity == 0) {
        quantity += 1;
    } 

    let formData = {
        product_id: product_id,
        _token: document.querySelector('meta[name=csrf-token]').getAttribute('value'),
        quantity: quantity
    };

    $.ajax({
        method: 'POST',
        url: window.Lara.routes.carts.update,
        data: formData,
        success: (response) => {
            Event.fire('cartsUpdated');
        },
        error: (exception) => {
            console.log({exception});
        }
    });
}

function updateProductShowButton() {
    let addToCartMessage = document.getElementById('add-to-cart-button-message');
    let removeFromCartMessage = document.getElementById('remove-from-cart-button-message');
    let removeTrashIcon = document.getElementById('remove-from-cart-trash');

    addToCartMessage.classList.remove('d-flex');
    addToCartMessage.classList.add('d-none');
    removeFromCartMessage.classList.remove('d-none');
    removeFromCartMessage.classList.add('d-flex');
    removeTrashIcon.classList.remove('d-none');
}

function showProductShowButton() {
    let addToCartMessage = document.getElementById('add-to-cart-button-message');
    let removeFromCartMessage = document.getElementById('remove-from-cart-button-message');
    let removeTrashIcon = document.getElementById('remove-from-cart-trash');
    let productQuantity = document.getElementById('product-quantity');

    addToCartMessage.classList.remove('d-none');
    addToCartMessage.classList.add('d-flex');
    removeFromCartMessage.classList.remove('d-flex');
    removeFromCartMessage.classList.add('d-none');
    removeTrashIcon.classList.add('d-none');
    productQuantity.value = 1;
}

function productShowCounterChanged(product_id, event) {
    let addToCartMessage = document.getElementById('add-to-cart-button-message');

    if (! addToCartMessage.classList.contains('d-flex')) {
        updateCart(product_id, event.type == 'click');
    }
}

async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json'
    },
    referrerPolicy: 'no-referrer',
    body: JSON.stringify(data)
  });
  
  return response.json();
}

async function globalSearch(q) {
    let response = await fetch(window.Lara.routes.app.globalSearch + '?q=' + q);

    return response.json();
}

function addSorting(value) {
    addUrlParam('sorting', value);
}

function addUrlParam(key, value, update = true) {
    let pageURL = new URL(location);

    pageURL.searchParams.delete(key)
    pageURL.searchParams.append(key, value);

    if (update) {
        location.href = pageURL.href;
    }
}

function sideScroll(element,direction,speed,distance,step){
    scrollAmount = 0;
    var slideTimer = setInterval(function(){
        if (direction == 'left'){
            element.scrollLeft -= step;
        } else {
            element.scrollLeft += step;
        }
        scrollAmount += step;
        if (scrollAmount >= distance) {
            window.clearInterval(slideTimer);
        }
    }, speed);
}


function scrollToClosest(position, elem, selector, points = 1000) {
    if (position == 'left') {
        let box = $(elem).parent().find(selector);

        let x = ((box.width() / 2)) + box.scrollLeft();
        box.animate({
            scrollLeft: x,
        });

        // $(elem).parent().find(selector).scrollLeft(-points);
    } else {
        // $(elem).parent().find(selector).scrollLeft(+points);
    }
}

// function orderDeliveryTimeChanged(event) {
//     let clientTime = document.getElementById('order-client-time-container');

//     if (event.target.value == 'standart') {
//         clientTime.classList.remove('d-none');
//     } else {
//         clientTime.classList.add('d-none');
//     }
// }

