(function () {
  "use strict";

  function isNoticeNode(node) {
    return !!(
      node &&
      node.nodeType === 1 &&
      (
        node.matches(".notice") ||
        node.matches(".update-nag") ||
        node.matches(".error") ||
        node.matches(".updated")
      )
    );
  }

  function moveNoticeToStack(stack, notice) {
    if (!stack || !notice || stack.contains(notice)) {
      return;
    }

    stack.appendChild(notice);
  }

  function shouldMoveNotice(notice, stack, wrap, root) {
    if (!notice || !stack || !wrap || !root) {
      return false;
    }

    if (stack.contains(notice) || notice.closest(".pdt-addons-notice-stack")) {
      return false;
    }

    if (notice.closest("#screen-meta, #screen-meta-links, .media-modal, .components-snackbar-list")) {
      return false;
    }

    if (notice.closest(".pdt-addons-wrap")) {
      return true;
    }

    return notice.parentElement === root;
  }

  function collectRelevantNotices(stack, wrap, root) {
    if (!stack || !wrap || !root) {
      return;
    }

    Array.prototype.slice.call(root.querySelectorAll(".notice, .update-nag, .error, .updated")).forEach(function (notice) {
      if (!isNoticeNode(notice)) {
        return;
      }

      if (!shouldMoveNotice(notice, stack, wrap, root)) {
        return;
      }

      moveNoticeToStack(stack, notice);
    });
  }

  document.addEventListener("DOMContentLoaded", function () {
    var shell = document.querySelector(".pdt-addons-page-shell");
    var wrap = shell ? shell.querySelector(".pdt-addons-wrap") : null;
    var stack = shell ? shell.querySelector(".pdt-addons-notice-stack") : null;
    var root = document.getElementById("wpbody-content");

    if (!shell || !wrap || !stack || !root) {
      return;
    }

    collectRelevantNotices(stack, wrap, root);

    if (!window.MutationObserver) {
      return;
    }

    var observer = new MutationObserver(function () {
      collectRelevantNotices(stack, wrap, root);
    });

    observer.observe(root, {
      childList: true,
      subtree: true
    });
  });
}());
