'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 { PlatformService } from '@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 { ReactComponent as SvgExternalLink } from '../../../../shared/assets/externalLink.js';
import { ReactComponent as SvgUnlink } from '../../../../shared/assets/unlink.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 { useDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import '../../../../context/DynamicContext/DynamicContext.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 '../../../../store/state/authMode/authMode.js';
import '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.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 { useWidgetContext } from '../../context/DynamicWidgetContext.js';
import { IconButton } from '../../../../components/IconButton/IconButton.js';
import { TypographyButton } from '../../../../components/TypographyButton/TypographyButton.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';

const ConnectedAppsView = ({ name }) => {
    var _a;
    const { t } = useTranslation();
    const { setDynamicWidgetView } = useWidgetContext();
    const { primaryWallet } = useDynamicContext();
    const [connectedApps, setConnectedApps] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [showSuccessMessage, setShowSuccessMessage] = useState(false);
    const { globalWallet } = (_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) !== null && _a !== void 0 ? _a : {};
    useEffect(() => {
        const fetchConnectedApps = () => __awaiter(void 0, void 0, void 0, function* () {
            try {
                // poll for 3 seconds for the global wallet to load
                const pollForSessions = () => __awaiter(void 0, void 0, void 0, function* () {
                    const startTime = Date.now();
                    while (Date.now() - startTime < 3000) {
                        try {
                            const sessions = yield globalWallet.getConnectedWCSessions();
                            if (sessions !== undefined) {
                                return sessions;
                            }
                        }
                        catch (error) {
                            // ignore polling error waiting for global wallet to load
                        }
                        yield new Promise((resolve) => setTimeout(resolve, 100));
                    }
                    logger.warn('Timeout waiting for sessions');
                    return undefined;
                });
                const sessions = yield pollForSessions();
                // when a user logs out on dapp side, refresh the connected apps
                globalWallet.getWeb3Wallet().on('session_delete', () => setRefreshing(!refreshing));
                if (sessions) {
                    const apps = Object.values(sessions).map((session) => ({
                        icon: session.peer.metadata.icons[0] || '',
                        name: session.peer.metadata.name,
                        topic: session.topic,
                        url: session.peer.metadata.url,
                    }));
                    setConnectedApps(apps);
                }
            }
            catch (error) {
                logger.warn('Error fetching connected apps', error);
            }
        });
        fetchConnectedApps();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [primaryWallet, refreshing]);
    useEffect(() => {
        if (name) {
            setShowSuccessMessage(true);
            const timer = setTimeout(() => {
                setShowSuccessMessage(false);
            }, 3000);
            return () => clearTimeout(timer);
        }
        else
            return;
    }, [name]);
    const handleDisconnect = (topic) => __awaiter(void 0, void 0, void 0, function* () {
        try {
            yield globalWallet.disconnectWCSession(topic);
            setRefreshing(!refreshing);
        }
        catch (error) {
            logger.warn('Error disconnecting app', error);
        }
    });
    return (jsxs("div", { className: 'connected-apps-view', children: [jsxs("div", { className: 'header', children: [jsx(IconButton, { onClick: () => setDynamicWidgetView('settings'), "data-testid": 'back-button', className: 'back-button', type: 'button', children: jsx(SvgArrowLeft, { className: 'arrow-left-icon' }) }), jsx(Typography, { variant: 'title', color: 'primary', className: 'title', copykey: 'global_wallet.connected_apps.title', children: t('global_wallet.connected_apps.title') })] }), jsx("div", { className: 'subheader', children: jsx(Typography, { variant: 'body_small', weight: 'medium', color: 'primary', className: 'title', copykey: 'global_wallet.connected_apps.subtitle', children: t('global_wallet.connected_apps.subtitle') }) }), connectedApps.length > 0 && (jsx("ul", { className: 'connected-apps-list', children: connectedApps.map((app) => (jsxs("li", { className: 'connected-app-item', children: [jsx("img", { src: app.icon, alt: app.name, className: 'app-icon' }), jsx("div", { className: 'app-info', children: jsx(Typography, { variant: 'body_normal', color: 'primary', children: app.url }) }), jsxs("div", { className: 'app-actions', children: [jsx(TypographyButton, { onClick: () => PlatformService.openURL(app.url, 'blank'), buttonVariant: 'tertiary', buttonPadding: 'none', startSlot: jsx(SvgExternalLink, {}), typographyProps: {
                                        color: 'secondary',
                                        variant: 'button_secondary',
                                    }, dataTestId: 'open-app-button' }), jsx(TypographyButton, { onClick: () => handleDisconnect(app.topic), buttonVariant: 'tertiary', buttonPadding: 'none', startSlot: jsx(SvgUnlink, {}), typographyProps: {
                                        color: 'secondary',
                                        variant: 'button_secondary',
                                    } })] })] }, app.url))) })), showSuccessMessage && (jsxs("div", { className: 'success-message', children: [jsx(SvgCheck, {}), jsx(Typography, { variant: 'body_small', color: 'primary', copykey: 'global_wallet.connected_apps.success', children: t('global_wallet.connected_apps.success', { name }) })] }))] }));
};

export { ConnectedAppsView, ConnectedAppsView as default };
