'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');
var utils = 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');
var externalLink = require('../../../../shared/assets/externalLink.cjs');
var unlink = require('../../../../shared/assets/unlink.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');
var useDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
require('../../../../context/DynamicContext/DynamicContext.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('../../../../store/state/authMode/authMode.cjs');
require('../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.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 DynamicWidgetContext = require('../../context/DynamicWidgetContext.cjs');
var IconButton = require('../../../../components/IconButton/IconButton.cjs');
var TypographyButton = require('../../../../components/TypographyButton/TypographyButton.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');

const ConnectedAppsView = ({ name }) => {
    var _a;
    const { t } = reactI18next.useTranslation();
    const { setDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const { primaryWallet } = useDynamicContext.useDynamicContext();
    const [connectedApps, setConnectedApps] = React.useState([]);
    const [refreshing, setRefreshing] = React.useState(false);
    const [showSuccessMessage, setShowSuccessMessage] = React.useState(false);
    const { globalWallet } = (_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) !== null && _a !== void 0 ? _a : {};
    React.useEffect(() => {
        const fetchConnectedApps = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
            try {
                // poll for 3 seconds for the global wallet to load
                const pollForSessions = () => _tslib.__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.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.logger.warn('Error fetching connected apps', error);
            }
        });
        fetchConnectedApps();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [primaryWallet, refreshing]);
    React.useEffect(() => {
        if (name) {
            setShowSuccessMessage(true);
            const timer = setTimeout(() => {
                setShowSuccessMessage(false);
            }, 3000);
            return () => clearTimeout(timer);
        }
        else
            return;
    }, [name]);
    const handleDisconnect = (topic) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            yield globalWallet.disconnectWCSession(topic);
            setRefreshing(!refreshing);
        }
        catch (error) {
            logger.logger.warn('Error disconnecting app', error);
        }
    });
    return (jsxRuntime.jsxs("div", { className: 'connected-apps-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, { className: 'arrow-left-icon' }) }), jsxRuntime.jsx(Typography.Typography, { variant: 'title', color: 'primary', className: 'title', copykey: 'global_wallet.connected_apps.title', children: t('global_wallet.connected_apps.title') })] }), jsxRuntime.jsx("div", { className: 'subheader', children: jsxRuntime.jsx(Typography.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 && (jsxRuntime.jsx("ul", { className: 'connected-apps-list', children: connectedApps.map((app) => (jsxRuntime.jsxs("li", { className: 'connected-app-item', children: [jsxRuntime.jsx("img", { src: app.icon, alt: app.name, className: 'app-icon' }), jsxRuntime.jsx("div", { className: 'app-info', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', children: app.url }) }), jsxRuntime.jsxs("div", { className: 'app-actions', children: [jsxRuntime.jsx(TypographyButton.TypographyButton, { onClick: () => utils.PlatformService.openURL(app.url, 'blank'), buttonVariant: 'tertiary', buttonPadding: 'none', startSlot: jsxRuntime.jsx(externalLink.ReactComponent, {}), typographyProps: {
                                        color: 'secondary',
                                        variant: 'button_secondary',
                                    }, dataTestId: 'open-app-button' }), jsxRuntime.jsx(TypographyButton.TypographyButton, { onClick: () => handleDisconnect(app.topic), buttonVariant: 'tertiary', buttonPadding: 'none', startSlot: jsxRuntime.jsx(unlink.ReactComponent, {}), typographyProps: {
                                        color: 'secondary',
                                        variant: 'button_secondary',
                                    } })] })] }, app.url))) })), showSuccessMessage && (jsxRuntime.jsxs("div", { className: 'success-message', children: [jsxRuntime.jsx(check.ReactComponent, {}), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: 'primary', copykey: 'global_wallet.connected_apps.success', children: t('global_wallet.connected_apps.success', { name }) })] }))] }));
};

exports.ConnectedAppsView = ConnectedAppsView;
exports["default"] = ConnectedAppsView;
