'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { DynamicError } from '@dynamic-labs/utils';
import { isDynamicWaasConnector } from '@dynamic-labs/wallet-connector-core';
import { Badge } from '../../components/Badge/Badge.js';
import { Checkbox } from '../../components/Checkbox/Checkbox.js';
import { ErrorContainer } from '../../components/ErrorContainer/ErrorContainer.js';
import { IconButton } from '../../components/IconButton/IconButton.js';
import { ModalHeader } from '../../components/ModalHeader/ModalHeader.js';
import { NeedHelpSection } from '../../components/NeedHelpSection/NeedHelpSection.js';
import { Typography } from '../../components/Typography/Typography.js';
import { TypographyButton } from '../../components/TypographyButton/TypographyButton.js';
import '../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useViewContext } from '../../context/ViewContext/ViewContext.js';
import { ReactComponent as SvgArrowLeft } from '../../shared/assets/arrow-left.js';
import { ReactComponent as SvgClose } from '../../shared/assets/close.js';
import { ReactComponent as SvgExportEmbeddedHero } from '../../shared/assets/export-embedded-hero.js';
import { ReactComponent as SvgFilledQuestionMark } from '../../shared/assets/filled-question-mark.js';
import '@dynamic-labs/iconic';
import { logger } from '../../shared/logger.js';
import { useSmartWallets } from '../../utils/hooks/useSmartWallets/useSmartWallets.js';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import '@dynamic-labs/wallet-book';
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-wallet/browser-wallet-client';
import '@dynamic-labs/locale';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import '../../events/dynamicEvents.js';
import { isZeroDevConnector } from '../../utils/hooks/useTransactionSimulation/utils/utils.js';
import 'bs58';

