$(document).ready(function () {
  // GLOBAL CALL
  globalHandler();

  // PAGE CALL
  homepageHandler();
  categoryHandler();
  productDetailHandler();
  cartHandler();
});

// GLOBAL
function globalHandler() {
  runLazyImageLoad();
  viewMoreHandler('.js-vm-block');
  searchHandler('#js-search-bar', 'search');
  closeWhenClickOutside();
  headerFixedScrollHandler();
}

// RESET SWIPER
function resetSwiperWrapper(target) {
  $(target).css("visibility", "hidden");
  setTimeout(function () {
    $(target).css("visibility", "unset");
  }, 300);
}

// HEADER FIXED
function headerFixedScrollHandler() {
  $(window).scroll(function () {
    let distanceFromTop = $(document).scrollTop();
    const $global_header_target = $(".global-header");
    const $global_fixed_block = $(".global-header-fixed-block");

    if (distanceFromTop > 500) {
      $global_header_target.addClass("fixed");
      $global_fixed_block.removeClass("d-none");
    } else {
      $global_fixed_block.addClass("d-none");
      $global_header_target.removeClass("fixed");
    }
  });
}

// HOMEPAGE
function homepageHandler() {
  collectionBoxHandler();

  swiperSectionHero();
  swiperCollectionProducts();
  swiperSectionCategory();
  swiperSectionCategory2();
  swiper4Slides();
}

function collectionBoxHandler() {
  if ($(".js-collection-item").length == 0) return;

  $(".js-collection-item").on("click", function () {
    const id = $(this).attr("data-id");
    const url = $(this).attr("data-url");

    $(this).closest("#js-collection-box").find(".js-collection-item").removeClass("active");
    $(this).closest("#js-collection-box").find("#js-collection-link").attr("href", url);
    $(this).addClass("active");
  })
}

function swiperSectionHero() {
  new Swiper(".swiper-section-hero", {
    slidesPerView: 1,
    spaceBetween: 0,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    pagination: {
      el: ".swiper-pagination",
    },
  });
}

