'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
require('@dynamic-labs/utils');
require('../../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
var arrowLeft = require('../../../../shared/assets/arrow-left.cjs');
var check = require('../../../../shared/assets/check.cjs');
require('@dynamic-labs/iconic');
require('../../../../context/ViewContext/ViewContext.cjs');
require('@dynamic-labs/wallet-connector-core');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../../shared/consts/index.cjs');
require('../../../../components/Alert/Alert.cjs');
require('../../../../events/dynamicEvents.cjs');
require('../../../../context/DynamicContext/DynamicContext.cjs');
require('../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../../../store/state/authMode/authMode.cjs');
require('../../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../../../utils/functions/compareChains/compareChains.cjs');
require('../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../../context/ThemeContext/ThemeContext.cjs');
require('../../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../../context/LoadingContext/LoadingContext.cjs');
require('../../../../context/WalletContext/WalletContext.cjs');
require('../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../../../context/MockContext/MockContext.cjs');
require('../../../../views/CollectUserDataView/useFields.cjs');
require('../../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../../store/state/walletOptions/walletOptions.cjs');
var Typography = require('../../../../components/Typography/Typography.cjs');
require('../../../../context/FooterAnimationContext/index.cjs');
require('../../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('react-focus-lock');
var shortenWalletAddress = require('../../../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.cjs');
var WalletIconWithNetwork = require('../../components/WalletIconWithNetwork/WalletIconWithNetwork.cjs');
var DynamicWidgetContext = require('../../context/DynamicWidgetContext.cjs');
var IconButton = require('../../../../components/IconButton/IconButton.cjs');
var TypographyButton = require('../../../../components/TypographyButton/TypographyButton.cjs');
var useWalletDelegation = require('../../../../utils/hooks/useWalletDelegation/useWalletDelegation.cjs');
require('../../../../components/MenuList/Dropdown/Dropdown.cjs');
require('formik');
require('../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../../store/state/sendBalances.cjs');
require('../../../../components/Input/Input.cjs');
require('../../../../components/OverlayCard/OverlayCard.cjs');
require('../../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../components/PasskeyCard/PasskeyCard.cjs');
require('../CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../context/OnrampContext/OnrampContext.cjs');
require('../../../../../index.cjs');
require('../../helpers/convertExchangeKeyAndProviderEnum.cjs');
require('qrcode');
require('../ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../../store/state/tokenBalances.cjs');
require('../../../../store/state/multichainBalances.cjs');
require('../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
require('../../../../components/InlineWidget/InlineWidget.cjs');
require('../../../../components/IsBrowser/IsBrowser.cjs');
require('../../../../components/Popper/Popper/Popper.cjs');
require('../../../../components/Popper/PopperContext/PopperContext.cjs');

// Exported helper functions for testing
const mapWalletsForRevoke = (wallets) => wallets
    .filter((w) => w.status === 'delegated')
    .map((wallet) => ({
    accountAddress: wallet.address,
    chainName: wallet.chain,
    status: wallet.status,
}));
const mapWalletsForDelegate = (wallets) => wallets.map((wallet) => ({
    accountAddress: wallet.address,
    chainName: wallet.chain,
}));
// Exported handler factory functions for testing
const createHandleRevoke = (revokeDelegation) => (walletWithStatus) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
    try {
        const formattedWallets = mapWalletsForRevoke(walletWithStatus);
        yield revokeDelegation(formattedWallets);
        return true;
    }
    catch (error) {
        logger.logger.warn('Error revoking delegation:', error);
        return false;
    }
});
const createHandleDelegate = (delegateKeyShares) => (walletWithStatus) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
    try {
        const formattedWallets = mapWalletsForDelegate(walletWithStatus);
        yield delegateKeyShares(formattedWallets);
        return true;
    }
    catch (error) {
        logger.logger.warn('Error delegating key shares:', error);
        return false;
    }
});
const createHandleWalletStatusChange = (handleRevoke, handleDelegate) => (wallet) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
    if (wallet.status === 'delegated') {
        yield handleRevoke([wallet]);
    }
    else {
        yield handleDelegate([wallet]);
    }
});
const createHandleRevokeAll = (handleRevoke, walletsWithStatus) => () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
    yield handleRevoke(walletsWithStatus);
});
const WalletsDelegatedSettingsView = ({ name }) => {
    const { t } = reactI18next.useTranslation();
    const { setDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const [showSuccessMessage, setShowSuccessMessage] = React.useState(false);
    const { getWalletsDelegatedStatus } = useWalletDelegation.useWalletDelegation();
    const { revokeDelegation, delegateKeyShares } = useWalletDelegation.useWalletDelegation();
    const walletsWithStatus = getWalletsDelegatedStatus();
    React.useEffect(() => {
        if (!name)
            return;
        setShowSuccessMessage(true);
        const timer = setTimeout(() => {
            setShowSuccessMessage(false);
        }, 3000);
        return () => clearTimeout(timer);
    }, [name]);
    const handleRevoke = createHandleRevoke(revokeDelegation);
    const handleDelegate = createHandleDelegate(delegateKeyShares);
    const handleWalletStatusChange = createHandleWalletStatusChange(handleRevoke, handleDelegate);
    const handleRevokeAll = createHandleRevokeAll(handleRevoke, walletsWithStatus);
    return (jsxRuntime.jsxs("div", { className: 'wallets-delegated-settings-view', children: [jsxRuntime.jsxs("div", { className: 'header', children: [jsxRuntime.jsx(IconButton.IconButton, { onClick: () => setDynamicWidgetView('settings'), "data-testid": 'back-button', className: 'back-button', type: 'button', children: jsxRuntime.jsx(arrowLeft.ReactComponent, {}) }), jsxRuntime.jsx(Typography.Typography, { variant: 'title', color: 'primary', className: 'title', copykey: 'wallets_delegated.title', children: t('wallets_delegated.title') })] }), walletsWithStatus.length > 0 && (jsxRuntime.jsx("ul", { className: 'delegated-wallets-list', children: walletsWithStatus.map((wallet) => {
                    var _a, _b;
                    return (jsxRuntime.jsxs("li", { className: 'delegated-wallets-item', children: [jsxRuntime.jsx("div", { className: 'wallet-icon', children: jsxRuntime.jsx(WalletIconWithNetwork.WalletIconWithNetwork, { walletKey: wallet.key, Icon: null, iconUrl: (_b = (_a = wallet.connector) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.icon, chainName: wallet.chain, iconSize: 24, showNetwork: true }) }), jsxRuntime.jsxs("div", { className: 'wallet-info', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', weight: 'medium', children: shortenWalletAddress.shortenWalletAddress(wallet.address) }), jsxRuntime.jsx("div", { className: wallet.status === 'delegated'
                                            ? 'status-badge'
                                            : 'status-badge status-badge--disconnected', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: wallet.status === 'delegated' ? 'primary' : 'secondary', children: wallet.status === 'delegated'
                                                ? t('connected', 'Connected')
                                                : t('disconnected', 'Disconnected') }) })] }), jsxRuntime.jsx(TypographyButton.TypographyButton, { onClick: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                                    yield handleWalletStatusChange(wallet);
                                }), buttonPadding: 'small', className: 'revoke-button', typographyProps: {
                                    color: 'primary',
                                    variant: 'body_small',
                                    weight: 'medium',
                                }, children: wallet.status === 'delegated'
                                    ? t('revoke', 'Revoke')
                                    : t('delegate', 'Delegate') })] }, wallet.id));
                }) })), walletsWithStatus.filter((w) => w.status === 'delegated').length > 0 && (jsxRuntime.jsx("div", { className: 'revoke-all-section', children: jsxRuntime.jsx(TypographyButton.TypographyButton, { onClick: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                        yield handleRevokeAll();
                    }), buttonVariant: 'tertiary', buttonPadding: 'none', className: 'revoke-all-button', typographyProps: {
                        variant: 'body_normal',
                        weight: 'medium',
                    }, children: t('revoke_all_wallet_access', 'Revoke all wallet access') }) })), showSuccessMessage && (jsxRuntime.jsxs("div", { className: 'success-message', children: [jsxRuntime.jsx(check.ReactComponent, {}), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: 'primary', copykey: 'global_wallet.wallets_delegated.success', children: t('global_wallet.wallets_delegated.success', { name }) })] }))] }));
};

exports.WalletsDelegatedSettingsView = WalletsDelegatedSettingsView;
exports.createHandleDelegate = createHandleDelegate;
exports.createHandleRevoke = createHandleRevoke;
exports.createHandleRevokeAll = createHandleRevokeAll;
exports.createHandleWalletStatusChange = createHandleWalletStatusChange;
exports["default"] = WalletsDelegatedSettingsView;
exports.mapWalletsForDelegate = mapWalletsForDelegate;
exports.mapWalletsForRevoke = mapWalletsForRevoke;
