'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('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
var arrowLeft = require('../../../../shared/assets/arrow-left.cjs');
var blueWalletconnect = require('../../../../shared/assets/blue-walletconnect.cjs');
var copy = require('../../../../shared/assets/copy.cjs');
var questionMark = require('../../../../shared/assets/question-mark.cjs');
var ViewContext = require('../../../../context/ViewContext/ViewContext.cjs');
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');
var IconButton = require('../../../../components/IconButton/IconButton.cjs');
var DynamicWidgetContext = require('../../context/DynamicWidgetContext.cjs');
require('../../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../../components/Alert/Alert.cjs');
require('../../../../events/dynamicEvents.cjs');
var useDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.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');
var blockaid = require('../../../../data/api/transactions/blockaid.cjs');
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 Divider = require('../../../../components/Divider/Divider.cjs');
require('../../../../components/MenuList/Dropdown/Dropdown.cjs');
require('formik');
require('../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../../store/state/sendBalances.cjs');
var Input = 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');
var GlobalWalletScanner = require('./scanner/GlobalWalletScanner.cjs');
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 GlobalWalletView = () => {
    var _a;
    const { t } = reactI18next.useTranslation();
    const { setDynamicWidgetView, goToInitialDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const { pushView } = ViewContext.useViewContext();
    const { setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { primaryWallet } = useDynamicContext.useDynamicContext();
    const [walletConnectUri, setWalletConnectUri] = React.useState('');
    const { environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const [bannerMessage, setBannerMessage] = React.useState(null);
    const [isScanned, setIsScanned] = React.useState(false);
    const { globalWallet } = 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) !== null && _a !== void 0 ? _a : {};
    if (!globalWallet)
        throw new Error('Global Wallet not found');
    const showBanner = React.useCallback((message, type) => {
        setBannerMessage({ message, type });
        const timeout = type === 'success' ? 0 : 3000;
        setTimeout(() => {
            setBannerMessage(null);
        }, timeout);
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []);
    const handleConfirmView = (pairingInfo) => {
        pushView('global-wallet-confirm', {
            onCancel: () => {
                setDynamicWidgetView('global-wallet');
                setShowAuthFlow(false, {
                    ignoreIfIsEmbeddedWidget: false,
                    performMultiWalletChecks: false,
                });
                setWalletConnectUri('');
            },
            onConfirm: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                var _a;
                try {
                    yield globalWallet.confirmPairing(true);
                    setDynamicWidgetView('global-wallet');
                    setShowAuthFlow(false, {
                        ignoreIfIsEmbeddedWidget: false,
                        performMultiWalletChecks: false,
                    });
                    setDynamicWidgetView('connected-apps', { name: pairingInfo.name });
                }
                catch (error) {
                    showBanner(t('global_wallet.banner.warning', {
                        name: (_a = pairingInfo.name) !== null && _a !== void 0 ? _a : t('global_wallet.the_dapp'),
                    }), 'error');
                }
            }),
            pairingInfo,
        });
        setShowAuthFlow(true, {
            ignoreIfIsEmbeddedWidget: false,
            performMultiWalletChecks: false,
        });
    };
    const popupConfirmView = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const pendingPairing = globalWallet.getPendingPairing();
        if (!pendingPairing)
            throw new Error('No pending pairing');
        const { name, url, icons } = pendingPairing.params.proposer.metadata;
        const pairingInfo = { icons, name, url };
        const isDefinitelyMalicious = yield blockaid.isMaliciousUrl({ environmentId, url });
        if (isDefinitelyMalicious ||
            isDefinitelyMalicious === undefined ||
            isDefinitelyMalicious === null) {
            pushView('global-wallet-malicious', {
                maliciousSiteInfo: {
                    isDefinitelyMalicious: isDefinitelyMalicious !== null && isDefinitelyMalicious !== void 0 ? isDefinitelyMalicious : false,
                    proceedFlow: () => handleConfirmView(pairingInfo),
                    url,
                },
            });
            setShowAuthFlow(true, {
                ignoreIfIsEmbeddedWidget: false,
                performMultiWalletChecks: false,
            });
        }
        else {
            handleConfirmView(pairingInfo);
        }
    });
    const handlePairing = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!walletConnectUri.startsWith('wc:')) {
            showBanner(t('global_wallet.banner.bad_input'), 'error');
            return;
        }
        try {
            yield globalWallet.pairWithWC(walletConnectUri);
            globalWallet.getWeb3Wallet().on('session_proposal', popupConfirmView);
        }
        catch (error) {
            const errorMessage = String(error);
            if (errorMessage.includes('expired')) {
                showBanner(t('global_wallet.banner.expired'), 'error');
            }
            else if (errorMessage.includes('exists')) {
                showBanner(t('global_wallet.banner.already_connected', {
                    name: t('global_wallet.this_app'),
                }), 'success');
            }
            else {
                showBanner(t('global_wallet.banner.warning', {
                    name: t('global_wallet.the_dapp'),
                }), 'error');
            }
        }
    }), // eslint-disable-next-line react-hooks/exhaustive-deps
    [walletConnectUri]);
    const handleScan = React.useCallback((result) => {
        if (result) {
            setIsScanned(true);
            setWalletConnectUri(result);
        }
    }, []);
    React.useEffect(() => {
        if (walletConnectUri.startsWith('wc:')) {
            handlePairing();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [walletConnectUri]);
    const renderHeader = () => (jsxRuntime.jsxs("div", { className: 'header', children: [jsxRuntime.jsx(IconButton.IconButton, { type: 'button', onClick: goToInitialDynamicWidgetView, "data-testid": 'back-button', children: jsxRuntime.jsx(arrowLeft.ReactComponent, {}) }), jsxRuntime.jsx(Typography.Typography, { variant: 'title', color: 'primary', as: 'h1', copykey: 'global_wallet.connect_to_apps', children: t('global_wallet.connect_to_apps') }), utils.isMobile() && (jsxRuntime.jsx(IconButton.IconButton, { type: 'button', onClick: () => {
                    pushView('global-wallet-info');
                    setShowAuthFlow(true, {
                        ignoreIfIsEmbeddedWidget: false,
                        performMultiWalletChecks: false,
                    });
                }, "data-testid": 'info-button', children: jsxRuntime.jsx(questionMark.ReactComponent, {}) }))] }));
    const renderScanner = () => utils.isMobile() && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'scanner-wrapper', children: [jsxRuntime.jsx(GlobalWalletScanner.GlobalWalletScanner, { onScan: handleScan, jsQR: globalWallet.qrScanner }), jsxRuntime.jsxs("div", { className: 'scanner-overlay', children: [jsxRuntime.jsxs("div", { className: 'scanner-frame', children: [jsxRuntime.jsx("div", { className: 'corner top-left' }), jsxRuntime.jsx("div", { className: 'corner top-right' }), jsxRuntime.jsx("div", { className: 'corner bottom-left' }), jsxRuntime.jsx("div", { className: 'corner bottom-right' })] }), jsxRuntime.jsxs("div", { className: 'scanner-overlay-content', children: [jsxRuntime.jsx(blueWalletconnect.ReactComponent, { className: 'scanner-icon' }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'white', copykey: 'global_wallet.scan_qr_code', children: t('global_wallet.scan_qr_code') })] })] })] }), jsxRuntime.jsx(Divider.Divider, { text: t('global_wallet.or') })] }));
    const renderInput = () => (jsxRuntime.jsxs("div", { className: 'wallet-connect-card', children: [jsxRuntime.jsx("div", { className: 'input-group', children: jsxRuntime.jsx(Input.Input, { copykey: 'global_wallet.walletconnect_uri', id: 'walletconnect-uri', label: t('global_wallet.walletconnect_uri'), placeholder: 'wc:...', value: isScanned ? '' : walletConnectUri, onChange: (e) => {
                        setWalletConnectUri(e.target.value);
                        setIsScanned(false);
                    }, variant: 'dense' }) }), bannerMessage && (jsxRuntime.jsx("div", { className: `banner ${bannerMessage.type}`, children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'primary', copykey: 'global_wallet.banner.message', children: bannerMessage.message }) }))] }));
    const renderInfoCard = () => !utils.isMobile() && (jsxRuntime.jsx("div", { className: 'info-card', children: jsxRuntime.jsxs("div", { className: 'wrapper', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'bold', color: 'primary', as: 'h2', copykey: 'global_wallet.help.title', children: t('global_wallet.help.title') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.1', children: t('global_wallet.help.step.1') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.2', children: t('global_wallet.help.step.2') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.3', children: jsxRuntime.jsxs("span", { className: 'inline-logo-text', children: ["3. Open WalletConnect", jsxRuntime.jsx(blueWalletconnect.ReactComponent, { className: 'inline-logo' }), " from the list"] }) }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.4', children: jsxRuntime.jsxs("span", { className: 'inline-logo-text', children: ["4. Locate and click ", jsxRuntime.jsx(copy.ReactComponent, { className: 'inline-logo' }), " to copy the URI code"] }) })] }) }));
    return (jsxRuntime.jsxs("div", { className: 'connect-dapps-view', children: [renderHeader(), renderScanner(), renderInput(), renderInfoCard()] }));
};

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