import { InobyModule } from "@lib/inoby-module";
import $ from "jquery";

class AdminModule extends InobyModule {
  run() {
    this.hideNotices();
    this.initBlockSidebarResizing();
    this.fixEditorRems();
    this.iframeTextAreaPaste();
  }

  private initBlockSidebarResizing() {
    setTimeout(() => {
      const $sidebar = $(".interface-interface-skeleton__sidebar").resizable({
        handles: "w",
        minWidth: 200,
      });
    }, 1000);
  }

  private hideNotices() {
    const noticeSelector = ".notice:not(.hidden), .updated, .woocommerce-store-alerts, .notice-yoast";

    const bodyContent = $("#wpbody-content");
    if (!bodyContent.length) {
      return;
    }

    const adminBadge = $('<li id="inoby-notices">Notifikácie</li>');
    const noticesCounter = $('<div class="counter">0</div>');
    adminBadge.append(noticesCounter);

    $("#wp-admin-bar-root-default").append(adminBadge);

    const getCount = () => $(noticeSelector).length;

    const updateCount = () => {
      const count = getCount();
      noticesCounter.html(count.toString());
      if (count) {
        adminBadge.show();
      } else {
        adminBadge.hide();
      }
    };

    // watch for added notices
    const hideNotice = (notice: JQuery<Node>) => {
      notice.hide();
      updateCount();
    };

    hideNotice($(noticeSelector)); // move existing notices

    const observer = new MutationObserver((mutationList, observer) => {
      mutationList.forEach((mutation) => {
        mutation.addedNodes.forEach((element) => {
          if ($(element).filter(noticeSelector).length) {
            hideNotice($(element));
          }
        });
      });
    });
    observer.observe(bodyContent[0], { attributes: false, childList: true, subtree: true });

    // open close
    adminBadge.on("click", (e) => {
      // notices.css("top", $("#wpadminbar").height());
      const $target = $(e.target);
      if ($target.hasClass("notices-shown")) {
        $target.removeClass("notices-shown");
        $(noticeSelector).slideUp();
      } else {
        $target.addClass("notices-shown");
        $(noticeSelector).slideDown();
      }
    });
  }

  fixEditorRems() {
    const has_editor = $("#wpbody-content>.block-editor").length;
    if (has_editor) {
      document.documentElement.style.fontSize = "62.5%";
    }
  }

  iframeTextAreaPaste() {
    $(document).on("paste", "textarea.rwmb-textarea", (e) => {
      var text;
      var clp = (e.originalEvent as ClipboardEvent)?.clipboardData;
      if (clp !== null) {
        text = clp.getData("text");
        if (text.startsWith("<iframe ")) {
          const regex = /"https?:\/\/(.*?)"/g;
          const matches = text.match(regex);
          if (matches[0] !== null) {
            e.preventDefault();
            (e.target as HTMLInputElement).value = matches[0]?.replace('"', "");
          }
        }
      }
    });
  }
}

new AdminModule().runOnReady();
