'use strict';

var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
var jsxRuntime = require('react/jsx-runtime');
var auth = require('@web3auth/auth');
var noModal = require('@web3auth/no-modal');
var deepmerge = require('deepmerge');
var react = require('react');
var constants = require('../../constants.js');
var interfaces = require('../../interfaces.js');
var Embed = require('../Embed/Embed.js');
var Modal = require('../Modal/Modal.js');
var Root = require('../Root/Root.js');

function Widget(props) {
  const {
    stateListener,
    handleSocialLoginClick,
    handleExternalWalletClick,
    handleShowExternalWallets,
    closeModal,
    appLogo,
    appName,
    chainNamespaces,
    walletRegistry,
    uiConfig,
    deviceDetails
  } = props;
  const {
    widgetType
  } = uiConfig;
  const visible = react.useMemo(() => widgetType === noModal.WIDGET_TYPE.EMBED, [widgetType]);
  const [modalState, setModalState] = react.useState({
    externalWalletsVisibility: false,
    status: interfaces.MODAL_STATUS.INITIALIZED,
    hasExternalWallets: false,
    externalWalletsInitialized: false,
    modalVisibility: false,
    modalVisibilityDelayed: false,
    postLoadingMessage: "",
    walletConnectUri: "",
    metamaskConnectUri: "",
    socialLoginsConfig: {
      loginMethods: {},
      loginMethodsOrder: [],
      connector: "",
      uiConfig: {}
    },
    externalWalletsConfig: {},
    showExternalWalletsOnly: false,
    currentPage: constants.PAGES.LOGIN,
    detailedLoaderConnector: "",
    detailedLoaderConnectorName: "",
    web3authClientId: "",
    web3authNetwork: auth.WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
    authBuildEnv: auth.BUILD_ENV.PRODUCTION
  });
  react.useEffect(() => {
    setModalState(prev => _objectSpread(_objectSpread({}, prev), {}, {
      modalVisibility: visible
    }));
  }, [visible]);
  react.useEffect(() => {
    stateListener.on("STATE_UPDATED", newModalState => {
      noModal.log.debug("state updated", newModalState);
      setModalState(prevState => {
        const mergedState = noModal.cloneDeep(deepmerge(prevState, newModalState, {
          arrayMerge: (_prevState, newState) => newState
        }));
        return mergedState;
      });
    });
    stateListener.emit("MOUNTED");
  }, [stateListener]);
  const preHandleExternalWalletClick = params => {
    const {
      connector
    } = params;
    setModalState(prevState => _objectSpread(_objectSpread({}, prevState), {}, {
      detailedLoaderConnector: connector,
      detailedLoaderAdapterName: noModal.CONNECTOR_NAMES[connector]
    }));
    // Call the passed-in handler with the params
    if (handleExternalWalletClick) handleExternalWalletClick(params);
  };
  const preHandleSocialWalletClick = params => {
    const {
      loginParams
    } = params;
    setModalState(prevState => {
      return _objectSpread(_objectSpread({}, prevState), {}, {
        detailedLoaderConnector: loginParams.authConnection,
        detailedLoaderConnectorName: loginParams.name
      });
    });
    handleSocialLoginClick(params);
  };
  // Memo for checking if social logins are visible
  const areSocialLoginsVisible = react.useMemo(() => {
    var _modalState$socialLog, _modalState$socialLog2;
    if (modalState.showExternalWalletsOnly) return false;
    if (Object.keys(((_modalState$socialLog = modalState.socialLoginsConfig) === null || _modalState$socialLog === void 0 ? void 0 : _modalState$socialLog.loginMethods) || {}).length === 0) return false;
    const isAnySocialLoginVisible = Object.entries(((_modalState$socialLog2 = modalState.socialLoginsConfig) === null || _modalState$socialLog2 === void 0 ? void 0 : _modalState$socialLog2.loginMethods) || {}).some(([k, v]) => ![auth.AUTH_CONNECTION.EMAIL_PASSWORDLESS, auth.AUTH_CONNECTION.SMS_PASSWORDLESS].includes(k) && v.showOnModal !== false);
    return isAnySocialLoginVisible;
  }, [modalState]);
  // Memo for checking if email passwordless login is visible
  const isEmailPasswordLessLoginVisible = react.useMemo(() => {
    var _modalState$socialLog3;
    return (_modalState$socialLog3 = modalState.socialLoginsConfig) === null || _modalState$socialLog3 === void 0 || (_modalState$socialLog3 = _modalState$socialLog3.loginMethods[auth.AUTH_CONNECTION.EMAIL_PASSWORDLESS]) === null || _modalState$socialLog3 === void 0 ? void 0 : _modalState$socialLog3.showOnModal;
  }, [modalState.socialLoginsConfig]);
  // Memo for checking if SMS passwordless login is visible
  const isSmsPasswordLessLoginVisible = react.useMemo(() => {
    var _modalState$socialLog4;
    return (_modalState$socialLog4 = modalState.socialLoginsConfig) === null || _modalState$socialLog4 === void 0 || (_modalState$socialLog4 = _modalState$socialLog4.loginMethods[auth.AUTH_CONNECTION.SMS_PASSWORDLESS]) === null || _modalState$socialLog4 === void 0 ? void 0 : _modalState$socialLog4.showOnModal;
  }, [modalState.socialLoginsConfig]);
  const isEmailPrimary = react.useMemo(() => {
    var _modalState$socialLog5;
    return ((_modalState$socialLog5 = modalState.socialLoginsConfig) === null || _modalState$socialLog5 === void 0 || (_modalState$socialLog5 = _modalState$socialLog5.uiConfig) === null || _modalState$socialLog5 === void 0 ? void 0 : _modalState$socialLog5.primaryButton) === "emailLogin";
  }, [modalState.socialLoginsConfig]);
  const isExternalPrimary = react.useMemo(() => {
    var _modalState$socialLog6;
    return ((_modalState$socialLog6 = modalState.socialLoginsConfig) === null || _modalState$socialLog6 === void 0 || (_modalState$socialLog6 = _modalState$socialLog6.uiConfig) === null || _modalState$socialLog6 === void 0 ? void 0 : _modalState$socialLog6.primaryButton) === "externalLogin";
  }, [modalState.socialLoginsConfig]);
  const showPasswordLessInput = react.useMemo(() => isEmailPasswordLessLoginVisible || isSmsPasswordLessLoginVisible, [isEmailPasswordLessLoginVisible, isSmsPasswordLessLoginVisible]);
  const showExternalWalletButton = react.useMemo(() => modalState.hasExternalWallets || !!modalState.externalWalletsConfig[noModal.WALLET_CONNECTORS.METAMASK], [modalState]);
  const showExternalWalletPage = react.useMemo(() => (areSocialLoginsVisible || showPasswordLessInput || !!modalState.externalWalletsConfig[noModal.WALLET_CONNECTORS.METAMASK]) && !modalState.externalWalletsVisibility, [areSocialLoginsVisible, showPasswordLessInput, modalState]);
  const handleExternalWalletBtnClick = flag => {
    setModalState(prevState => {
      return _objectSpread(_objectSpread({}, prevState), {}, {
        externalWalletsVisibility: flag
      });
    });
    if (flag && handleShowExternalWallets) handleShowExternalWallets(modalState.externalWalletsInitialized);
  };
  const onCloseModal = () => {
    setModalState(prevState => _objectSpread(_objectSpread({}, prevState), {}, {
      externalWalletsVisibility: false,
      modalVisibility: false,
      currentPage: constants.PAGES.LOGIN
    }));
    closeModal();
  };
  const onCloseLoader = () => {
    if (modalState.status === interfaces.MODAL_STATUS.CONNECTED) {
      setModalState(_objectSpread(_objectSpread({}, modalState), {}, {
        modalVisibility: false,
        externalWalletsVisibility: false
      }));
    }
    if (modalState.status === interfaces.MODAL_STATUS.ERRORED) {
      setModalState(_objectSpread(_objectSpread({}, modalState), {}, {
        modalVisibility: true,
        status: interfaces.MODAL_STATUS.INITIALIZED
      }));
    }
  };
  const showCloseIcon = react.useMemo(() => {
    return modalState.status === interfaces.MODAL_STATUS.INITIALIZED || modalState.status === interfaces.MODAL_STATUS.CONNECTED || modalState.status === interfaces.MODAL_STATUS.ERRORED;
  }, [modalState.status]);
  react.useEffect(() => {
    // TODO: maybe move this inside root
    if (!modalState.modalVisibility) return;
    if (typeof modalState.externalWalletsConfig === "object") {
      var _modalState$externalW;
      // auto connect to WC if not injected to generate QR code URI for mobile connection
      const wcAvailable = (((_modalState$externalW = modalState.externalWalletsConfig[noModal.WALLET_CONNECTORS.WALLET_CONNECT_V2]) === null || _modalState$externalW === void 0 ? void 0 : _modalState$externalW.showOnModal) || false) !== false;
      if (wcAvailable && !modalState.walletConnectUri && typeof handleExternalWalletClick === "function") {
        handleExternalWalletClick({
          connector: noModal.WALLET_CONNECTORS.WALLET_CONNECT_V2
        });
      }
    }
  }, [modalState, handleExternalWalletClick]);
  if (widgetType === noModal.WIDGET_TYPE.MODAL) {
    return jsxRuntime.jsx(Modal, {
      open: modalState.modalVisibility,
      placement: "center",
      padding: false,
      showCloseIcon: showCloseIcon,
      onClose: onCloseModal,
      borderRadius: uiConfig.borderRadiusType,
      children: modalState.modalVisibility && jsxRuntime.jsx(Root, {
        appLogo: appLogo,
        appName: appName,
        chainNamespaces: chainNamespaces,
        walletRegistry: walletRegistry,
        showPasswordLessInput: showPasswordLessInput,
        showExternalWalletButton: showExternalWalletButton,
        handleSocialLoginClick: params => preHandleSocialWalletClick(params),
        socialLoginsConfig: modalState.socialLoginsConfig,
        areSocialLoginsVisible: areSocialLoginsVisible,
        isEmailPrimary: isEmailPrimary,
        isExternalPrimary: isExternalPrimary,
        showExternalWalletPage: showExternalWalletPage,
        handleExternalWalletBtnClick: handleExternalWalletBtnClick,
        modalState: modalState,
        preHandleExternalWalletClick: preHandleExternalWalletClick,
        setModalState: setModalState,
        onCloseLoader: onCloseLoader,
        isEmailPasswordLessLoginVisible: isEmailPasswordLessLoginVisible,
        isSmsPasswordLessLoginVisible: isSmsPasswordLessLoginVisible,
        uiConfig: uiConfig,
        deviceDetails: deviceDetails
      })
    });
  }
  return jsxRuntime.jsx(Embed, {
    open: modalState.modalVisibility,
    padding: false,
    onClose: onCloseModal,
    borderRadius: uiConfig.borderRadiusType,
    children: modalState.modalVisibility && jsxRuntime.jsx(Root, {
      chainNamespaces: chainNamespaces,
      walletRegistry: walletRegistry,
      appLogo: appLogo,
      appName: appName,
      showPasswordLessInput: showPasswordLessInput,
      showExternalWalletButton: showExternalWalletButton,
      handleSocialLoginClick: params => preHandleSocialWalletClick(params),
      socialLoginsConfig: modalState.socialLoginsConfig,
      areSocialLoginsVisible: areSocialLoginsVisible,
      isEmailPrimary: isEmailPrimary,
      isExternalPrimary: isExternalPrimary,
      showExternalWalletPage: showExternalWalletPage,
      handleExternalWalletBtnClick: handleExternalWalletBtnClick,
      modalState: modalState,
      preHandleExternalWalletClick: preHandleExternalWalletClick,
      setModalState: setModalState,
      onCloseLoader: onCloseLoader,
      isEmailPasswordLessLoginVisible: isEmailPasswordLessLoginVisible,
      isSmsPasswordLessLoginVisible: isSmsPasswordLessLoginVisible,
      uiConfig: uiConfig,
      deviceDetails: deviceDetails
    })
  });
}

module.exports = Widget;
