'use client'
import { useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { SdkViewType, SdkViewSectionType } from '@dynamic-labs/sdk-api-core';
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 '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../../utils/constants/colors.js';
import '../../../utils/constants/values.js';
import '../../../shared/consts/index.js';
import '../../../events/dynamicEvents.js';
import '../../../../../_virtual/_tslib.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import { isPhoneNumberProviderEnabled } from '../../../utils/functions/isPhoneNumberProviderEnabled/isPhoneNumberProviderEnabled.js';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import { isEmailProviderEnabled } from '../../../utils/functions/isEmailProviderEnabled/isEmailProviderEnabled.js';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import { useProjectSettings } from '../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import { isPasskeyProviderEnabled } from '../../../utils/functions/isPasskeyProviderEnabled/isPasskeyProviderEnabled.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../store/state/authMode/authMode.js';
import '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../../utils/functions/compareChains/compareChains.js';
import '../../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import { useSocialRedirectContext } from '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../CollectUserDataView/useFields.js';
import '../../../context/FieldsStateContext/FieldsStateContext.js';
import '../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../../store/state/walletOptions/walletOptions.js';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.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 '../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import { useWalletList } from '../../../utils/hooks/useWalletList/useWalletList.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 '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import { getLoginViewStructure } from './getLoginViewStructure/getLoginViewStructure.js';
import '../../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 '../../TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { useViewSettings } from '../../../utils/hooks/useViewSettings/useViewSettings.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';

/* eslint-disable multiline-comment-style */
const NUMBER_OF_WALLETS = 3;
const useLoginView = () => {
    const loginView = useViewSettings(SdkViewType.Login);
    const { authorizationViewDisplayOrder, loginWithEmail, walletsFilter } = useInternalDynamicContext();
    const projectSettings = useProjectSettings();
    const { t } = useTranslation();
    const { enabledSocialProviders } = useSocialRedirectContext();
    const { numberOfWallets } = useWalletList({
        viewWalletsFilter: walletsFilter,
    });
    const hasSocialProvidersEnabled = Boolean(enabledSocialProviders === null || enabledSocialProviders === void 0 ? void 0 : enabledSocialProviders.length);
    const hasEmailProviderEnabled = isEmailProviderEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
    const hasPhoneProviderEnabled = isPhoneNumberProviderEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
    const hasPasskeyProviderEnabled = isPasskeyProviderEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
    const isWalletOnly = useMemo(() => {
        var _a;
        if (!projectSettings) {
            return false;
        }
        // When no other methods are enabled we can safely assume it's wallet only
        if (!loginWithEmail &&
            !hasPhoneProviderEnabled &&
            !hasSocialProvidersEnabled) {
            return true;
        }
        // backwards compatibility for those that didn't set up login view sections
        if (!((_a = loginView === null || loginView === void 0 ? void 0 : loginView.sections) === null || _a === void 0 ? void 0 : _a.length)) {
            return (!hasEmailProviderEnabled &&
                !hasPhoneProviderEnabled &&
                !hasSocialProvidersEnabled);
        }
        return (loginView.sections.length === 1 && loginView.sections[0].type === 'wallet');
    }, [
        loginView === null || loginView === void 0 ? void 0 : loginView.sections,
        projectSettings,
        loginWithEmail,
        hasSocialProvidersEnabled,
        hasPhoneProviderEnabled,
        hasEmailProviderEnabled,
    ]);
    /**
     * remove wallet view section from projectSettings?.sdk?.views if no wallet defined
     * @param sections
     * @returns
     */
    const filterLoginViewSections = useCallback((sections) => {
        var _a;
        const hasEnabledNetwork = (chain) => { var _a; return (_a = chain.networks) === null || _a === void 0 ? void 0 : _a.some((network) => network.enabled); };
        const hasEnabledChain = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.chains) === null || _a === void 0 ? void 0 : _a.some((chain) => chain.enabled && hasEnabledNetwork(chain));
        if (projectSettings &&
            !hasEnabledChain &&
            sections.find((section) => section.type === 'wallet')) {
            logger.error('Failed to render WalletSignInSection - no chains enabled');
        }
        if (numberOfWallets > 0) {
            return sections;
        }
        return sections.filter((section) => section.type !== 'wallet');
    }, [numberOfWallets, projectSettings]);
    /**
     * returns the login view sections to be displayed in order from projectSettings?.sdk?.views
     * and has backwards compatibility with project settings design.modal props
     */
    const loginViewSections = useMemo(() => {
        var _a, _b, _c, _d, _e, _f;
        // If client provides the sections explicitly, we use their definitions
        if ((_a = loginView === null || loginView === void 0 ? void 0 : loginView.sections) === null || _a === void 0 ? void 0 : _a.length) {
            return filterLoginViewSections(loginView === null || loginView === void 0 ? void 0 : loginView.sections);
        }
        // If not, we build it using the default structure
        const { splitEmailAndSocial = false, socialAboveEmail = false } = (_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design.modal) !== null && _b !== void 0 ? _b : {};
        const sections = [];
        const sectionRecipes = getLoginViewStructure({
            defaultSocialItem: enabledSocialProviders[0],
            numOfWalletsToDisplay: ((_d = (_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design) === null || _c === void 0 ? void 0 : _c.modal) === null || _d === void 0 ? void 0 : _d.showWalletsButton)
                ? 0
                : NUMBER_OF_WALLETS,
            showEmail: hasEmailProviderEnabled,
            showPasskey: hasPasskeyProviderEnabled,
            showPhone: hasPhoneProviderEnabled,
            showSocial: Boolean(enabledSocialProviders === null || enabledSocialProviders === void 0 ? void 0 : enabledSocialProviders.length),
            // is email only is set in the project settings when the "Email (Web2) only" is toggled on in the dashboard
            showWallets: numberOfWallets > 0 && !((_f = (_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design) === null || _e === void 0 ? void 0 : _e.modal) === null || _f === void 0 ? void 0 : _f.emailOnly),
            socialAboveEmail,
            splitEmailAndSocial,
            web3Layout: authorizationViewDisplayOrder === 'web3',
        });
        const separator = {
            label: t('dyn_login.separators.default'),
            type: SdkViewSectionType.Separator,
        };
        let skipSeparator = false;
        for (const recipe of sectionRecipes) {
            if (!recipe.condition)
                continue;
            // First we add the separator
            if (sections.length > 0 &&
                !skipSeparator &&
                recipe.hideSeparator !== 'above')
                sections.push(separator);
            sections.push(recipe.section);
            skipSeparator = recipe.hideSeparator === 'below';
        }
        return sections;
    }, [
        loginView === null || loginView === void 0 ? void 0 : loginView.sections,
        projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design.modal,
        enabledSocialProviders,
        hasEmailProviderEnabled,
        hasPasskeyProviderEnabled,
        hasPhoneProviderEnabled,
        numberOfWallets,
        authorizationViewDisplayOrder,
        t,
        filterLoginViewSections,
    ]);
    return {
        isWalletOnly,
        loginViewSections,
    };
};

export { NUMBER_OF_WALLETS, useLoginView };