const parseThresholdScheme = (scheme) => {
    if (!scheme)
        return { required: 2, total: 3 };
    const schemeMap = {
        THREE_OF_THREE: { required: 3, total: 3 },
        TWO_OF_THREE: { required: 2, total: 3 },
        TWO_OF_TWO: { required: 2, total: 2 },
    };
    return schemeMap[scheme] || { required: 2, total: 3 };
};
const ExportSharesView = ({ passcode }) => {
    const { t } = useTranslation();
    const { primaryWallet, setShowAuthFlow, user } = useInternalDynamicContext();
    const { getEOAWallet } = useSmartWallets();
    const { goBack, canGoBack } = useViewContext();
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState();
    const [isAcknowledged, setIsAcknowledged] = useState(false);
    const eoaWallet = primaryWallet && getEOAWallet(primaryWallet);
    const wallet = eoaWallet !== null && eoaWallet !== void 0 ? eoaWallet : primaryWallet;
    const walletCredential = useMemo(() => {
        var _a;
        if (!user || !primaryWallet)
            return undefined;
        return (_a = user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.find((cred) => cred.walletName === 'dynamicwaas' &&
            cred.address === primaryWallet.address);
    }, [user, primaryWallet]);
    const thresholdInfo = useMemo(() => {
        var _a;
        const scheme = (_a = walletCredential === null || walletCredential === void 0 ? void 0 : walletCredential.walletProperties) === null || _a === void 0 ? void 0 : _a.thresholdSignatureScheme;
        return parseThresholdScheme(scheme);
    }, [walletCredential]);
    const handleExportShares = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        setError(undefined);
        setIsLoading(true);
        try {
            if (!wallet) {
                throw new DynamicError('No wallet found', 'no_wallet_found');
            }
            if (isDynamicWaasConnector(wallet.connector)) {
                yield wallet.connector.exportClientKeyshares({
                    accountAddress: wallet.address,
                    password: passcode,
                });
                setShowAuthFlow(false);
                return;
            }
            if (isZeroDevConnector(wallet.connector)) {
                const { eoaConnector } = wallet.connector;
                if (eoaConnector && isDynamicWaasConnector(eoaConnector)) {
                    yield eoaConnector.exportClientKeyshares({
                        accountAddress: wallet.address,
                        password: passcode,
                    });
                    setShowAuthFlow(false);
                    return;
                }
            }
            throw new DynamicError('Not a supported connector type for export shares', 'unsupported_connector_for_export');
        }
        catch (err) {
            logger.error('Error exporting shares', { error: err });
            setError(t('dyn_export_shares.error'));
        }
        finally {
            setIsLoading(false);
        }
    }), [wallet, passcode, setShowAuthFlow, t]);
    const bulletPoints = [
        { key: 'dyn_export_shares.bullet_1' },
        {
            key: 'dyn_export_shares.bullet_2',
            values: { required: thresholdInfo.required },
        },
        { key: 'dyn_export_shares.bullet_3' },
    ];
    const backButton = canGoBack && (jsx(IconButton, { onClick: goBack, type: 'button', children: jsx(SvgArrowLeft, {}) }));
    const closeButton = (jsx(IconButton, { onClick: () => {
            setShowAuthFlow(false);
        }, type: 'button', children: jsx(SvgClose, {}) }));
    return (jsxs(Fragment, { children: [jsx(ModalHeader, { leading: backButton, trailing: closeButton, children: jsx(Typography, { as: 'h1', variant: 'title', color: 'primary', "data-testid": 'dynamic-auth-modal-heading', className: 'header__typography', children: t('dyn_export_shares.title') }) }), jsx("div", { className: 'embedded-reveal-view', children: jsxs("div", { className: 'embedded-reveal-view__body', children: [jsx("div", { className: 'embedded-reveal-view__body__description', children: jsx("div", { className: 'embedded-reveal-view__header', children: jsx("div", { className: 'embedded-reveal-view__header__hero', children: jsx(SvgExportEmbeddedHero, {}) }) }) }), jsxs("div", { className: 'embedded-reveal-view__body__description', children: [jsx("div", { className: 'embedded-reveal-view__body__badge-container', children: jsx(Badge, { text: t('dyn_export_shares.sensitive_info'), className: 'embedded-reveal-view__body__badge' }) }), jsx(Typography, { variant: 'body_normal', color: 'primary', weight: 'regular', copykey: 'dyn_export_shares.threshold_description', children: t('dyn_export_shares.threshold_description', {
                                        required: thresholdInfo.required,
                                        total: thresholdInfo.total,
                                    }) })] }), error && jsx(ErrorContainer, { children: error }), jsxs("div", { className: 'embedded-reveal-view__body__card', children: [jsxs("div", { className: 'embedded-reveal-view__body__card__statement', children: [jsx("div", { className: 'embedded-reveal-view__body__card__icon', children: jsx(SvgFilledQuestionMark, { height: 16, width: 16 }) }), jsx("div", { className: 'embedded-reveal-view__body__card__statement__text', children: jsx(Typography, { variant: 'body_small', color: 'primary', weight: 'medium', copykey: 'dyn_export_shares.how_to_use_title', children: t('dyn_export_shares.how_to_use_title') }) })] }), jsx("ul", { className: 'embedded-reveal-view__body__bullet-list', children: bulletPoints.map((bullet) => (jsx("li", { children: jsx(Typography, { variant: 'body_small', color: 'primary', copykey: bullet.key, children: t(bullet.key, bullet.values) }) }, bullet.key))) })] }), jsx("div", { className: 'embedded-reveal-view__body__confirm_card', children: jsxs("button", { className: 'embedded-reveal-view__body__card__acknowledgement', onClick: () => setIsAcknowledged(!isAcknowledged), children: [jsx("div", { children: jsx(Checkbox, { checked: isAcknowledged, onChange: () => setIsAcknowledged(!isAcknowledged), className: 'embedded-reveal-view__body__card__statement__checkbox', id: 'export-shares-checkbox' }) }), jsx("div", { children: jsx(Typography, { variant: 'body_small', color: 'primary', style: { letterSpacing: '-0.15px' }, copykey: 'dyn_export_shares.acknowledge', children: t('dyn_export_shares.acknowledge') }) })] }) }), jsx(NeedHelpSection, { isExport: true }), jsx("div", { className: 'embedded-reveal-view__body__button_section', children: jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                                    color: 'inherit',
                                }, onClick: handleExportShares, disabled: !isAcknowledged, loading: isLoading, dataTestId: 'export-shares-submit-button', copykey: 'dyn_export_shares.download_button', style: { width: '100%' }, className: 'embedded-reveal-view__body__button', expanded: true, children: t('dyn_export_shares.download_button') }) })] }) })] }));
};

export { ExportSharesView };
