document.title = DDetail.diamond.title;

$(document).ready(function () {
  // set query string in back to collection.
  var queryString = localStorage.getItem("kirb_query_string");
  backToCollection = DDetail.catgUrl;
  if(queryString) {
    backToCollection += '?' + queryString;
  }

  $("#back-to-coll").attr("href", backToCollection);

  // Slick slider
  // $('.slider-thumbnail').slick({
  //   slidesToShow: 4,
  //   slidesToScroll: 1,
  //   dots: false,
  //   arrows: true,
  //   infinite: false
  // });

  $(`span[data-color='${DDetail.diamond.color}']`).addClass("gld-c");
  $(`span[data-clarity='${DDetail.diamond.clarity}']`).addClass("gld-c");  

  // Set diamond carat pointer
  setCaratPointer(DDetail.diamond['weight']);

  $(".kirb-img-item").click((e) => {
    if (e.currentTarget.dataset.img != "none") {
      $(".kirb-img-item").removeClass("active");
      $(e.currentTarget).addClass("active");
      $(".kirb_detail_img_preview").hide();
      $(`.${e.currentTarget.dataset.img}`).show();
    }
  });

  $(".kirb_diamond_byor").click((e)=>{
    toggle_kirb_loader(true);
    $.get(KIRB_GLOBALS.ajax_url, {
      action: "kirb_add_to_byor",
      product_id: DDetail.diamond._id,
      diamond_type: DDetail.is_gemstone ? 'gemstone' : 'diamond',
      type: 'diamond',
      diamond_redirect: $(this).attr("data-type"),
      nonce: KIRB_GLOBALS.nonce,
    }, (resp)=>{
      if(resp.status == 'success') {
        window.location.href = resp.redirect_url;
      }
    });
  });

  $('#choose-bttn-modal').modal({
    backdrop: 'static',
    keyboard: false
  });

  $('#choose-bttn-modal').on('show.bs.modal', function () {
    $(this).addClass('modal-static');
  }).on('hide.bs.modal', function () {
    $(this).removeClass('modal-static');
  });

  let wishlist_timer = null;

  $(".kirb-wishlist-btn").click((e) => {
    let enabled = $(e.currentTarget).hasClass("active-wishlist");
    let action = enabled ? "remove" : "add";
    $(e.currentTarget).toggleClass("active-wishlist");
    if(wishlist_timer) {
      clearTimeout(wishlist_timer);
    }
    wishlist_timer = setTimeout(()=>{
      $.post(
        KIRB_GLOBALS.ajax_url,
        {
          action: "kirb_toggle_wishlist_diamond",
          diamond_id: DDetail.diamond._id,
          m_action: action,
          nonce: KIRB_GLOBALS.nonce,
        },
        (resp) => {}
      );
    }, 1000);
  });

  // Add to recent products
  kirb_recent_prod(DDetail.diamond._id, DDetail.current_catg);

  // Prepare All Modals
  setTimeout(() => {
    $("body").append(DViewModals.drop_hint_popup_code);
    $("body").append(DViewModals.consult_expert_popup_code);
    $("body").append(DViewModals.share_popup_code);
    $("body").append(DViewModals.certificate_popup_code);
    $("body").append(DViewModals.view_360_popup_code);
    $("body").append(DViewModals.diamond_tryon);
    
    // Flushes the modals from the memory
    DViewModals = null;

    // Model Listeners
    
    $("#pageLinkText").html(window.location.href);

    $("#share_facebook").attr("href", `https://www.facebook.com/sharer/sharer.php?u=${window.location.href}`);
    // $("#share_instagram").attr("href", `https://www.facebook.com/sharer/sharer.php?u=${window.location.href}`);
    $("#share_pinterest").attr("href", `https://pinterest.com/pin/create/button/?url=${window.location.href}&description=${DDetail.diamond.title}`);
    
    $(".cpy-button").click(()=>{
      let old_html = $(".cpy-button").html();
      $(".cpy-button").html(DTranslations['copied']);
      setTimeout(()=>{
        $(".cpy-button").html(old_html);
      }, 2000);
      copyTextToClipboard(window.location.href);
    });

    $(".send_mail").click(function (e) {
      e.preventDefault();
  
      var idt = $(this).data("id");
  
      let data = {
        rec_email: idt == 'sendDropHint' ? $('#rec_email-'+idt).val() : '',
        email: $('#email-'+idt).val(),
        name: $('#name-'+idt).val(),
        message: $('#message-'+idt).val(),
        phone: idt == 'consult' ? $('#phone-'+idt).val() : '',
        type: $('#type-'+idt).val(),
        prod_url: window.location.href,
        prod_name: DDetail.diamond.title,
        prod_image: DDetail.diamond.imageurl.length == 0 ? DDetail.diamond_err_img : DDetail.diamond.imageurl,
      };
  
      let required_feilds = ['email', 'name'];
      if(idt == 'sendDropHint') {
        required_feilds = ['rec_email', 'email', 'name'];
      }
  
      let verified = true
      $(".kirb_validation_err_lbl").remove();
      required_feilds.forEach((feild)=>{
        if(data[feild].length == 0) {
          $(`#${feild}-${idt}`).after(`<span class="kirb_validation_err_lbl text-danger">${DTranslations['field_required']}.</span>`);
          verified = false;
        }else if(feild == 'email' || feild == 'rec_email') {
          let email = data[feild];
          if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
            $(`#${feild}-${idt}`).after(`<span class="text-danger kirb_validation_err_lbl">${DTranslations['invalid_mail']}.</span>`);
            verified = false;
          }
        }
      });
  
      if(verified && idt == 'sendDropHint' && data['email'] == data['rec_email']) {
        $(`#email-${idt}`).after(`<span class="text-danger kirb_validation_err_lbl">${DTranslations['email_not_recept']}.</span>`);
        verified = false;
      }
  
      if(!verified) {return;}
  
      toggle_kirb_loader(true);
  
      $.get(
        KIRB_GLOBALS.ajax_url,
        {
          action: "kirb_send_mail",
          data: data,
          type: 'detail',
          nonce: KIRB_GLOBALS.nonce,
        },
        (resp) => {
          toggle_kirb_loader(false);
          if (resp.status == "success") {
            $("#resMessage-" + idt).html(resp.message);
            if(idt == 'sendDropHint') {
              $("#sendDropHint").get(0).reset();
            }else{
              $("#consultExpert").get(0).reset();
            }
          } else {
            $("#resMessage-" + idt).html(resp.message);
          }
        }
      );
    });
    
    $('input[type=number]').on('input', function() {
      this.value = this.value.replace(/[^0-9]/g, '');
    }).on('keydown', function(e) {
        if (e.key === 'e' || e.key === '+' || e.key === '-') {
            e.preventDefault();
        }
    });
  }, 1000);


});

