'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import '@dynamic-labs/utils';
import '../../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import { ReactComponent as SvgArrowLeft } from '../../../../shared/assets/arrow-left.js';
import { ReactComponent as SvgCheck } from '../../../../shared/assets/check.js';
import '@dynamic-labs/iconic';
import '../../../../context/ViewContext/ViewContext.js';
import '@dynamic-labs/wallet-connector-core';
import { logger } from '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../../shared/consts/index.js';
import '../../../../components/Alert/Alert.js';
import '../../../../events/dynamicEvents.js';
import '../../../../context/DynamicContext/DynamicContext.js';
import '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../../store/state/authMode/authMode.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 '@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 '../../../../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 'bs58';
import '@dynamic-labs/types';
import '../../../../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 '../../../../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 { Typography } from '../../../../components/Typography/Typography.js';
import '../../../../context/FooterAnimationContext/index.js';
import '../../../../components/ShadowDOM/ShadowDOM.js';
import '../../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import { shortenWalletAddress } from '../../../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.js';
import { WalletIconWithNetwork } from '../../components/WalletIconWithNetwork/WalletIconWithNetwork.js';
import { useWidgetContext } from '../../context/DynamicWidgetContext.js';
import { IconButton } from '../../../../components/IconButton/IconButton.js';
import { TypographyButton } from '../../../../components/TypographyButton/TypographyButton.js';
import { useWalletDelegation } from '../../../../utils/hooks/useWalletDelegation/useWalletDelegation.js';
import '../../../../components/MenuList/Dropdown/Dropdown.js';
import 'formik';
import '../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../../../store/state/sendBalances.js';
import '../../../../components/Input/Input.js';
import '../../../../components/OverlayCard/OverlayCard.js';
import '../../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../../context/PasskeyContext/PasskeyContext.js';
import '../../components/PasskeyCard/PasskeyCard.js';
import '../CryptoComOnramp/CryptoComOnramp.js';
import '../../../../context/OnrampContext/OnrampContext.js';
import '../../../../../index.js';
import '../../helpers/convertExchangeKeyAndProviderEnum.js';
import 'qrcode';
import '../ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../../store/state/tokenBalances.js';
import '../../../../store/state/multichainBalances.js';
import '../../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import '../../../../components/InlineWidget/InlineWidget.js';
import '../../../../components/IsBrowser/IsBrowser.js';
import '../../../../components/Popper/Popper/Popper.js';
import '../../../../components/Popper/PopperContext/PopperContext.js';

// 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) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const formattedWallets = mapWalletsForRevoke(walletWithStatus);
        yield revokeDelegation(formattedWallets);
        return true;
    }
    catch (error) {
        logger.warn('Error revoking delegation:', error);
        return false;
    }
});
const createHandleDelegate = (delegateKeyShares) => (walletWithStatus) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const formattedWallets = mapWalletsForDelegate(walletWithStatus);
        yield delegateKeyShares(formattedWallets);
        return true;
    }
    catch (error) {
        logger.warn('Error delegating key shares:', error);
        return false;
    }
});
const createHandleWalletStatusChange = (handleRevoke, handleDelegate) => (wallet) => __awaiter(void 0, void 0, void 0, function* () {
    if (wallet.status === 'delegated') {
        yield handleRevoke([wallet]);
    }
    else {
        yield handleDelegate([wallet]);
    }
});
const createHandleRevokeAll = (handleRevoke, walletsWithStatus) => () => __awaiter(void 0, void 0, void 0, function* () {
    yield handleRevoke(walletsWithStatus);
});
const WalletsDelegatedSettingsView = ({ name }) => {
    const { t } = useTranslation();
    const { setDynamicWidgetView } = useWidgetContext();
    const [showSuccessMessage, setShowSuccessMessage] = useState(false);
    const { getWalletsDelegatedStatus } = useWalletDelegation();
    const { revokeDelegation, delegateKeyShares } = useWalletDelegation();
    const walletsWithStatus = getWalletsDelegatedStatus();
    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 (jsxs("div", { className: 'wallets-delegated-settings-view', children: [jsxs("div", { className: 'header', children: [jsx(IconButton, { onClick: () => setDynamicWidgetView('settings'), "data-testid": 'back-button', className: 'back-button', type: 'button', children: jsx(SvgArrowLeft, {}) }), jsx(Typography, { variant: 'title', color: 'primary', className: 'title', copykey: 'wallets_delegated.title', children: t('wallets_delegated.title') })] }), walletsWithStatus.length > 0 && (jsx("ul", { className: 'delegated-wallets-list', children: walletsWithStatus.map((wallet) => {
                    var _a, _b;
                    return (jsxs("li", { className: 'delegated-wallets-item', children: [jsx("div", { className: 'wallet-icon', children: jsx(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 }) }), jsxs("div", { className: 'wallet-info', children: [jsx(Typography, { variant: 'body_normal', color: 'primary', weight: 'medium', children: shortenWalletAddress(wallet.address) }), jsx("div", { className: wallet.status === 'delegated'
                                            ? 'status-badge'
                                            : 'status-badge status-badge--disconnected', children: jsx(Typography, { variant: 'body_small', color: wallet.status === 'delegated' ? 'primary' : 'secondary', children: wallet.status === 'delegated'
                                                ? t('connected', 'Connected')
                                                : t('disconnected', 'Disconnected') }) })] }), jsx(TypographyButton, { onClick: () => __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 && (jsx("div", { className: 'revoke-all-section', children: jsx(TypographyButton, { onClick: () => __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 && (jsxs("div", { className: 'success-message', children: [jsx(SvgCheck, {}), jsx(Typography, { variant: 'body_small', color: 'primary', copykey: 'global_wallet.wallets_delegated.success', children: t('global_wallet.wallets_delegated.success', { name }) })] }))] }));
};

export { WalletsDelegatedSettingsView, createHandleDelegate, createHandleRevoke, createHandleRevokeAll, createHandleWalletStatusChange, WalletsDelegatedSettingsView as default, mapWalletsForDelegate, mapWalletsForRevoke };
