'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ProviderEnum } from '@dynamic-labs/sdk-api-core';
import { isDynamicWaasConnector } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs-sdk/client/core';
import '../../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import { ReactComponent as SvgCheck } from '../../../../shared/assets/check.js';
import { ReactComponent as SvgClose } from '../../../../shared/assets/close.js';
import { ReactComponent as SvgQuestionMark } from '../../../../shared/assets/question-mark.js';
import '../../../../context/ViewContext/ViewContext.js';
import { ReactComponent as SvgBackupWaas } from '../../../../shared/assets/backup-waas.js';
import { ReactComponent as SvgGoogleDrive } from '../../../../shared/assets/google-drive.js';
import '../../../../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 '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../../store/state/nonce/nonce.js';
import '@dynamic-labs/locale';
import '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../../events/dynamicEvents.js';
import { useUser } from '../../../../client/extension/user/useUser/useUser.js';
import { ErrorContainer } from '../../../../components/ErrorContainer/ErrorContainer.js';
import { Icon } from '../../../../components/Icon/Icon.js';
import { IconButton } from '../../../../components/IconButton/IconButton.js';
import { ModalHeader } from '../../../../components/ModalHeader/ModalHeader.js';
import { Typography } from '../../../../components/Typography/Typography.js';
import { TypographyButton } from '../../../../components/TypographyButton/TypographyButton.js';
import '../../../../context/DynamicContext/DynamicContext.js';
import '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../../context/CaptchaContext/CaptchaContext.js';
import '../../../../context/ErrorContext/ErrorContext.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 '../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../../context/ThemeContext/ThemeContext.js';
import '../../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import { isZeroDevConnector } from '../../../../utils/hooks/useTransactionSimulation/utils/utils.js';
import 'bs58';
import { useSocialAccounts } from '../../../../utils/hooks/useSocialAccounts/useSocialAccounts.js';
import 'yup';
import '../../../../context/MockContext/MockContext.js';
import '../../../../views/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 '../../../../context/WalletContext/WalletContext.js';
import '../../../../components/ShadowDOM/ShadowDOM.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 '../../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../../context/LoadingContext/LoadingContext.js';
import { useWidgetContext } from '../../context/DynamicWidgetContext.js';
import '../../helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../../context/FooterAnimationContext/index.js';
import '@dynamic-labs/types';
import '../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import '../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../../context/PasskeyContext/PasskeyContext.js';
import '../../../../context/OnrampContext/OnrampContext.js';
import { useRefreshUser } from '../../../../utils/hooks/useRefreshUser/useRefreshUser.js';
import '../../../../store/state/sendBalances.js';
import '../../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../components/PasskeyCard/PasskeyCard.js';
import '../CryptoComOnramp/CryptoComOnramp.js';
import '../../../../../index.js';
import '../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 WaasBackupView = () => {
    const { setDynamicWidgetView } = useWidgetContext();
    const user = useUser();
    const { primaryWallet } = useInternalDynamicContext();
    const refresh = useRefreshUser();
    const { linkSocialAccount, isLinked, isProcessingForProvider } = useSocialAccounts();
    const { t } = useTranslation();
    const [errorMessage, setErrorMessage] = useState(null);
    const isGoogleLinked = isLinked(ProviderEnum.Google);
    const checkGoogleDriveBackup = useCallback(() => {
        var _a, _b;
        if (!user || !primaryWallet)
            return false;
        const walletCredential = (_a = user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.find((cred) => cred.walletName === 'dynamicwaas' &&
            cred.address === primaryWallet.address);
        const keyShares = (_b = walletCredential === null || walletCredential === void 0 ? void 0 : walletCredential.walletProperties) === null || _b === void 0 ? void 0 : _b.keyShares;
        if (!keyShares || !Array.isArray(keyShares))
            return false;
        return keyShares.some((keyShare) => keyShare &&
            typeof keyShare === 'object' &&
            'backupLocation' in keyShare &&
            keyShare.backupLocation === 'googleDrive');
    }, [user, primaryWallet]);
    const isBackedUp = useMemo(() => checkGoogleDriveBackup(), [checkGoogleDriveBackup]);
    const handleBackClick = useCallback(() => setDynamicWidgetView('account-and-security-settings'), [setDynamicWidgetView]);
    const handleInfoClick = useCallback(() => {
        setDynamicWidgetView('waas-backup-info');
    }, [setDynamicWidgetView]);
    const handleBackupWalletClick = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        setErrorMessage(null);
        try {
            if (!primaryWallet) {
                throw new Error('No primary wallet found');
            }
            if (!isGoogleLinked) {
                yield linkSocialAccount(ProviderEnum.Google, {
                    forcePopup: true,
                    showWidgetAfterConnection: false,
                });
                yield refresh();
            }
            let waasConnector;
            if (isDynamicWaasConnector(primaryWallet.connector)) {
                waasConnector = primaryWallet.connector;
            }
            else if (isZeroDevConnector(primaryWallet.connector)) {
                const { eoaConnector } = primaryWallet.connector;
                if (!eoaConnector || !isDynamicWaasConnector(eoaConnector)) {
                    throw new Error('ZeroDev connector must have a WaaS EOA connector');
                }
                waasConnector = eoaConnector;
            }
            else {
                throw new Error('Not a supported connector type');
            }
            yield waasConnector.backupKeySharesToGoogleDrive({
                accountAddress: primaryWallet.address,
            });
            yield refresh();
        }
        catch (error) {
            setErrorMessage(t('dyn_waas.backup.error'));
        }
    }), [primaryWallet, refresh, isGoogleLinked, linkSocialAccount, t]);
    const infoButton = (jsx(IconButton, { type: 'button', onClick: handleInfoClick, "data-testid": 'info-button', children: jsx(SvgQuestionMark, {}) }));
    const closeButton = (jsx(IconButton, { type: 'button', onClick: handleBackClick, "data-testid": 'close-button', children: jsx(SvgClose, {}) }));
    return (jsxs("div", { className: 'waas-backup-view', children: [jsx(ModalHeader, { leading: infoButton, trailing: closeButton, children: jsx("div", { className: 'send-balance-page-layout__header-content', children: jsx(Typography, { variant: 'title', color: 'primary', copykey: 'dyn_waas.backup.title', children: t('dyn_waas.backup.title') }) }) }), jsx("div", { className: 'account-wrap', children: jsxs("div", { className: 'settings-view__body', children: [errorMessage && (jsx(ErrorContainer, { variant: 'error', withIcon: false, children: errorMessage })), jsxs("div", { className: 'backup-content', children: [jsx("div", { className: 'backup-icon-container', children: jsx(Icon, { color: 'brand-primary', children: jsx(SvgBackupWaas, { width: 64, height: 64 }) }) }), jsx("div", { className: 'backup-subtitle', children: jsx(Typography, { variant: 'body_normal', color: 'primary', copykey: 'dyn_waas.backup.subtitle', children: t('dyn_waas.backup.subtitle') }) }), jsx("div", { className: 'google-drive-section', children: jsxs("div", { className: 'google-drive-container', children: [jsxs("div", { className: 'google-drive-header', children: [jsx(SvgGoogleDrive, { className: 'google-drive-icon' }), jsxs("div", { className: 'google-drive-text', children: [jsxs("div", { className: 'google-drive-title-row', children: [jsx(Typography, { variant: 'body_normal', color: 'primary', weight: 'bold', copykey: 'dyn_waas.backup.google_drive', children: t('dyn_waas.backup.google_drive') }), isBackedUp && (jsx("div", { className: 'backed-up-pill', children: jsx(Typography, { color: 'inherit', weight: 'bold', copykey: 'dyn_waas.backup.backed_up', children: t('dyn_waas.backup.backed_up') }) }))] }), jsx(Typography, { variant: 'body_small', color: 'secondary', copykey: 'dyn_waas.backup.google_drive_subtitle', children: t('dyn_waas.backup.google_drive_subtitle') })] }), isBackedUp && (jsx(SvgCheck, { className: 'google-drive-check-icon' }))] }), !isBackedUp && (jsx(TypographyButton, { dataTestId: 'backup-wallet-button', onClick: handleBackupWalletClick, buttonClassName: 'backup-button', disabled: isProcessingForProvider(ProviderEnum.Google), typographyProps: {
                                                    color: 'primary',
                                                    weight: 'bold',
                                                }, copykey: 'dyn_waas.backup.back_up', buttonPadding: 'small', children: t('dyn_waas.backup.back_up') }))] }) })] })] }) })] }));
};

export { WaasBackupView };
