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

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


// GLOBAL HANDLER
function globalHandler() {
  lazyLoadingGroupHandler(lazy_load_group);
  runLazyImageLoad();
  searchHandler("#js-search-bar", "product");
  closeWhenClickOutside();
  viewMoreHandler('.js-vm-block');
  //headerCartHandler();

  if (window.screen.availWidth < 769 && 1 < 2) scrollPageMbHandler();
}

function addComboToCart(combo_id, quantity) {
  Hura.Cart.Combo.add(combo_id, { quantity: quantity }).then(function (response) {
    //console.log(response);

    if (response.status == 'error') {
      if (response.error_type == 'item-in-cart') callModal('error', 'Combo đã trong giỏ hàng!');
      else if (response.error_type == 'invalid-item-id') callModal('error', 'ID combo không đúng!');
      else callModal('error', response.message);
    } else {
      modalSuccess();
      setTimeout(function () {
        location.href = "/cart";
      }, 1200)
    }
  });
}

function toggleMenu() {
  $("#js-global-menu").toggleClass("active");
  $("body").toggleClass("overflow-hidden");
}

function slideMenuItem(_this, type) {
  $(_this).toggleClass("active");

  switch (type) {
    case "sub-menu":
      $("#js-sub-menu").slideToggle();
      break;
    case "sub-menu-2":
      $("#js-sub-menu-2").slideToggle();
      break;
    case "sub-item":
      $(_this)
        .closest(".sub-item")
        .find(".cat-child")
        .first()
        .slideToggle();
      break;
    default:
      break;
  }
}

function scrollPageMbHandler() {
  $(window).scroll(function () {
    let distance = $(document).scrollTop();
    globalHeaderMbHandler(distance);
  })
}

function globalHeaderMbHandler(distance) {
  if (distance > 500) {
    if (!$('.col-search').hasClass('clicked')) {
      $('.col-search').slideUp();
      $('.header-search-mb-btn').fadeIn();
      $('.social_ct_fixed').fadeIn();
    }
  } else {
    $('.col-search').slideDown().removeClass('clicked');
    $('.header-search-mb-btn').fadeOut();
    $('.social_ct_fixed').fadeOut();
  }
}

function arccodionMBHandler(_this) {
  if (window.screen.availWidth > 768) return;

  const arccodionBlock = $(_this).closest(".accordion");
  const arccodionItem = $(_this).closest(".accordion-item");
  const arccodionIcon = arccodionItem.find(".accordion-icon");
  const arccodionContent = arccodionItem.find(".accordion-content");

  if (!arccodionContent.hasClass('a-active')) {
    arccodionBlock.find(".accordion-content").slideUp().removeClass("a-active");
    arccodionBlock.find(".accordion-icon").removeClass("rotate");
  }

  arccodionContent.slideToggle().toggleClass("a-active");
  if (arccodionIcon) arccodionIcon.toggleClass("rotate");
}

// HOMEPAGE HANDLER
function homepageHandler() {
  swiperHomepageShowcase();
  swiperSectionApplication();
  swiperSectionProductBestsale();
}

function getArticlesNewestHomepage() {
  $.get("/ajax/get_json.php", {
    action: "article",
    action_type: "list",
    type: "article",
    sort: "new",
    show: 5
  }, function (data) {
    const newData = JSON.parse(data);
    // console.log(newData);

    const filterData = newData.list.slice(0, 5);
    HuraRenderAjax(filterData, article_newest_homepage_tpl, '#js-article-newest-homepage-list')
  });
}

function getArticlesFeaturedHomepage() {
  $.get("/ajax/get_json.php", {
    action: "article",
    action_type: "list",
    type: "article",
    featured: 1,
    sort: "new",
    show: 4
  }, function (data) {
    const newData = JSON.parse(data);
    // console.log(newData);

    if (newData.total == 0) {
      $('#js-article-featured').remove();
      return;
    }

    const filterData1 = [...[], newData.list[0]];
    const filterData2 = newData.list.slice(1, 4);

    HuraRenderAjax(filterData1, article_featured_homepage_tpl, '#js-article-featured-big');
    HuraRenderAjax(filterData2, article_featured_homepage_tpl, '#js-article-featured-list');
  });
}

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

function swiperSectionProductBestsale() {
  new Swiper(".swiper-product-bestsale", {
    slidesPerView: 2,
    spaceBetween: 10,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      577: {
        slidesPerView: 3,
      },
      769: {
        slidesPerView: 4,
      },
      1025: {
        spaceBetween: 12,
        slidesPerView: 5,
      }
    },
  });
}

function swiperSectionApplication() {
  new Swiper(".swiper-section-application", {
    slidesPerView: 1.5,
    spaceBetween: 10,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      577: {
        slidesPerView: 2,
      },
      769: {
        slidesPerView: 3,
      },
    },
  });
}

// CATEGORY HANDLER
function categoryHandler() {

}

// PRODUCT DETAIL HANDLER
function productDetailHandler() {
  listenQuantityBuy();
  productAttrDisplayHandler();
  ratingHover();
  convertAvatarUser();
  swiperProRelated();
  swiperArticleRelated();

  if (window.screen.availWidth > 768) {
    $('[data-fancybox="gallery"]').fancybox({ thumbs: { autoStart: true } });
    hoverGalleryThumbs();
  }

  $('[data-fancybox]').attr('onclick', 'galleryThumbsNote();');
}

