const LaniakeaAdminModule = (function () {
  function ready(fn) {
    if (document.readyState !== "loading") {
      fn();
    } else {
      document.addEventListener("DOMContentLoaded", fn);
    }
  }

  function onReady() {
    const TabHeaders = document.querySelectorAll(
      ".laniakea-multitab .tab-header li"
    );
    const Tabs = document.querySelectorAll(".laniakea-multitab .tab");

    let currentTab =
      sessionStorage.getItem("laniakea_admin_curtab") ?? "generale";

    let tabHeaderToHighlight = document.querySelector(
      'li[data-tab="#' + currentTab + '"]'
    );

    removeActiveTabHeaderClass();
    if (tabHeaderToHighlight) tabHeaderToHighlight.classList.add("active");
    changeActiveTab(document.querySelector("#laniakea #" + currentTab));

    function removeActiveTabHeaderClass() {
      TabHeaders.forEach((th) => th.classList.remove("active"));
    }

    function changeActiveTab(tab) {
      if (!tab) return;
      Tabs.forEach((tab) => tab.classList.remove("active"));
      tab.classList.add("active");
      sessionStorage.setItem("laniakea_admin_curtab", tab.id);
    }

    TabHeaders.forEach((th) => {
      th.addEventListener("click", (e) => {
        removeActiveTabHeaderClass();
        e.currentTarget.classList.add("active");
        let dataTab = e.currentTarget.getAttribute("data-tab");
        changeActiveTab(document.querySelector(dataTab));
      });
    });

    ////LOGO
    var file_frame;
    const logoButton = document.querySelector("#primary-logo-button");
    const primaryLogoPreview = document.querySelector("#primary-logo-preview");
    const primaryLogoInput = document.querySelector("#primary-logo-input");

    const logoMobileButton = document.querySelector(
      "#primary-logo-mobile-button"
    );
    const primaryLogoMobilePreview = document.querySelector(
      "#primary-logo-mobile-preview"
    );
    const primaryLogoMobileInput = document.querySelector(
      "#primary-logo-mobile-input"
    );

    const invertedLogoButton = document.querySelector("#inverted-logo-button");
    const invertedLogoPreview = document.querySelector(
      "#inverted-logo-preview"
    );
    const invertedLogoInput = document.querySelector("#inverted-logo-input");

    const invertedLogoMobileButton = document.querySelector(
      "#inverted-logo-mobile-button"
    );
    const invertedLogoMobilePreview = document.querySelector(
      "#inverted-logo-mobile-preview"
    );
    const invertedLogoMobileInput = document.querySelector(
      "#inverted-logo-mobile-input"
    );

    function initFileFrame(options) {
      file_frame = wp.media.frames.file_frame = wp.media({
        title: options.title,
        button: {
          text: "Usa Questa immmagine",
        },
        multiple: false,
      });

      file_frame.on("select", () => {
        attachment = file_frame.state().get("selection").first().toJSON();

        options.previewNode.setAttribute("src", attachment.url);
        options.inputNode.value = attachment.id;
      });
    }

    logoButton &&
      logoButton.addEventListener("click", (e) => {
        initFileFrame({
          title: "Scegli logo primario",
          previewNode: primaryLogoPreview,
          inputNode: primaryLogoInput,
        });

        file_frame.open();
      });

    invertedLogoButton &&
      invertedLogoButton.addEventListener("click", (e) => {
        initFileFrame({
          title: "Scegli logo inverito",
          previewNode: invertedLogoPreview,
          inputNode: invertedLogoInput,
        });

        file_frame.open();
      });

    logoMobileButton &&
      logoMobileButton.addEventListener("click", (e) => {
        initFileFrame({
          title: "Scegli logo primario",
          previewNode: primaryLogoMobilePreview,
          inputNode: primaryLogoMobileInput,
        });

        file_frame.open();
      });

    invertedLogoMobileButton &&
      invertedLogoMobileButton.addEventListener("click", (e) => {
        initFileFrame({
          title: "Scegli logo inverito",
          previewNode: invertedLogoMobilePreview,
          inputNode: invertedLogoMobileInput,
        });

        file_frame.open();
      });

    ///COLORS
    const ResetBakeryButtons = document.querySelectorAll(".reset-bakery");

    ResetBakeryButtons.forEach((b) =>
      b.addEventListener("click", (e) => {
        let targetName = e.currentTarget.getAttribute("data-name");
        let color = e.currentTarget.getAttribute("data-color");
        console.log(color, targetName);
        let input = document.querySelector(`input[name=${targetName}]`);
        console.log("-->", input);
        input.value = color;
      })
    );

    var gfonts = [];

    (async function fetchGoogleFonts($) {
      ///FONT AUTOCOMPLETE
      if (typeof GFONT_APIKEY != "undefined") {
        let url = `https://www.googleapis.com/webfonts/v1/webfonts?key=${GFONT_APIKEY}`;
        const response = await fetch(url);
        const fonts = await response.json();
        gfonts = fonts.items.map((f) => f.family);
      }

      $(function () {
        try {
          $("#gfont-autocomplete").autocomplete({
            source: gfonts,
            minLength: 3,
            select: function (event, ui) {
              $("#gfont-autocomplete").val(ui.item.value);
            },
            classes: {
              "ui-autocomplete": "laniakea-autocomplete",
            },
          });

          ///COLOR PICKER
          $(".color-picker input").wpColorPicker();
        } catch (e) {
          console.debug("catched exception", e);
        }
      });
    })(jQuery);
  }

  ready(onReady);
})();
