jQuery(document).ready(function ($) {
  function mediaUpload(buttonClass, inputField, previewImage) {
    $(buttonClass).click(function (e) {
      e.preventDefault();
      var mediaUploader = wp.media({
        title: "Choose Image",
        button: { text: "Select Image" },
        multiple: false,
      });

      mediaUploader.on("select", function () {
        var attachment = mediaUploader
          .state()
          .get("selection")
          .first()
          .toJSON();
        $(inputField).val(attachment.url);
        $(previewImage).attr("src", attachment.url);
      });

      mediaUploader.open();
    });
  }

  mediaUpload(
    ".hero_bg_image_upload",
    "#hero_bg_image",
    "#hero_bg_image_preview"
  );

  $(".hero_bg_image_remove").click(function (e) {
    e.preventDefault();
    $("#hero_bg_image").val("");
    $("#hero_bg_image_preview").attr("src", mytheme.defaultHeroImage);
  });

  // header logo upload and footer logo upload

  $(".upload_logo_button").click(function (e) {
    e.preventDefault();
    var targetInput = $(this).data("target"); // Get the target input field
    var custom_uploader = wp
      .media({
        title: "Select Logo",
        button: {
          text: "Use this logo",
        },
        multiple: false,
      })
      .on("select", function () {
        var attachment = custom_uploader
          .state()
          .get("selection")
          .first()
          .toJSON();
        $("#" + targetInput).val(attachment.url);
      })
      .open();
  });
});