// ADD NOTE FANCYBOX
function galleryThumbsNote() {
  setTimeout(function () {
    $(".fancybox-stage").append(`<p style="position:absolute;bottom:15px;text-align:center;color:#fff;width:100%">Vuốt lên trên hoặc xuống dưới để đóng</p>`)
  }, 200)
}

//
function hoverGalleryThumbs() {
  $('.gallery-thumbs .swiper-slide-hover').on('mouseover', function () {
    galleryTop.slideTo($(this).index());
  })

  $('.gallery-thumbs .swiper-slide').on('click', function () {
    let srcImg = $(this).find('img').attr('src');
    $(`[data-fancybox="gallery"][href="${srcImg}"]`).click();
  })
}

//
let galleryThumbs = new Swiper(".gallery-thumbs", {
  spaceBetween: 10,
  slidesPerView: 4,
  direction: 'horizontal',
  slideToClickedSlide: true,
  freeMode: true,
  watchSlidesProgress: true,
  centerInsufficientSlides: true,
  allowTouchMove: false,
  breakpoints: {
    769: {
      direction: 'vertical',
      slidesPerView: 1,
      spaceBetween: 12,
    },
  },
});

let galleryTop = new Swiper(".gallery-top", {
  spaceBetween: 12,
  slidesPerView: 1,
  speed: 1000,
  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();
      }
    },
  },
});

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

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

  $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-pro-quantity");
    let current_quantity = parseInt($row.find(".js-buy-quantity").val());

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

    let totalQuantity = current_quantity + quantity_change;

    $row.find(".js-buy-quantity").val(totalQuantity);
    $buy_quantity.attr("value", totalQuantity);
  });
}

// ADD PRODUCT TO CART - PRODUCT DETAILS
function addProductToCart(product_id) {
  const stockQuantity = parseInt($("#js-product-quantity").attr("value"));
  const buyQuantity = parseInt($("#js-buy-quantity-temp").val());
  const variantId = parseInt($("#js-product-variant-id").attr("value"));

  let variant_id = 0;
  if (variantId) variant_id = variantId;

  if (stockQuantity) {
    var product_props = {
      quantity: buyQuantity,
      buyer_note: '',
    };

    Hura.Cart.Product.add(product_id, variant_id, product_props).then(function (response) {
      // Error response
      if (response.status === "error") {
        if (response.error_type == "item-in-cart") callGlobalAlertModal("error", "Sản phẩm đã trong giỏ hàng!", "");
        else if (response.error_type == "invalid-item-id") callGlobalAlertModal("error", "ID sản phẩm không đúng!", "");
        else callGlobalAlertModal("error", response.message, "");
      }
      // Success response
      else {
        modalSuccess();
        getHeaderCartListProductNew(response);
      }
    });
  } else callGlobalAlertModal("error", "Sản phẩm không có sẵn. Vui lòng chọn sản phẩm khác hoặc liên hệ lại shop. Xin cảm ơn!", "");
}

// BUY NOW
function buyNow(product_id) {
  addProductToCart(product_id);
  const stockQuantityCheck = parseInt($("#js-product-quantity").attr("value"));
  if (stockQuantityCheck) {
    setTimeout(function () {
      window.location.href = "./cart";
    }, 1500);
  }
}

// 
function productAttrDisplayHandler() {
  $("[data-attr]").on("click", function () {
    const targetName = $(this).attr("data-attr");

    $("[data-attr]").removeClass("active");
    $(this).addClass("active");

    $(".pro-attr-item").hide();
    $(`.${targetName}`).fadeIn();
  })

  if (window.screen.availWidth > 768) $("[data-attr]").first().click();
  viewMoreHandler('.js-vm-block-2');
}

// FUNC REVIEW FORM
function showReviewForm() {
  $(".js-form-review").fadeIn();
  $(".rate-riview-right a").attr("href", "javascript:hideReviewForm()");
  $(".rate-riview-right a").html("Đóng lại !");
  $(".rate-riview-right a").addClass("close-btt")
}

function hideReviewForm() {
  $(".js-form-review").fadeOut();
  $(".rate-riview-right a").attr("href", "javascript:showReviewForm()");
  $(".rate-riview-right a").html("Gửi đánh giá của bạn ");
  $(".rate-riview-right a").removeClass("close-btt")
}

function swiperProRelated() {
  new Swiper(".swiper-pro-related", {
    slidesPerView: 2,
    spaceBetween: 10,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      577: {
        spaceBetween: 12,
        slidesPerView: 3,
      },
      769: {
        slidesPerView: 4,
      },
      1025: {
        slidesPerView: 5,
      },
    },
  });
}

function swiperArticleRelated() {
  new Swiper(".swiper-article-related", {
    slidesPerView: 1.5,
    spaceBetween: 10,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      577: {
        spaceBetween: 12,
        slidesPerView: 2,
      },
      769: {
        slidesPerView: 3,
      },
      1025: {
        slidesPerView: 4,
      },
    },
  });
}

// ARTICLE HANDLER
function articleHandler() {
  swiperProCombo();
}

function swiperProCombo() {
  new Swiper(".swiper-combo-list", {
    slidesPerView: 1.5,
    spaceBetween: 28,
    rewind: true,
    speed: 1000,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: "true",
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      577: {
        slidesPerView: 2,
      },
      769: {
        slidesPerView: 3,
      },
      1025: {
        slidesPerView: 4,
      },
    },
  });
}