function swiperCollectionProducts() {
  new Swiper(".swiper-collection-products", {
    slidesPerView: 5,
    spaceBetween: 12,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
}

function swiper4Slides() {
  new Swiper(".swiper-4-slides", {
    slidesPerView: 4,
    spaceBetween: 12,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
}

function swiperSectionCategory() {
  new Swiper(".swiper-section-category", {
    slidesPerView: 5,
    spaceBetween: 0,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      1601: {
        slidesPerView: 6,
      },
    }
  });
}

function swiperSectionCategory2() {
  new Swiper(".swiper-section-category-2", {
    slidesPerView: 4,
    spaceBetween: 0,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      1601: {
        slidesPerView: 5,
      },
    }
  });
}

// CATEGORY
function categoryHandler() {
  swiperCategoryTop();
}

function swiperCategoryTop() {
  new Swiper(".swiper-category-top", {
    slidesPerView: 2,
    spaceBetween: 12,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 4500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
}

// PRODUCT DETAIL
function productDetailHandler() {
  swiperBottomProductBox();
}

let galleryThumbs = new Swiper(".gallery-thumbs", {
  spaceBetween: 4,
  slidesPerView: 4,
  slideToClickedSlide: true,
  freeMode: true,
  watchSlidesProgress: true,
  centerInsufficientSlides: true,
  breakpoints: {
    577: {
      slidesPerView: 6,
    },
  },
});

let galleryTop = new Swiper(".gallery-top", {
  spaceBetween: 0,
  slidesPerView: 1,
  speed: 1000,
  autoplay: {
    delay: 2500,
    disableOnInteraction: false,
    pauseOnMouseEnter: "true",
  },
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
  thumbs: {
    swiper: galleryThumbs,
  },
  // AUTO SILDED AT FISRT AND END
  on: {
    slideChange: function () {
      let activeIndex = this.activeIndex + 1;

      let activeSlide = document.querySelector(
        `.gallery-thumbs .swiper-slide:nth-child(${activeIndex})`
      );
      let nextSlide = document.querySelector(
        `.gallery-thumbs .swiper-slide:nth-child(${activeIndex + 1})`
      );
      let prevSlide = document.querySelector(
        `.gallery-thumbs .swiper-slide:nth-child(${activeIndex - 1})`
      );

      if (
        nextSlide &&
        !nextSlide.classList.contains("swiper-slide-visible")
      ) {
        this.thumbs.swiper.slideNext();
      } else if (
        prevSlide &&
        !prevSlide.classList.contains("swiper-slide-visible")
      ) {
        this.thumbs.swiper.slidePrev();
      }
    },
  },
});

$('[data-fancybox="gallery"]').fancybox({
  thumbs: {
    autoStart: true
  }
});

function swiperBottomProductBox() {
  new Swiper(".bottom-product-box-swiper", {
    slidesPerView: 2.2,
    spaceBetween: 10,
    rewind: true,
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      1601: {
        slidesPerView: 6,
        spaceBetween: 12,
      },
      1201: {
        slidesPerView: 5,
      },
      1025: {
        slidesPerView: 4,
      },
      769: {
        slidesPerView: 3,
      },
    },
  });
}

// CART
function cartHandler() {
  //thay doi so luong chon mua
  listenQuantityBuy();

  //xoa sp
  listenDeleteCartItem();

  //
  clickOutSideCloseProvinceContent();

  //
  paymentMethodChange();
}

function paymentMethodChange() {
  $('.list-pay-method label').on("click", function () {
    $('.list-pay-method label').removeClass('active');
    $(this).addClass('active');
  })
}

// Kiem tra gui don hang
function check_send_cart() {
  const noffyEL = $('#cart-policy-noffy');

  const checkForm = checkFormGlobal('#js-customer-form', '#d9d9d9');
  if (!checkForm.result) noffyEL.html(`Có lỗi xảy ra. Vui lòng kiểm tra lại <span class="color-primary font-weight-700">THÔNG TIN GIAO HÀNG</span>.`);

  return checkForm.result;
}

// thay doi tong gia cua 1 san pham
function changeItemTotalPrice() {
  var $row = $(this).closest(".js-item-row");
  var $row_type = $row.data("item_type");
  var $row_price = $row.find(".js-buy-price");
  var $row_quantity = $row.find(".js-buy-quantity");

  var price = $row_price.attr("data-price");
  var quantity = $row_quantity.val();
  var total_price = price * quantity;

  //loai bo so luong vo ly
  if (quantity < 0 && 1 < 2) {
    $row_quantity.val(0);
    total_price = 0;
  }

  $row_price.html(formatCurrency(total_price) + ' ₫');

  calculateCartTotalPrice();

  //save to cart
  switch ($row_type) {
    case "product":
      Hura.Cart.Product.update($row.data("item_id"), $row.data("variant_id"), { quantity: quantity });
      break;

    case "deal":
      Hura.Cart.Deal.update($row.data("item_id"), { quantity: quantity });
      break;

    case "combo":
      Hura.Cart.Combo.update($row.data("item_id"), { quantity: quantity });
      break;
  }
}

// tinh tong gia don hang
function calculateCartTotalPrice() {
  var dom_target = ".js-total-cart-price";
  var dom_target_2 = ".js-total-cart-price-temp";
  var total_cart_price = 0;

  $(".js-buy-price").each(function () {
    total_cart_price += strToNumber($(this).text());
  });

  checkVoucherPriceOffExist(total_cart_price);

  //log for other reference
  $("#js-total-before-fee-discount").val(total_cart_price);
  //giam gia khac: voucher, membership, loyalty point conversion
  var total_discount = 0;
  total_discount += parseInt($("#js-discount-voucher").val());
  total_discount += parseInt($("#js-discount-membership").val());

  $("#js-discount-price").html(formatCurrency(total_discount) + ' ₫');

  //phi khac: shipping, COD...
  var total_other_fee = 0;
  total_other_fee += parseInt($("#js-fee-shipping").val());
  total_other_fee += parseInt($("#js-fee-cod").val());

  setTimeout(function () {
    $(dom_target_2).html(formatCurrency(total_cart_price) + ' ₫');
    $(dom_target).html(formatCurrency(total_cart_price - total_discount - total_other_fee) + ' ₫');
  }, 100)
}

// LANG NGHE THAY DOI SO LUONG SP
function listenQuantityBuy() {
  const $track_change = $(".js-quantity-change");

  $track_change.on("change", function (e) {
    if ($(this).val() < 1 && 1 < 2) $(this).val(1);
    $(this).attr("value", e.target.value);

    calcTotalCartQuantity("input", parseInt(e.target.value));
    changeItemTotalPrice.call(this);
  });

  $track_change.on("click", function (e) {
    if (e.target.nodeName === "INPUT") return;

    let quantity_change = parseInt(this.getAttribute("data-value"));
    let $row = $(this).closest(".js-item-row");
    let current_quantity = parseInt($row.find(".js-buy-quantity").val());

    if (current_quantity + quantity_change < 1 && 1 < 2) {
      $row.find(".js-buy-quantity").val(1);
      return;
    }

    let totalQuantity = current_quantity + quantity_change;
    $row.find(".js-buy-quantity").val(totalQuantity);

    calcTotalCartQuantity("click", quantity_change);
    changeItemTotalPrice.call(this);
  });
}

//
function calcTotalCartQuantity(type, value) {
  let total_temp = 0;
  const $total_quantity = $("#js-cart-total-quantity");
  const total_current = parseInt($total_quantity.attr("data-total-quantity"));

  $(".js-buy-quantity").each(function () { total_temp += parseInt($(this).attr("value")); })

  const total_change = type === "input" ? total_temp : total_current + value;

  $total_quantity.html(`Tạm tính (${total_change} sản phẩm)`);
  $total_quantity.attr("data-total-quantity", total_change);
}

//
function listenDeleteCartItem() {
  $(".js-delete-cart-item").on("click", function () {
    const _this = this;

    QiuModal.call({ type: "comfirm", content: "Bạn muốn xóa sản phẩm này khỏi giỏ hàng?" }).then(function (respond) {
      if (respond.result) deleteCartItem(_this);
    });
  })
}

// nghe xoa san pham
function deleteCartItem(_this) {
  const $row = $(_this).closest(".js-item-row");
  const item_type = $row.data("item_type");
  const item_id = $row.data("item_id");

  let deleteStatus;
  //save to cart
  switch (item_type) {
    case "product":
      deleteStatus = Hura.Cart.Product.remove(item_id, $row.data("variant_id"));
      break;

    case "deal":
      deleteStatus = Hura.Cart.Deal.remove(item_id);
      break;

    case "combo":
      deleteStatus = Hura.Cart.Combo.remove(item_id);
      break;
  }

  if (deleteStatus) {
    deleteStatus.then(function () {
      $row.remove();
      calculateCartTotalPrice();
      Hura.Cart.getSummary().then(function (data) {
        //console.log(data);
        $("#js-cart-total-quantity").attr("data-total-quantity", data.total_quantity).html(`Tạm tính (${data.total_quantity} sản phẩm)`);
      })
      if ($(".js-item-row").length == 0) {
        setTimeout(function () {
          location.reload();
        }, 500);
      }
    })
  }
}

// voucher
function checkVoucherPriceOffExist(total_cart_price) {
  let voucherValue = parseInt($("#js-discount-voucher").val());
  let priceoffValue = parseInt($("#js-priceoff-voucher").attr("value"));
  if (priceoffValue) {
    voucherValue = total_cart_price * priceoffValue / 100;
    $("#js-discount-voucher").val(voucherValue);
  }
}

function listenVoucherCode(dom_node) {
  let cart_total_before_fee_discount = $("#js-total-before-fee-discount").val();
  const $message_holder = $("#js-voucher-message");

  $(dom_node).change(debounce(function () {
    let voucher_code = this.value.trim();

    //update field to send when submit
    $("#js-coupon-code").val(voucher_code);
    $("#js-discount-voucher").val(0);
    $("#js-discount-price").html('');
    $message_holder.html('');

    //xu ly hien thi
    if (voucher_code.length > 2) {
      var params = {
        action_type: 'check',
        code: voucher_code,
        order_value: cart_total_before_fee_discount,
        product_ids: product_in_cart.join(',')
      }

      Hura.Ajax.post('coupon', params).then(function (data) {
        //console.log(data);
        var voucher_info = data;

        if (voucher_info.status == 'error') {
          $message_holder.show().html(voucher_info.message);
          return;
        }

        if (voucher_info.coupon_info.type == "priceoff") {
          $message_holder.show().html(`<p id="js-priceoff-voucher" value="${voucher_info.coupon_info.content}">Bạn đang sử dụng mã coupon/voucher: <b class="text-16 color-red">${voucher_info.coupon_info.title}</b></p>`);
        } else {
          $message_holder.show().html(`Bạn đang sử dụng mã coupon/voucher: <b class="text-16 color-red">${voucher_info.coupon_info.title}</b>`);
        }

        //xu ly khac
        switch (voucher_info.coupon_info.type) {
          case "cash": //giam tru tien
            $("#js-discount-voucher").val(Hura.Util.strToNumber(voucher_info.coupon_info.cash_discount));
            break;

          case "priceoff": //giam gia %
            var total_price_in_cart = $('#js-total-before-fee-discount').val();
            var after_discount = Math.ceil(total_price_in_cart * voucher_info.coupon_info.content / 100);
            $("#js-discount-voucher").val(Hura.Util.strToNumber(after_discount));
            break;

          case "pro":
            //todo:
            break;

          case "other":
            //todo:
            break;
        }

        calculateCartTotalPrice();
      })
    } else {
      $("#js-discount-voucher").val(0);
      $message_holder.hide().html('');
      calculateCartTotalPrice();
    }
  }, 500));
}


function showProvinceContent(_this) {
  const $target = $(_this).closest(".form-select").find(".form-select-list");

  if (!$target.hasClass('onSelect')) {
    $(".form-select-list").hide().removeClass("onSelect");
    $target.fadeIn().addClass("onSelect");
  }
}

function clickOutSideCloseProvinceContent() {
  $(document).on("click", function (e) {
    const $container = $(".form-select");
    const $target = $(".form-select-list");

    if (!$container.is(e.target) && $container.has(e.target).length === 0) $target.hide().removeClass("onSelect");
  })
}

function searchProvinceHandler(_this) {
  const $search_list = $(_this).closest('.form-select-list').find('.form-select-search-result .item');
  const search_value = convertToSlug($(_this).val().toLowerCase().trim());

  if (search_value) {
    $search_list.each(function () {
      const $search_text = convertToSlug($(this).text().toLowerCase().trim());

      if ($search_text.indexOf(search_value) > -1) $(this).show();
      else $(this).hide();
    })
  } else $search_list.show()
}

// HURA 8
function getProvinceList(_this, type, target) {
  let params;
  let next_type = '';
  let next_target = '';
  const id = parseInt($(_this).attr('data-key'));
  const text = $(_this).text().trim();
  const $input = $(_this).closest('.form-select').find('.js-input-primary');
  const $input_data = $(_this).closest('.form-select').find('.js-input-data');
  const $input_invalid = $(target).closest('.form-select').find('.form-select-input.invalid');
  const $input_target = $(target).closest('.form-select').find('.js-input-primary');

  $input.val(text);
  $input_target.val('');
  $input_data.val(id).attr('value', id);
  $input_invalid.removeClass('invalid');
  $('body').click();

  if (type === 'province') {
    params = { action_type: 'district-list', province: id };
    next_type = 'district';
    next_target = '#js-search-ward-result';

    $(next_target).html(`<li class="item text-center mb-2" style="grid-column:span 2;pointer-events:none">Bạn chưa chọn Quận/Huyện</li>`);
    $(next_target).closest('.form-select').find('.js-input-primary').val('');
    $(next_target).closest('.form-select').find('.form-select-search .form-select-input').addClass('invalid');
  }
  else if (type === 'district') params = { action_type: 'ward-list', district: id };
  else return;

  Hura.Ajax.get("province", params).then(function (data) {
    //console.log(data);
    let html_tpl = '';
    data.forEach(function (item) {
      html_tpl += `<li class="item" onclick="getProvinceList(this, '${next_type}', '${next_target}');" data-key="${item.id}">${item.name}</li>`;
    })
    $(target).html(html_tpl);
  })
}