(function ($) {
  "use strict";

  var mediaFrames = {};
  var config = window.polangerMaintenanceCenterAdmin || {};

  function initializeColorPickers() {
    if ($.fn.wpColorPicker) {
      $(".pmc-color-field").wpColorPicker();
    }
  }

  function initializeCodeEditor(selector, settings) {
    if (!window.wp || !wp.codeEditor || !settings || !document.querySelector(selector)) {
      return;
    }

    wp.codeEditor.initialize(selector, settings);
  }

  function toggleSelectedState(selector) {
    $(selector).each(function () {
      var $card = $(this);
      var $input = $card.find("input").first();

      if (!$input.length) {
        return;
      }

      $card.toggleClass("is-selected", $input.is(":checked"));
    });
  }

  function refreshSelectableCards() {
    toggleSelectedState(".pmc-mode-card");
    toggleSelectedState(".pmc-role-card");
    toggleSelectedState(".pmc-check-card");
    toggleSelectedState(".pmc-alignment-option");
  }

  function refreshConditionalFields() {
    var backgroundType = $("input[name='pdt_maintenance_center[background_type]']:checked").val() || "gradient";
    var countdownEnabled = $("#pmc-countdown-enabled").is(":checked");
    var hasScheduleEnd = $.trim($("#pmc-schedule-end").val() || "").length > 0;

    $("[data-pmc-conditional='countdown']").toggleClass("is-visible", countdownEnabled);
    $("[data-pmc-conditional='countdown-schedule-on']").toggleClass("is-visible", countdownEnabled && hasScheduleEnd);
    $("[data-pmc-conditional='countdown-schedule-off']").toggleClass("is-visible", countdownEnabled && !hasScheduleEnd);
    $("[data-pmc-conditional='background-secondary']").toggleClass("is-visible", backgroundType === "gradient" || backgroundType === "image");
    $("[data-pmc-conditional='background-image']").toggleClass("is-visible", backgroundType === "image");
  }

  function updateMediaPreview(fieldBase, image) {
    var $preview = $("[data-pmc-media-preview='" + fieldBase + "']");
    var $idField = $("[data-pmc-media-id='" + fieldBase + "']");
    var $urlField = $("[data-pmc-media-url='" + fieldBase + "']");
    var $openButton = $("[data-pmc-media-open='" + fieldBase + "']");
    var $clearButton = $("[data-pmc-media-clear='" + fieldBase + "']");

    if (image && image.url) {
      $idField.val(image.id || "");
      $urlField.val(image.url);
      $preview.addClass("has-image").html('<img src="' + image.url + '" alt="">');
      $openButton.text(config.changeImage || "Change image");
      $clearButton.prop("disabled", false);
      return;
    }

    $idField.val("");
    $urlField.val("");
    $preview.removeClass("has-image").html("<span>" + (config.noImageSelected || "No image selected yet.") + "</span>");
    $openButton.text(config.chooseImage || "Choose image");
    $clearButton.prop("disabled", true);
  }

  function openMediaFrame(fieldBase) {
    if (mediaFrames[fieldBase]) {
      mediaFrames[fieldBase].open();
      return;
    }

    mediaFrames[fieldBase] = wp.media({
      title: config.mediaTitle || "Choose an image",
      button: {
        text: config.mediaButton || "Use this image"
      },
      multiple: false,
      library: {
        type: "image"
      }
    });

    mediaFrames[fieldBase].on("select", function () {
      var selection = mediaFrames[fieldBase].state().get("selection").first();

      if (!selection) {
        return;
      }

      var data = selection.toJSON();
      updateMediaPreview(fieldBase, {
        id: data.id,
        url: data.url
      });
    });

    mediaFrames[fieldBase].open();
  }

  $(function () {
    initializeColorPickers();
    initializeCodeEditor("#pmc-custom-css", config.cssEditor);
    initializeCodeEditor("#pmc-custom-js", config.jsEditor);
    refreshSelectableCards();
    refreshConditionalFields();

    $(document).on("change", ".pmc-mode-card input, .pmc-role-card input, .pmc-check-card input, .pmc-alignment-option input", refreshSelectableCards);
    $(document).on("change", "#pmc-countdown-enabled, #pmc-schedule-end, input[name='pdt_maintenance_center[background_type]']", refreshConditionalFields);

    $(document).on("click", "[data-pmc-media-open]", function (event) {
      event.preventDefault();
      openMediaFrame($(this).data("pmc-media-open"));
    });

    $(document).on("click", "[data-pmc-media-clear]", function (event) {
      event.preventDefault();
      updateMediaPreview($(this).data("pmc-media-clear"), null);
    });
  });
})(jQuery);
