import {createMessenger, loadWidgetConfig} from '@userlike/messenger';

$(document).ready(function () {
  const userlikeCustomButtonSelector = document.querySelector(".userlike-custom-button");
  const widgetConfig = loadWidgetConfig(ihk.settings.userlikeWidgetKey);
  let api;

// Get the config and check if the button should be shown
  widgetConfig.then((config) => {
    if (!config.hide_button) {
      if (userlikeCustomButtonSelector) {
        if (!userlikeCustomButtonSelector.classList.contains("initialized")) {
          userlikeCustomButtonSelector.addEventListener("click", userlikeInitClickHandler);
        }

      } else {
        createUserlikeMessenger();
      }
    }

  }).catch((error) => {
    console.log(error);
  });

  function userlikeInitClickHandler() {
    createUserlikeMessenger();
    userlikeCustomButtonSelector.classList.add("initialized");
    userlikeCustomButtonSelector.removeEventListener("click", userlikeInitClickHandler);
  }

  function createUserlikeMessenger() {

    const result = createMessenger({
      version: 1,
      widgetKey: ihk.settings.userlikeWidgetKey,
    });
    result.then((result) => {
      if (result.kind === "error") throw new Error(result.error);
      api = result.value.api;
      api.mount().then(() => {
          requestAnimationFrame(() => {
            if (ihk.settings.useOriginalChattoolButton) {
              // Show userlike original button
              api.setVisibility({
                main: true,
                button: true,
                notifications: true,
              });
            } else {
              // Show gfi button and listen to the click
              api.setVisibility({
                main: true,
                button: false,
                notifications: true,
              }).then(() => {
                setTimeout(() => {
                  api.maximize();
                }, 1000);
              });


              userlikeCustomButtonSelector.addEventListener("click", () => {
                api.maximize();
              });
            }


          });
        }
      );

      // React to changes, for example mum of nottifications
      //  api.state$.subscribe({
      //   next: (state) => console.log("next", state),
      //   complete: () => console.log("complete"),
      // });

    }).catch((error) => {
      console.log(error);
    });
  }

});



