import $ from "jquery";

var initIconMediaLibrary = function () {
  var fileFrame = null;

  $(document.body).on("click", ".remove-icon-btn", function (e) {
    e.preventDefault();
    var $self = $(this);
    var $parent = $self.closest(".wrp");

    $self.hide();
    $parent.find("input").val("");
    $parent.find(".img-preview").attr("src", "").hide();
  });

  $(document.body).on("click", ".upload-icon-btn", function (e) {
    e.preventDefault();
    var $parent = $(this).closest(".wrp");

    if (!fileFrame) {
      fileFrame = wp.media.frames.file_frame = wp.media({
        title: "Select a image to upload",
        button: {
          text: "Use this image",
        },
        multiple: false,
      });
    } else {
      fileFrame.off("select");
    }

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

      $parent.find(".img-preview").attr("src", attachment.url).show();
      $parent.find("input").val(attachment.id);
      $parent.find(".remove-icon-btn").show();
    });

    fileFrame.open();
  });
};

$(function () {
  $('input[id^="menu-item-megamenu-column"]').on("change", function () {
    $(this).parents('.megamenu-column').find('input[id^="menu-item-megamenu-column"]')
      .not(this)
      .prop("checked", false);
  });
  initIconMediaLibrary();
});