function map(val, min1, max1, min2, max2) {
  r1 = max1 - min1;
  r2 = max2 - min2;
  sv = (val - min1) / r1;
  return min2 + (sv * r2);
}

function setCaratPointer(size) {
  let left_carat = null;
  let center_pointer = null;

  if(size < 0.5) {
    left_carat = 7;
    center_pointer = 7;
  }else if(size >= 0.5 && size <= 1) {
    left_carat = 10;
    center_pointer = map(size, 0.5, 1, 2, 52);
  }else if(size > 1 && size <= 1.5) {
    left_carat = map(size, 1.01, 1.5, 11, 21.5);
    center_pointer = 45;
  }else if(size > 1.5 && size <= 2) {
    left_carat = map(size, 1.51, 2, 21.6, 32.5);
    center_pointer = 45;
  }else if(size > 2 && size <= 2.5) {
    left_carat = map(size, 2.01, 2.5, 32.6, 44);
    center_pointer = 45;
  }else if(size > 2.5 && size <= 3) {
    left_carat = map(size, 2.51, 3, 44.1, 56);
    center_pointer = 45;
  }else if(size > 3 && size <= 3.5) {
    left_carat = map(size, 3.01, 3.5, 56.1, 68.5);
    center_pointer = 45;
  }else if(size > 3.5 && size <= 4) {
    left_carat = map(size, 3.51, 4, 68.6, 81.5);
    center_pointer = 45;
  }else if(size > 4) {
    left_carat = 89.5;
    center_pointer = 76;
  }
  
  $(".pointer-create-css-carat").css("left", `${left_carat}%`);
  $(".pointer-create-css-carat").css("--after-left", `${center_pointer}%`);
}

const reset_byor = (redirect_url) => {
  toggle_kirb_loader(true);
  $.get(
    KIRB_GLOBALS.ajax_url,
    { 
      action: "kirb_reset_byor",
      nonce: KIRB_GLOBALS.nonce
    },
    (response) => {
      window.location.href = redirect_url;
    }
  );
}

// Function to add product to recent products
const kirb_recent_prod = (diamond_id, catg) => {
  if (!DDetail.loggedin) {
    let recent_list = JSON.parse(localStorage.getItem("kirb_recent_list"));
    if (recent_list == null) {
      recent_list = {};
    }

    let current_catg_recent = []; 
    if(recent_list.hasOwnProperty(catg)) {
      current_catg_recent = recent_list[catg];
    }
    
    if (current_catg_recent.includes(diamond_id)) {
      current_catg_recent = current_catg_recent.filter((val) => val != diamond_id);
    }


    if (current_catg_recent.length >= DDetail.max_recent_products) {
      current_catg_recent.pop();
    }
    current_catg_recent.unshift(diamond_id);
    recent_list[catg] = current_catg_recent;
    localStorage.setItem("kirb_recent_list", JSON.stringify(recent_list));
  } else {
    $.get(
      KIRB_GLOBALS.ajax_url,
      { 
        action: "kirb_handle_rc_prods", 
        prod_id: diamond_id, 
        type: "recent", 
        catg: catg,
        nonce: KIRB_GLOBALS.nonce
      },
      (response) => {}
    );
  }
};

function copyTextToClipboard(text) {
  if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(function() {}).catch(function(err) {});
  } else {
      // Fallback for browsers that do not support the Clipboard API
      var textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      document.body.appendChild(textarea);
      textarea.select();
      textarea.setSelectionRange(0, 99999); // For mobile devices
      document.execCommand("copy");
      document.body.removeChild(textarea);
  }
}

const entryTitle = document.getElementsByClassName("entry-title")[0];
if (entryTitle) {
  entryTitle.remove();
}