jQuery(function ($) {
  jQuery(document).ready(function ($) {
    var file_frame;
    var mediaUploader;
    var skyboxErrSec = $(".tpv-env-skybox-section .tpv-errors");
    var skyboxCheckbox = $("#tpv_env_skybox");

    /**
     * File upload on click.
     */
    $("#select-file").on("click", function (event) {
      event.preventDefault();

      if (file_frame) {
        file_frame.open();
        return;
      }

      file_frame = wp.media({
        title: "Select or Upload File",
        button: {
          text: "Use this file",
        },
        multiple: false,
      });

      file_frame.on("select", function () {
        var attachment = file_frame.state().get("selection").first().toJSON();

        if (attachment.url) {
          // $("#file-upload-section").hide();
          $("#tpv_file").val(attachment.url);
          $("#file-preview").html("");
          $("#file-preview").html(
            '<model-viewer src="' + attachment.url + '"> </model-viewer>'
          );

          $(
            "#tpv_custom_side_meta_box .tpv-model-options, #tpv_import_export_button_meta_box .tpv-model-options"
          ).each(function () {
            if ($(this).hasClass("tpv-disable-model-action")) {
              $(this).removeClass("tpv-disable-model-action");
            }
          });

          setTimeout(() => {
            let loadingType = $(
              'input[name="emwvp_loading_type"]:checked'
            ).val();
            if (loadingType) {
              setLoadingType(loadingType);
              // Check Enable Animation Call.
              Tpv_check_enable_animation();

              // By Default Set Post Processing effects.
              tpvSetPostProcessingEffects();

              // Bind after effects are added.
              bindEffectCheckboxes();
            }
          }, 500);
        }
      });
      file_frame.open();
    });

    /**
     * Click to set auto rotate data attributes.
     */
    $(document).on("change", "#tpv_auto_rotate", function (e) {
      //e.preventDefault();
      var modelViewer = $("model-viewer");
      if ($(this).is(":checked")) {
        if (!modelViewer.attr("auto-rotate")) {
          modelViewer.attr("auto-rotate", "");
        }
      } else {
        modelViewer.removeAttr("auto-rotate");
      }
    });

    /**
     * Click to set AR mode data attributes.
     */
    $(document).on("change", "#tpv_ar_mode", function (e) {
      //e.preventDefault();
      var modelViewer = $("model-viewer");

      if ($(this).is(":checked")) {
        if (!modelViewer.attr("ar") && !modelViewer.attr("ar-modes")) {
          modelViewer.attr("ar", "");
          modelViewer.attr("ar-modes", "webxr scene-viewer quick-look");
        }
      } else {
        modelViewer.removeAttr("ar");
        modelViewer.removeAttr("ar-modes");
      }
    });

    /**
     * Click to set AR place on wall data attributes.
     */
    $(document).on("change", "#tpv_place_on_wall", function (e) {
      e.preventDefault();
      var modelViewer = $("model-viewer");

      if ($(this).is(":checked")) {
        if (!modelViewer.attr("ar") && !modelViewer.attr("ar-placement")) {
          modelViewer.attr("ar", "");
          modelViewer.attr("ar-placement", "wall");
        }
      } else {
        modelViewer.removeAttr("ar");
        modelViewer.removeAttr("ar-placement");
      }
    });

    /**
     * Click to set moving controls data attributes.
     */
    $(document).on("change", "#tpv_moving_controls", function (e) {
      var modelViewer = $("model-viewer");
      if ($(this).is(":checked")) {
        if (!modelViewer.attr("camera-controls")) {
          modelViewer.attr("camera-controls", "");
        }
      } else {
        modelViewer.removeAttr("camera-controls");
      }
    });

    /**
     * Click to set zoom enable and disable.
     */
    $(document).on("change", "#tpv_zoom_disable", function (e) {
      var modelViewer = $("model-viewer");
      if ($(this).is(":checked")) {
        if (!modelViewer.attr("disable-zoom")) {
          modelViewer.attr("disable-zoom", "");
        }
      } else {
        modelViewer.removeAttr("disable-zoom");
      }
    });

    /**
     * Click to set ENV as Skybox.
     */
    $(document).on("change", "#tpv_env_skybox", function (e) {
      var modelViewer = $("model-viewer");
      skyboxErrSec.html("").addClass("tpv-d-none");

      if ($(this).is(":checked")) {
        var environmentImage = modelViewer.attr("environment-image");
        if (environmentImage) {
          modelViewer.attr("skybox-image", environmentImage);
        } else {
          skyboxErrSec
            .html("Choose a non-default environment")
            .removeClass("tpv-d-none");
        }
      } else {
        modelViewer.removeAttr("skybox-image");
      }
    });

    /**
     * On Select set tone mapping.
     */
    $(document).on("change", "#tpv_tone_mapping_option", function (e) {
      var modelViewer = $("model-viewer");
      var tone_mapping = $(this).find(":selected").val();
      if (tone_mapping === "aces") {
        modelViewer.removeAttr("tone-mapping");
      } else {
        modelViewer.attr("tone-mapping", tone_mapping);
      }
    });

    /**
     * On Select set environment image.
     */
    $(document).on("change", "#tpv_environment_image", function (e) {
      e.preventDefault();
      var modelViewer = $("model-viewer");
      var ImgURL = $(this).find(":selected").val();
      setUpdateHiddenFields(ImgURL);
      if (ImgURL) {
        modelViewer.removeAttr("environment-image");
        modelViewer.removeAttr("skybox-image");

        if (!modelViewer.attr("environment-image")) {
          modelViewer.attr("environment-image", ImgURL);
          // setUpdateHiddenFields(ImgURL);

          $("#tpvHDRImgPreview").attr("src", ImgURL);
          $(".tpv-upload-hdr-preview").removeClass("tpv-d-none");

          if (skyboxCheckbox.is(":checked")) {
            modelViewer.attr("skybox-image", ImgURL);
            skyboxErrSec.html("");
          }
        }
      } else {
        modelViewer.removeAttr("environment-image");
        modelViewer.removeAttr("skybox-image");
        resetEnvironmentImagePreview();
      }
    });

    /**
     * HDR button click to set environment image.
     */
    $(document).on("click", ".tpv-hdr-uploader", function (e) {
      e.preventDefault(); // Prevent default action
      let modelViewer = $("model-viewer");

      // Create a new media frame for HDR every time
      let hdrUploader = wp.media({
        title: "Choose HDR Image",
        button: {
          text: "Choose HDR Image",
        },
        multiple: false,
      });

      // Handle image selection
      hdrUploader.on("select", function () {
        let attachment = hdrUploader.state().get("selection").first().toJSON();

        if (attachment.url) {
          resetEnvironmentImagePreview();
          setUpdateHiddenFields(attachment.url);

          $(".tpv-upload-hdr-preview").removeClass("tpv-d-none");
          $("#tpvHDRImgPreview").attr("src", attachment.url);

          if ($("#skyboxCheckbox").is(":checked")) {
            modelViewer.attr("skybox-image", attachment.url);
          } else {
            modelViewer.removeAttr("skybox-image");
          }
        }
      });

      hdrUploader.open(); // Open the media frame
    });

    // Prevent 'Enter' key on following event from triggering the poster uploader
    $("#title, .tpv-range-input").on("keydown", function (e) {
      if (e.key === "Enter") {
        e.preventDefault();
      }
    });

    /**
     * Poster Image Upload.
     */
    $(document).on("click", ".tpv-poster-uploader", function (e) {
      e.preventDefault(); // Prevent default action
      let modelViewer = $("model-viewer");

      // Create a new media frame for Poster every time
      let posterUploader = wp.media({
        title: "Choose Poster Image",
        button: {
          text: "Choose Poster Image",
        },
        multiple: false,
      });

      // Handle image selection
      posterUploader.on("select", function () {
        let attachment = posterUploader
          .state()
          .get("selection")
          .first()
          .toJSON();

        if (attachment.url) {
          $("#tpv_poster_image_url").val(attachment.url);
          $("#tpvPosterImgPreview").attr("src", attachment.url);
          $(".tpv-upload-poster-preview").removeClass("tpv-d-none");
          modelViewer.attr("poster", attachment.url);
        }
      });

      posterUploader.open(); // Open the media frame
    });

    /**
     * Remove Poster Image Uploaded.
     */
    $(document).on("click", "#tpvPosterRemoveImgBtn", function (e) {
      e.preventDefault();
      var modelViewer = $("model-viewer");
      $("#tpv_poster_image_url").val("");
      $("#tpvPosterImgPreview").attr("src", "");
      modelViewer.removeAttr("poster");
      $(".tpv-upload-poster-preview").addClass("tpv-d-none");
    });

    /**
     * Set an Exposure.
     */
    $(document).on("input", "#tpv_exposure_value", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "exposure");
    });

    $(document).on("input", "#tpv_exposure_range", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "exposure");
    });

    /**
     * Set an shadow-intensity.
     */
    $(document).on("input", "#tpv_shadow-intensity_value", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "shadow-intensity");
    });

    $(document).on("input", "#tpv_shadow-intensity_range", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "shadow-intensity");
    });

    /**
     * Set an shadow-softness.
     */
    $(document).on("input", "#tpv_shadow-softness_value", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "shadow-softness");
    });

    /**
     * Set an shadow-softness.
     */
    $(document).on("input", "#tpv_shadow-softness_range", function (e) {
      e.preventDefault();
      updateRangeInputValue($(this).val(), "shadow-softness");
    });

    /**
     * Update range input value.
     */
    function updateRangeInputValue(exp_val, attributeType) {
      let exp_new_val = parseFloat(exp_val);
      var modelViewer = $("model-viewer");

      if (isNaN(exp_new_val) || exp_new_val < 0) {
        exp_new_val = 0;
      } else if (exp_new_val > 2) {
        exp_new_val = 2;
      }

      // Update the number input value
      $("#tpv_" + attributeType + "_value").val(exp_new_val);

      // Update the range input value
      $("#tpv_" + attributeType + "_range").val(exp_new_val);

      // Hidden Field Value
      $("tpv_set_" + attributeType + "_value").val(exp_new_val);

      // Update the model-viewer's exposure attribute
      if (exp_new_val === 0) {
        modelViewer.removeAttr(attributeType);
      } else {
        modelViewer.attr(attributeType, exp_new_val);
      }
    }

    /**
     * Set environment image URL to hidden field.
     */
    function setUpdateHiddenFields(ImgURL) {
      const hiddenEnvImgURL = $("#tpv_environment_image_url");
      const hiddenSkyboxImgURL = $("#tpv_skybox_image_url");
      const modelViewer = $("model-viewer");

      $(hiddenEnvImgURL).val(ImgURL);
      $(hiddenSkyboxImgURL).val(ImgURL);
      modelViewer.removeAttr("environment-image");

      if (ImgURL) {
        modelViewer.attr("environment-image", ImgURL);
      }
    }

    /**
     * Remove HDR Image Uploaded.
     */
    $(document).on("click", "#tpvHDRRemoveImgBtn", function (e) {
      e.preventDefault();
      resetEnvironmentImagePreview();
    });

    /**
     * Reset Environment Image Preview.
     */
    function resetEnvironmentImagePreview() {
      var modelViewer = $("model-viewer");

      // Set the environment dropdown to "None"
      $("#tpv_environment_image").val("");

      if ($("#tpv_env_skybox").is(":checked")) {
        $("#tpv_env_skybox").prop("checked", false);
      }

      $("#tpv_skybox_image_url").val("");
      $("#tpvHDRImgPreview").attr("src", "");
      $("#tpv_environment_image_url").val(" ");
      modelViewer.removeAttr("environment-image");
      modelViewer.removeAttr("skybox-image");

      $(".tpv-upload-hdr-preview ").addClass("tpv-d-none");
    }
    /**
     * Set a loading type.
     */
    $(document).on("change", ".emwvp-loading-type", function () {
      if ($(this).is(":checked")) {
        setLoadingType($(this).val());
      }
    });

    function setLoadingType(loadingType) {
      var modelViewer = $("model-viewer");
      if (loadingType) {
        modelViewer.attr("loading", loadingType);
      } else {
        modelViewer.removeAttr("loading", loadingType);
      }
    }
  });

  /**
   * Model viewer custom metafield tabs section.
   */
  jQuery(document).ready(function ($) {
    $(".tab-content").hide();
    $("#tpv-metafield-tabs-nav li:first-child").addClass("active");
    $(".tab-content:first").show();

    // Tab click to active current tab and tab-content.
    $("#tpv-metafield-tabs-nav li").click(function () {
      $("#tpv-metafield-tabs-nav li").removeClass("active");
      $(this).addClass("active");
      $(".tab-content").hide();
      $(".tab-content.tpv-animation-option").addClass("tpv-animation-tab");

      var activeTab = $(this).find("a").attr("href");
      $(activeTab).fadeIn();
      $(activeTab).removeClass("d-none tpv-animation-tab");
      return false;
    });
  });

  /**
   * Customize Limits Control Start.
   */
  jQuery(document).ready(function ($) {
    // On change apply yaw limits.
    $(document).on("change", "#tpv_apply_yaw_limits_box", function (e) {
      var modelViewer = $("model-viewer");
      const applyYawLimitBoxSection = ".tpv-apply-yaw-limits-controls";
      if ($(this).is(":checked")) {
        $(applyYawLimitBoxSection).removeClass("tpv-d-none");
      } else {
        $(applyYawLimitBoxSection).addClass("tpv-d-none");
      }
      //setCustomizeLimitAttributes();
      updateCustomizeLimitAttributes();
    });

    // On change clockwise limit.
    $(document).on("change", "#tpv_apply_pitch_limits_box", function (e) {
      const applyYawLimitBoxSection = ".tpv-apply-pitch-limits-controls";
      if ($(this).is(":checked")) {
        $(applyYawLimitBoxSection).removeClass("tpv-d-none");
      } else {
        $("#tpv_max_camera_orbit_y").val("auto");
        $(applyYawLimitBoxSection).addClass("tpv-d-none");
      }
      updateCustomizeLimitAttributes();
    });

    // On change apply minimum zoom.
    $(document).on("change", "#tpv_apply_minimum_zoom_box", function (e) {
      const applyMinimumZoomSection = ".tpv-apply-minimum-zoom-controls";
      if ($(this).is(":checked")) {
        $(applyMinimumZoomSection).removeClass("tpv-d-none");
      } else {
        $(applyMinimumZoomSection).addClass("tpv-d-none");
        $("#tpv_min_camera_orbit_z").val("auto");
        $("#tpv_customize_set_min_zoom").prop("disabled", false);
        $("#tpv_customize_reset_set_min_zoom").prop("disabled", false);
      }
      updateCustomizeLimitAttributes();
    });

    /*================== Customize Limits Feature Code Started ==================*/

    /*--------------- Apply Yaw Limits Code Started ---------------*/
    /**
     * On Change Range Input Counter-Clockwise Limit.
     */
    $(document).on(
      "input",
      "#tpv_counter_clockwise_limit_range",
      function (e) {
        e.preventDefault();
        updateCustomizerLimitsInputValue($(this).val(), "counter_clockwise");
      }
    );

    /**
     * On Change Number Input Counter-Clockwise Limit.
     */
    $(document).on(
      "input",
      "#tpv_counter_clockwise_limit_value",
      function (e) {
        e.preventDefault();
        updateCustomizerLimitsInputValue($(this).val(), "counter_clockwise");
      }
    );

    /**
     * On Change Range Input Clockwise Limit.
     */
    $(document).on("input", "#tpv_clockwise_limit_range", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "clockwise");
    });

    /**
     * On Change Number Input Clockwise Limit.
     */
    $(document).on("input", "#tpv_clockwise_limit_value", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "clockwise");
    });
    /*--------------- Apply Yaw Limits Code Ended ---------------*/

    /*--------------- Apply Pitch Limits Code Started ---------------*/
    /**
     * On Change Range Input Top Down Limit.
     */
    $(document).on("input", "#tpv_pitch_top_down_limit_range", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "pitch_top_down");
    });

    /**
     * On Change Number Input Top Down Limit.
     */
    $(document).on("input", "#tpv_pitch_top_down_limit_value", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "pitch_top_down");
    });

    /**
     * On Change Range Input Bottom-up Limit.
     */
    $(document).on("input", "#tpv_pitch_bottom_up_limit_range", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "pitch_bottom_up");
    });

    /**
     * On Change Range Input Top Down Limit.
     */
    $(document).on("input", "#tpv_pitch_bottom_up_limit_value", function (e) {
      e.preventDefault();
      updateCustomizerLimitsInputValue($(this).val(), "pitch_bottom_up");
    });
    /*--------------- apply Pitch Limits Code Ended ---------------*/

    /*--------------- Apply minimum zoom code started ---------------*/
    $(document).on("click", "#tpv_customize_set_min_zoom", function (e) {
      e.preventDefault();
      setMinimumZoom("#tpv_customize_set_min_zoom", "4.037m");
    });

    $(document).on(
      "click",
      "#tpv_customize_reset_set_min_zoom",
      function (e) {
        e.preventDefault();
        setMinimumZoom("#tpv_customize_reset_set_min_zoom", "auto");
      }
    );

    function setMinimumZoom(buttonID, value) {
      var modelViewer = $("model-viewer");
      if ("4.037m" === value) {
        modelViewer.attr("min-field-of-view", "30deg");
        $("#tpv_min_field_of_view").val("30deg");
      } else {
        modelViewer.removeAttr("min-field-of-view");
        $("#tpv_min_field_of_view").val("");
      }

      $("#tpv_customize_set_min_zoom").prop("disabled", false);
      $("#tpv_customize_reset_set_min_zoom").prop("disabled", false);

      $(buttonID).prop("disabled", true);
      $("#tpv_min_camera_orbit_z").val(value);
      updateCustomizeLimitAttributes();
    }
    /*--------------- Apply minimum zoom code ended ---------------*/

    function updateCustomizerLimitsInputValue(limitValue, inputFieldType) {
      let parsedValue = parseFloat(limitValue) || 0;

      // Update the range input value.
      $("#tpv_" + inputFieldType + "_limit_range").val(parsedValue);

      // Update the range input value.
      $("#tpv_" + inputFieldType + "_limit_value").val(parsedValue);

      // Update the button value.
      $("#tpv_" + inputFieldType + "_btn_val").html(parsedValue);

      updateCustomizeLimitAttributes();
    }

    function updateCustomizeLimitAttributes() {
      var min_camera_orbit_x = $("#tpv_counter_clockwise_limit_value").val();
      $("#tpv_min_camera_orbit_x").val(min_camera_orbit_x);

      var max_camera_orbit_x = $("#tpv_clockwise_limit_value").val();
      $("#tpv_max_camera_orbit_x").val(max_camera_orbit_x);

      // Apply Pitch Limits
      if ($("#tpv_apply_pitch_limits_box").is(":checked")) {
        var min_camera_orbit_y = $("#tpv_pitch_top_down_limit_value").val();
        var max_camera_orbit_y = $("#tpv_pitch_bottom_up_limit_value").val();
      } else {
        var min_camera_orbit_y = $("#tpv_min_camera_orbit_y").val();
        var max_camera_orbit_y = $("#tpv_max_camera_orbit_y").val();
      }
      $("#tpv_min_camera_orbit_y").val(min_camera_orbit_y);
      $("#tpv_max_camera_orbit_y").val(max_camera_orbit_y);

      setCustomizeLimitAttributes();
    }

    function setCustomizeLimitAttributes() {
      var modelViewer = $("model-viewer");

      // Apply Yaw Limits is checked and Apply Pitch Limits not checked.
      if (
        $("#tpv_apply_yaw_limits_box").is(":checked") &&
        !$("#tpv_apply_pitch_limits_box").is(":checked")
      ) {
        $("#tpv_min_camera_orbit_y").val("auto");
        $("#tpv_max_camera_orbit_y").val("auto");
      }

      // Apply Pitch Limits is checked and Apply Yaw Limits not checked.
      if (
        !$("#tpv_apply_yaw_limits_box").is(":checked") &&
        $("#tpv_apply_pitch_limits_box").is(":checked")
      ) {
        $("#tpv_min_camera_orbit_x").val("auto");
        $("#tpv_max_camera_orbit_x").val("auto");
      }

      // Apply Pitch Limits is checked and Apply Yaw Limits checked and Set Min button clicked(disable).
      if (
        !$("#tpv_apply_yaw_limits_box").is(":checked") &&
        !$("#tpv_apply_pitch_limits_box").is(":checked") &&
        $("#tpv_apply_minimum_zoom_box").is(":checked") &&
        $("#tpv_min_camera_orbit_z").val() === "4.037m"
      ) {
        $("#tpv_min_camera_orbit_x").val("auto");
        $("#tpv_min_camera_orbit_y").val("auto");
      }

      // min-camera-orbit value.
      var min_x_val = $("#tpv_min_camera_orbit_x").val();
      min_x_val =
        min_x_val == "0" || parseFloat(min_x_val)
          ? min_x_val + "deg"
          : min_x_val;

      var min_y_val = $("#tpv_min_camera_orbit_y").val();
      min_y_val =
        min_y_val == "0" || parseFloat(min_y_val)
          ? min_y_val + "deg"
          : min_y_val;
      var min_z_val = $("#tpv_min_camera_orbit_z").val();

      // max-camera-orbit value.
      var max_x_val = $("#tpv_max_camera_orbit_x").val();
      max_x_val =
        max_x_val == "0" || parseFloat(max_x_val)
          ? max_x_val + "deg"
          : max_x_val;

      var max_y_val = $("#tpv_max_camera_orbit_y").val();
      max_y_val =
        max_y_val == "0" || parseFloat(max_y_val)
          ? max_y_val + "deg"
          : max_y_val;
      var max_z_val = $("#tpv_max_camera_orbit_z").val();

      var min_camera_orbit_attr = min_x_val + " " + min_y_val + " " + min_z_val;

      var max_camera_orbit_attr = max_x_val + " " + max_y_val + " " + max_z_val;

      // Apply Pitch Limits is checked and Apply Yaw Limits checked and Set Min button clicked(disable).
      if (
        !$("#tpv_apply_yaw_limits_box").is(":checked") &&
        !$("#tpv_apply_pitch_limits_box").is(":checked") &&
        $("#tpv_apply_minimum_zoom_box").is(":checked") &&
        $("#tpv_min_camera_orbit_z").val() === "4.037m"
      ) {
        modelViewer.attr("min-camera-orbit", min_camera_orbit_attr);
      } else {
        modelViewer.removeAttr("min-camera-orbit");
      }

      // Apply Pitch Limits is checked or Apply Yaw Limits checked.
      if (
        $("#tpv_apply_yaw_limits_box").is(":checked") ||
        $("#tpv_apply_pitch_limits_box").is(":checked")
      ) {
        modelViewer.attr("min-camera-orbit", min_camera_orbit_attr);
        modelViewer.attr("max-camera-orbit", max_camera_orbit_attr);
      } else {
        modelViewer.removeAttr("max-camera-orbit");
      }
    }
  });
  /*================== Customize Limits Feature Code Ended ==================*/
});
