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

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

// GLOBAL
function globalHandler() {
  arccodionHandler('.arc-click');
}

// HOMEPAGE
function homepageHandler() {
  swiperSectionHero();
  swiperCollectionProducts();
  swiper4Slides();
}

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

function swiperCollectionProducts() {
  new Swiper(".swiper-collection-products", {
    slidesPerView: 2.2,
    spaceBetween: 10,
    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: 1.3,
    spaceBetween: 10,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
}

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

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

// FILTER POPUP
function filterPopupHandler() {
  $('.js-filter-title').click(function () {
    var check = $(this).parents('.item');
    if (check.hasClass('active') == true) {
      check.removeClass('active');
      $('.product-cate-bannner, .box-product-hot, .p-filter-group').removeClass('active');
    } else {
      $('.filter-list-box .item').removeClass('active')
      $(this).parents('.item').addClass('active')
      $('.product-cate-bannner, .box-product-hot, .p-filter-group').addClass('active');
    }
  });

  $('.js-sort-check .sort-by-list a').each(function () {
    if ($(this).hasClass('current') == true) {
      var name = $(this).text();
      $('.js-sort-check span').text(name)
    }
  });

  $('.js-filter-selected').click(function () {
    if ($(this).hasClass('current') == true) $(this).removeClass('current');
    else {
      $(this).parents('.js-filter-item').find('.js-filter-selected').removeClass('current');
      $(this).addClass('current');
    }
  });

  $(".popup-filter-group").on("click", function (e) {
    if (e.target === document.querySelector(".popup-filter-group")) {
      $(".popup-filter-group").css("display", "none");
      $("body").removeClass("overflow-hidden");
    }
  })
}

// CHECK VIEW MORE POPUP
function filterPopupListViewMore() {
  $(".list-holder").each(function () {
    let summaryHeight = $(this).height();
    if (summaryHeight >= 133) {
    } else $(this).next().css("display", "none");
  })
}

// ONCLICK VIEW MORE POPUP
function showFilterMoreBtn(_this) {
  $(_this).prev().toggleClass("max-height-none");
  let viewMoreEle = $(_this).find(".js-vm-btn-text");
  let viewMoreIcon = $(_this).find(".js-vm-btn-icon");

  viewMoreEle.html() === "Xem thêm" ? viewMoreEle.html("Thu gọn") : viewMoreEle.html("Xem thêm");
  viewMoreIcon.toggleClass("rotate");
}

// filter
function _getLink(current_url) {
  var sort = '';
  var brand = '';
  var max = '';
  var min = '';
  var atrr_current = '';

  if ($('.js-brand-list a').hasClass('current') == true) brand = '&brand=' + $('.js-brand-list .current').attr('data-brand');
  if ($('.js-price-list a').hasClass('current') == true) max = '&max=' + $('.js-price-list .current').attr('data-max');
  if ($('.js-price-list a').hasClass('current') == true) min = '&min=' + $('.js-price-list .current').attr('data-min');

  $('.js-attr-list .current').each(function () {
    atrr_current += $(this).attr('data-attr') + '_';
  });

  var attr = atrr_current ? '&filter=' + atrr_current : '';

  if (GetURLParameter('sort')) sort = '&sort=' + GetURLParameter('sort')
  var link = current_url + brand + max + min + attr + sort;
  location.href = link;
}

function _openFilter() {
  $('.popup-filter-group').fadeIn(150);
  $('body').addClass('overflow-hidden');
  $('#js-p-filter-group .item.active').removeClass('active');
  $('.product-cate-bannner, .box-product-hot, .p-filter-group').removeClass('active');
  filterPopupListViewMore();
}

function _closeFilter() {
  $('.popup-filter-group').hide();
  $('body').removeClass('overflow-hidden bg-filter');
}
// end filter

function GetURLParameter(sParam) {
  var sPageURL = window.location.search.substring(1);
  var sURLVariables = sPageURL.split('&');
  for (var i = 0; i < sURLVariables.length; i++) {
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam) {
      return sParameterName[1];
    }
  }
}

// 
function productDetailHandler() {
  swiperBottomProductBox()
}

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

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);
  })
}