import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { LOGIN_PROVIDER } from "@toruslabs/openlogin-utils";
import { ADAPTER_NAMES, log } from "@web3auth/base";
import cloneDeep from "lodash.clonedeep";
import deepmerge from "lodash.merge";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ThemedContext } from "../context/ThemeContext";
import { MODAL_STATUS } from "../interfaces";
import AdapterLoader from "./AdapterLoader";
import ExternalWallets from "./ExternalWallets";
import Footer from "./Footer";
import Header from "./Header";
// import Loader from "./Loader";
import SocialLoginPasswordless from "./SocialLoginPasswordless";
log.enableAll();
// const DETAILED_ADAPTERS = [WALLET_ADAPTERS.PHANTOM, WALLET_ADAPTERS.METAMASK];
export default function Modal(props) {
    var _a, _b, _c, _d;
    const [modalTransitionClasses, setModalTransitionClasses] = useState(["w3a-modal__inner"]);
    const [modalState, setModalState] = useState({
        externalWalletsVisibility: true,
        status: MODAL_STATUS.INITIALIZED,
        hasExternalWallets: true,
        externalWalletsInitialized: false,
        modalVisibility: false,
        modalVisibilityDelayed: false,
        postLoadingMessage: "",
        walletConnectUri: "",
        socialLoginsConfig: {
            loginMethods: {},
            loginMethodsOrder: [],
            adapter: "",
            uiConfig: {},
        },
        externalWalletsConfig: {},
        detailedLoaderAdapter: "",
        detailedLoaderAdapterName: "",
        showExternalWalletsOnly: false,
        wcAdapters: [],
    });
    const { isDark } = useContext(ThemedContext);
    const [t] = useTranslation();
    const { stateListener, appLogo, adapterLogo, appName, handleSocialLoginClick, handleExternalWalletClick, handleShowExternalWallets, closeModal, web3AuthNetwork, } = props;
    useEffect(() => {
        stateListener.emit("MOUNTED");
        stateListener.on("STATE_UPDATED", (newModalState) => {
            log.debug("state updated", newModalState);
            setModalState((prevState) => {
                const mergedState = cloneDeep(deepmerge(prevState, newModalState));
                return mergedState;
            });
        });
    }, [stateListener]);
    useEffect(() => {
        let timeOutId;
        if (modalState.modalVisibility) {
            setModalState((prevState) => {
                return Object.assign(Object.assign({}, prevState), { modalVisibilityDelayed: modalState.modalVisibility });
            });
            document.body.style.overflow = "hidden";
            timeOutId = window.setTimeout(() => {
                setModalTransitionClasses(["w3a-modal__inner", modalState.modalVisibility ? "w3a-modal__inner--active" : ""]);
                // hide external wallets, if modal is closing, so that it will show social login screen on reopen.
            }, 100);
        }
        else {
            document.body.style.overflow = "auto";
            setModalTransitionClasses(["w3a-modal__inner", modalState.modalVisibility ? "w3a-modal__inner--active" : ""]);
            // hide external wallets, if modal is closing, so that it will show social login screen on reopen.
            timeOutId = window.setTimeout(() => {
                setModalState((prevState) => {
                    return Object.assign(Object.assign({}, prevState), { modalVisibilityDelayed: modalState.modalVisibility });
                });
            }, 250);
        }
        return () => {
            clearTimeout(timeOutId);
        };
    }, [modalState.modalVisibility]);
    const onCloseLoader = useCallback(() => {
        if (modalState.status === MODAL_STATUS.CONNECTED) {
            closeModal();
        }
        if (modalState.status === MODAL_STATUS.ERRORED) {
            setModalState((prevState) => {
                return Object.assign(Object.assign({}, prevState), { modalVisibility: true, status: MODAL_STATUS.INITIALIZED });
            });
        }
    }, [closeModal, modalState.status]);
    const preHandleExternalWalletClick = useCallback((params) => {
        const { adapter } = params;
        // if (DETAILED_ADAPTERS.includes(adapter))
        setModalState((prevState) => {
            return Object.assign(Object.assign({}, prevState), { detailedLoaderAdapter: adapter, detailedLoaderAdapterName: ADAPTER_NAMES[adapter] });
        });
        // else if (adapter !== WALLET_ADAPTERS.WALLET_CONNECT_V1)
        //   setModalState((prevState) => {
        //     return { ...prevState, detailedLoaderAdapter: "" };
        //   });
        handleExternalWalletClick(params);
    }, [handleExternalWalletClick]);
    const preHandleSocialWalletClick = (params) => {
        const { loginParams } = params;
        setModalState((prevState) => {
            return Object.assign(Object.assign({}, prevState), { detailedLoaderAdapter: loginParams.loginProvider, detailedLoaderAdapterName: loginParams.name });
        });
        handleSocialLoginClick(params);
    };
    const areSocialLoginsVisible = useMemo(() => {
        var _a, _b;
        if (modalState.showExternalWalletsOnly)
            return false;
        if (Object.keys(((_a = modalState.socialLoginsConfig) === null || _a === void 0 ? void 0 : _a.loginMethods) || {}).length === 0)
            return false;
        const isAnySocialLoginVisible = Object.entries(((_b = modalState.socialLoginsConfig) === null || _b === void 0 ? void 0 : _b.loginMethods) || {}).some(([k, v]) => k !== LOGIN_PROVIDER.EMAIL_PASSWORDLESS && v.showOnModal !== false);
        if (isAnySocialLoginVisible)
            return true;
        return false;
    }, [modalState.showExternalWalletsOnly, (_a = modalState.socialLoginsConfig) === null || _a === void 0 ? void 0 : _a.loginMethods]);
    log.info("modal state", modalState, areSocialLoginsVisible);
    const isEmailPasswordlessLoginVisible = useMemo(() => {
        var _a, _b;
        return (_b = (_a = modalState.socialLoginsConfig) === null || _a === void 0 ? void 0 : _a.loginMethods[LOGIN_PROVIDER.EMAIL_PASSWORDLESS]) === null || _b === void 0 ? void 0 : _b.showOnModal;
    }, [(_b = modalState.socialLoginsConfig) === null || _b === void 0 ? void 0 : _b.loginMethods]);
    const isSmsPasswordlessLoginVisible = useMemo(() => {
        var _a, _b;
        return (_b = (_a = modalState.socialLoginsConfig) === null || _a === void 0 ? void 0 : _a.loginMethods[LOGIN_PROVIDER.SMS_PASSWORDLESS]) === null || _b === void 0 ? void 0 : _b.showOnModal;
    }, [(_c = modalState.socialLoginsConfig) === null || _c === void 0 ? void 0 : _c.loginMethods]);
    // const modalClassName = `w3a-modal ${isDark ? "" : " w3a-modal--light"}`;
    const modalClassName = `w3a-modal ${isDark ? "" : ""}`;
    useEffect(() => {
        setTimeout(() => {
            handleShowExternalWallets(modalState.externalWalletsInitialized);
            setModalState((prevState) => {
                return Object.assign(Object.assign({}, prevState), { externalWalletsVisibility: true });
            });
        }, 2000);
    }, [modalState.externalWalletsInitialized]);
    return (modalState.modalVisibilityDelayed && (_jsxs(_Fragment, { children: [_jsx("div", Object.assign({ id: "w3a-modal", className: modalClassName }, { children: _jsxs("div", Object.assign({ className: modalTransitionClasses.join(" ") }, { children: [_jsx(Header, { onClose: closeModal, appLogo: appLogo, appName: appName }), modalState.status !== MODAL_STATUS.INITIALIZED ? (_jsx("div", Object.assign({ className: "w3a-modal__content w3ajs-content" }, { children: _jsx(AdapterLoader, { onClose: onCloseLoader, appLogo: appLogo, adapterLogo: adapterLogo, modalStatus: modalState.status, message: t(modalState.postLoadingMessage), adapter: modalState.detailedLoaderAdapter, adapterName: modalState.detailedLoaderAdapterName }) }))) : (_jsxs("div", Object.assign({ className: "w3a-modal__content w3ajs-content" }, { children: [(isEmailPasswordlessLoginVisible || isSmsPasswordlessLoginVisible) && (_jsx(SocialLoginPasswordless, { isEmailVisible: isEmailPasswordlessLoginVisible, isSmsVisible: false, adapter: (_d = modalState.socialLoginsConfig) === null || _d === void 0 ? void 0 : _d.adapter, web3AuthNetwork: web3AuthNetwork, handleSocialLoginClick: (params) => preHandleSocialWalletClick(params), isPrimaryBtn: true })), _jsx("div", Object.assign({ className: "w3a-divider" }, { children: "OR" })), _jsx(ExternalWallets, { modalStatus: modalState.status, handleExternalWalletClick: preHandleExternalWalletClick, walletConnectUri: modalState.walletConnectUri, wcAdapters: modalState.wcAdapters, config: modalState.externalWalletsConfig })] }))), _jsx(Footer, {})] })) })), _jsx("div", { className: "w3a-cover" })] })));
}
//# sourceMappingURL=Modal.js.map