'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useRef, useEffect } from 'react';
import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../constants/colors.js';
import { VerifiedCredentialNameToChainEnum } from '../../constants/values.js';
import { hasPendingMfaAction } from '../../../shared/utils/functions/hasPendingMfaAction/hasPendingMfaAction.js';
import '../../../shared/consts/index.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '../../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../store/state/authMode/authMode.js';
import { useVerification } from '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import { useUserAuth } from '../useUserAuth/useUserAuth.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../../views/CollectUserDataView/useFields.js';
import { useUserUpdateRequestInternal } from '../useUserUpdateRequest/useUserUpdateRequest.js';
import '../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '../../../context/FieldsStateContext/FieldsStateContext.js';
import '@dynamic-labs/rpc-providers';
import '../../../store/state/walletOptions/walletOptions.js';
import 'react-i18next';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.js';
import '../../../context/WalletContext/WalletContext.js';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/IconButton/IconButton.js';
import '../../../components/InlineWidget/InlineWidget.js';
import '../../../components/Input/Input.js';
import '../../../components/IsBrowser/IsBrowser.js';
import '../../../components/MenuList/Dropdown/Dropdown.js';
import '../../../components/OverlayCard/OverlayCard.js';
import '../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../components/Popper/Popper/Popper.js';
import '../../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../context/OnrampContext/OnrampContext.js';
import '../../../store/state/sendBalances.js';
import '../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const useSyncOnboardingFlow = ({ handler: headlessHandler, } = {}) => {
    const { setShowAuthFlow, userWithMissingInfo, sdkHasLoaded, setSelectedWalletConnectorKey, } = useInternalDynamicContext();
    const { pushView } = useViewContext();
    const { updateUser } = useUserUpdateRequestInternal({
        validationSchemaStripUnknown: false,
    });
    const { completeAuth, handleAuthError } = useUserAuth({});
    const { displayedDestination: formattedPhone } = useVerification();
    const triggeredOnboarding = useRef(false);
    useInternalDynamicEvents('logout', () => {
        triggeredOnboarding.current = false;
    });
    // this is used to trigger onboarding flow
    // either by headless or dynamic widget
    // it will be triggered when user has missing fields
    // either on login or refreshing the page
    useEffect(() => {
        var _a;
        const handleHeadlessOnboarding = () => __awaiter(void 0, void 0, void 0, function* () {
            var _b;
            if (!headlessHandler || !((_b = userWithMissingInfo === null || userWithMissingInfo === void 0 ? void 0 : userWithMissingInfo.missingFields) === null || _b === void 0 ? void 0 : _b.length)) {
                return;
            }
            triggeredOnboarding.current = true;
            try {
                const missingFieldsRequestInput = userWithMissingInfo.missingFields.map((field) => ({
                    isCustom: field.type === 'custom',
                    key: field.name,
                    label: field.label,
                    required: field.required,
                }));
                const onboardingResponse = yield headlessHandler(missingFieldsRequestInput);
                const userFields = {};
                const customFields = Object.assign({}, userWithMissingInfo === null || userWithMissingInfo === void 0 ? void 0 : userWithMissingInfo.metadata);
                onboardingResponse.forEach((field) => {
                    if (field.isCustom) {
                        customFields[field.key] = field.value;
                    }
                    else {
                        userFields[field.key] = field.value;
                    }
                });
                yield completeAuth({
                    updateJwtFunction: () => __awaiter(void 0, void 0, void 0, function* () { return updateUser(Object.assign(Object.assign({}, userFields), { metadata: customFields })); }),
                });
            }
            catch (error) {
                logger.error('Error handling user onboarding', error);
                handleAuthError(error, {});
            }
        });
        const handleOnboarding = () => __awaiter(void 0, void 0, void 0, function* () {
            triggeredOnboarding.current = true;
            setShowAuthFlow(true);
            const lastVerifiedCredential = userWithMissingInfo === null || userWithMissingInfo === void 0 ? void 0 : userWithMissingInfo.verifiedCredentials.find((vc) => vc.id === (userWithMissingInfo === null || userWithMissingInfo === void 0 ? void 0 : userWithMissingInfo.lastVerifiedCredentialId));
            if (lastVerifiedCredential === null || lastVerifiedCredential === void 0 ? void 0 : lastVerifiedCredential.walletName) {
                setSelectedWalletConnectorKey({
                    chain: (lastVerifiedCredential === null || lastVerifiedCredential === void 0 ? void 0 : lastVerifiedCredential.chain)
                        ? VerifiedCredentialNameToChainEnum[lastVerifiedCredential.chain]
                        : undefined,
                    key: lastVerifiedCredential === null || lastVerifiedCredential === void 0 ? void 0 : lastVerifiedCredential.walletName,
                });
            }
            switch (lastVerifiedCredential === null || lastVerifiedCredential === void 0 ? void 0 : lastVerifiedCredential.format) {
                case JwtVerifiedCredentialFormatEnum.Email:
                case JwtVerifiedCredentialFormatEnum.Oauth:
                    pushView('collect-user-data-login-no-wallet', {
                        userIdentification: 'email',
                    });
                    break;
                case JwtVerifiedCredentialFormatEnum.PhoneNumber:
                    pushView('collect-user-data-login-no-wallet', {
                        userIdentification: 'phoneNumber',
                        userIdentificationOverride: formattedPhone,
                    });
                    break;
                default:
                    pushView('collect-user-data');
            }
        });
        if (!sdkHasLoaded ||
            triggeredOnboarding.current ||
            !((_a = userWithMissingInfo === null || userWithMissingInfo === void 0 ? void 0 : userWithMissingInfo.missingFields) === null || _a === void 0 ? void 0 : _a.length) ||
            hasPendingMfaAction(userWithMissingInfo)) {
            return;
        }
        if (headlessHandler) {
            handleHeadlessOnboarding();
            return;
        }
        handleOnboarding();
        return;
    }, [
        sdkHasLoaded,
        userWithMissingInfo,
        headlessHandler,
        completeAuth,
        updateUser,
        setShowAuthFlow,
        pushView,
        formattedPhone,
        handleAuthError,
        setSelectedWalletConnectorKey,
    ]);
};

export { useSyncOnboardingFlow };
