import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import { BUILD_ENV, WEB3AUTH_NETWORK, AUTH_CONNECTION } from '@web3auth/auth';
import { WIDGET_TYPE, log, cloneDeep, WALLET_CONNECTORS, CONNECTOR_NAMES } from '@web3auth/no-modal';
import deepmerge from 'deepmerge';
import { useMemo, useState, useEffect } from 'react';
import { PAGES } from '../../constants.js';
import { MODAL_STATUS } from '../../interfaces.js';
import Embed from '../Embed/Embed.js';
import Modal from '../Modal/Modal.js';
import Root from '../Root/Root.js';
import { jsx } from 'react/jsx-runtime';

function Widget(props) {
  const {
    stateListener,
    handleSocialLoginClick,
    handleExternalWalletClick,
    handleShowExternalWallets,
    closeModal,
    appLogo,
    appName,
    chainNamespaces,
    walletRegistry,
    uiConfig,
    deviceDetails
  } = props;
  const {
    widgetType
  } = uiConfig;
  const visible = useMemo(() => widgetType === WIDGET_TYPE.EMBED, [widgetType]);
  const [modalState, setModalState] = useState({
    externalWalletsVisibility: false,
    status: MODAL_STATUS.INITIALIZED,
    hasExternalWallets: false,
    externalWalletsInitialized: false,
    modalVisibility: false,
    modalVisibilityDelayed: false,
    postLoadingMessage: "",
    walletConnectUri: "",
    metamaskConnectUri: "",
    socialLoginsConfig: {
      loginMethods: {},
      loginMethodsOrder: [],
      connector: "",
      uiConfig: {}
    },
    externalWalletsConfig: {},
    showExternalWalletsOnly: false,
    currentPage: PAGES.LOGIN,
    detailedLoaderConnector: "",
    detailedLoaderConnectorName: "",
    web3authClientId: "",
    web3authNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
    authBuildEnv: BUILD_ENV.PRODUCTION
  });
  useEffect(() => {
    setModalState(prev => _objectSpread(_objectSpread({}, prev), {}, {
      modalVisibility: visible
    }));
  }, [visible]);
  useEffect(() => {
    stateListener.on("STATE_UPDATED", newModalState => {
      log.debug("state updated", newModalState);
      setModalState(prevState => {
        const mergedState = 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: 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 = 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_CONNECTION.EMAIL_PASSWORDLESS, AUTH_CONNECTION.SMS_PASSWORDLESS].includes(k) && v.showOnModal !== false);
    return isAnySocialLoginVisible;
  }, [modalState]);

  // Memo for checking if email passwordless login is visible
  const isEmailPasswordLessLoginVisible = useMemo(() => {
    var _modalState$socialLog3;
    return (_modalState$socialLog3 = modalState.socialLoginsConfig) === null || _modalState$socialLog3 === void 0 || (_modalState$socialLog3 = _modalState$socialLog3.loginMethods[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 = useMemo(() => {
    var _modalState$socialLog4;
    return (_modalState$socialLog4 = modalState.socialLoginsConfig) === null || _modalState$socialLog4 === void 0 || (_modalState$socialLog4 = _modalState$socialLog4.loginMethods[AUTH_CONNECTION.SMS_PASSWORDLESS]) === null || _modalState$socialLog4 === void 0 ? void 0 : _modalState$socialLog4.showOnModal;
  }, [modalState.socialLoginsConfig]);
  const isEmailPrimary = 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 = 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 = useMemo(() => isEmailPasswordLessLoginVisible || isSmsPasswordLessLoginVisible, [isEmailPasswordLessLoginVisible, isSmsPasswordLessLoginVisible]);
  const showExternalWalletButton = useMemo(() => modalState.hasExternalWallets || !!modalState.externalWalletsConfig[WALLET_CONNECTORS.METAMASK], [modalState]);
  const showExternalWalletPage = useMemo(() => (areSocialLoginsVisible || showPasswordLessInput || !!modalState.externalWalletsConfig[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: PAGES.LOGIN
    }));
    closeModal();
  };
  const onCloseLoader = () => {
    if (modalState.status === MODAL_STATUS.CONNECTED) {
      setModalState(_objectSpread(_objectSpread({}, modalState), {}, {
        modalVisibility: false,
        externalWalletsVisibility: false
      }));
    }
    if (modalState.status === MODAL_STATUS.ERRORED) {
      setModalState(_objectSpread(_objectSpread({}, modalState), {}, {
        modalVisibility: true,
        status: MODAL_STATUS.INITIALIZED
      }));
    }
  };
  const showCloseIcon = useMemo(() => {
    return modalState.status === MODAL_STATUS.INITIALIZED || modalState.status === MODAL_STATUS.CONNECTED || modalState.status === MODAL_STATUS.ERRORED;
  }, [modalState.status]);
  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[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: WALLET_CONNECTORS.WALLET_CONNECT_V2
        });
      }
    }
  }, [modalState, handleExternalWalletClick]);
  if (widgetType === WIDGET_TYPE.MODAL) {
    return /*#__PURE__*/jsx(Modal, {
      open: modalState.modalVisibility,
      placement: "center",
      padding: false,
      showCloseIcon: showCloseIcon,
      onClose: onCloseModal,
      borderRadius: uiConfig.borderRadiusType,
      children: modalState.modalVisibility && /*#__PURE__*/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 /*#__PURE__*/jsx(Embed, {
    open: modalState.modalVisibility,
    padding: false,
    onClose: onCloseModal,
    borderRadius: uiConfig.borderRadiusType,
    children: modalState.modalVisibility && /*#__PURE__*/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
    })
  });
}

export { Widget as default };
