document.addEventListener("DOMContentLoaded", () => {
  console.log("admin.js loaded (PowerWidget)");

  const $ = jQuery;

  $('input[name="firevert_power_widget_type"]').change(function () {
    const selectedType = $(this).val();

    $(".widget-type-block").hide();

    if (selectedType === "text") {
      $("#widget-type-text").show();
    } else if (selectedType === "image") {
      $("#widget-type-image").show();
    }
  });

  $("#select-widget-image").on("click", function (e) {
    e.preventDefault();

    let image_frame;

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

    image_frame = wp.media({
      title: "Select Image",
      multiple: false,
      library: {
        type: "image",
      },
    });

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

      $("#firevert_power_widget_image").val(attachment.id);

      const img = $("<img>").attr({
        src: attachment.url,
        style: "max-width:100%; height:auto;",
      });

      $("#widget-image-preview").html(img);
    });

    image_frame.open();
  });
});
