$(document).ready(() => {
  // slick slider
  // $(".slider-thumbnail").slick({
  //   slidesToShow: 3,
  //   slidesToScroll: 1,
  //   dots: false,
  //   arrows: true,
  // });

 function kirbLoad360Desktop() {
  if ($(window).width() < 768) return;

  $(".kirb-360-container").each(function () {
    const $iframe = $(this).find(".kirb-review-360-frame");
    if (!$iframe.length) return;

    let videoUrl = $iframe.data("video-url");
    if (!videoUrl) return;

    videoUrl = videoUrl.replace(/\/\d+\/\d+(?=\/|\?|$)/, `/320/320`);

    if (!videoUrl.includes("/true")) {
      videoUrl = videoUrl.includes("?")
        ? videoUrl.replace("?", "/true?")
        : videoUrl + "/true";
    }

    $iframe.attr("src", videoUrl).show();
  });
}

kirbLoad360Desktop();

function kirbLoad360Mobile($iframe) {
  if ($(window).width() >= 768) return;
  if (!$iframe || !$iframe.length) return;

  let videoUrl = $iframe.data("video-url");
  if (!videoUrl) return;

  videoUrl = videoUrl.replace(/\/\d+\/\d+(?=\/|\?|$)/, `/310/310`);

  if (!videoUrl.includes("/true")) {
    videoUrl = videoUrl.includes("?")
      ? videoUrl.replace("?", "/true?")
      : videoUrl + "/true";
  }

  $iframe.attr("src", "");
  setTimeout(() => {
    $iframe.attr("src", videoUrl);
  }, 50);
}

if ($(window).width() <= 768) {
  const $previewBox = $("#kirb-mobile-preview");
  const $thumbnails = $(".thumbnail-image-slide .kirb-img-item");
  const $iframeBox = $(".kirb-360-iframe-mobile-byor");

  if (!$previewBox.length || !$thumbnails.length) return;

  function loadPreview($item) {
    $previewBox.empty();
    $iframeBox.hide();

    if ($item.hasClass("kirb-360-container")) {
      $iframeBox.show();
      $previewBox.hide();
      kirbLoad360Mobile($iframeBox.find(".kirb-review-360-frame"));
      return;
    }

    $previewBox.show();
    const $img = $item.find("img").first();
    if ($img.length) $previewBox.append($img.clone());
  }

  loadPreview($thumbnails.first());

  $thumbnails.on("click", function () {
    loadPreview($(this));
  });
}
  
  $(".360-show-div").on("click", function () {
    if($(document).width() <= 766) {
      $(".kirb-view-360-mob").show();
    }else{
      $(".kirb-view-360").show();
    }
  });

  $(".normal-div").on("click", function () {
    if($(document).width() <= 766) {
      $(".kirb-view-360-mob").attr("style", "display:none !important");
    }else{
      $(".kirb-view-360").hide();
    }
  });

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


  $("#kirb_byor_back_btn").click(()=>{
    window.history.back();
  });

  $("#kirb_byor_start_over_btn").click(() => {
    toggle_kirb_loader(true);
    $.get(
      KIRB_GLOBALS.ajax_url,
      {
        action: "kirb_byor_restart",
        nonce: KIRB_GLOBALS.nonce,
      },
      (resp) => {
        if (resp.status == "success") {
          window.location.href = resp.redirect_url;
        }
      }
    );
  });

  // Prepare All Modals
  setTimeout(() => {
    $("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();
        }
      });

    $(".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_diamond: BYORPageData.byor_diamond_url,
        prod_url_ring: BYORPageData.byor_ring_url,
        prod_price_ring: BYORPageData.byor_ring_price,
        prod_price_diamond: BYORPageData.byor_diamond_price,
        prod_name_ring: BYORPageData.byor_ring_title,
        prod_name_diamond: BYORPageData.byor_diamond_title,
        prod_image: BYORPageData.byor_ring_image,
        page_url: window.location.href,
      };

      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: 'byor',
          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);
          }
        }
      );
    });
  }, 1000);

  $("#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=${BYORPageData.byor_diamond_title}`);

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

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

  $(".cpy-button").click(()=>{
    let old_html = $(".cpy-button").html();
    $(".cpy-button").html("Copied!");
    setTimeout(()=>{
      $(".cpy-button").html(old_html);
    }, 2000);
    copyTextToClipboard(window.location.href);
  });

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