'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { isMobile } from '@dynamic-labs/utils';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import { ReactComponent as SvgArrowLeft } from '../../../../shared/assets/arrow-left.js';
import { ReactComponent as SvgBlueWalletconnect } from '../../../../shared/assets/blue-walletconnect.js';
import { ReactComponent as SvgCopy } from '../../../../shared/assets/copy.js';
import { ReactComponent as SvgQuestionMark } from '../../../../shared/assets/question-mark.js';
import { useViewContext } from '../../../../context/ViewContext/ViewContext.js';
import '../../../../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 { IconButton } from '../../../../components/IconButton/IconButton.js';
import { useWidgetContext } from '../../context/DynamicWidgetContext.js';
import '../../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../../components/Alert/Alert.js';
import '../../../../events/dynamicEvents.js';
import { useDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.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 { isMaliciousUrl } from '../../../../data/api/transactions/blockaid.js';
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 { Divider } from '../../../../components/Divider/Divider.js';
import '../../../../components/MenuList/Dropdown/Dropdown.js';
import 'formik';
import '../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../../../store/state/sendBalances.js';
import { Input } from '../../../../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 { GlobalWalletScanner } from './scanner/GlobalWalletScanner.js';
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 GlobalWalletView = () => {
    var _a;
    const { t } = useTranslation();
    const { setDynamicWidgetView, goToInitialDynamicWidgetView } = useWidgetContext();
    const { pushView } = useViewContext();
    const { setShowAuthFlow } = useInternalDynamicContext();
    const { primaryWallet } = useDynamicContext();
    const [walletConnectUri, setWalletConnectUri] = useState('');
    const { environmentId } = useInternalDynamicContext();
    const [bannerMessage, setBannerMessage] = useState(null);
    const [isScanned, setIsScanned] = 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 = 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: () => __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 = () => __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 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 = useCallback(() => __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 = useCallback((result) => {
        if (result) {
            setIsScanned(true);
            setWalletConnectUri(result);
        }
    }, []);
    useEffect(() => {
        if (walletConnectUri.startsWith('wc:')) {
            handlePairing();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [walletConnectUri]);
    const renderHeader = () => (jsxs("div", { className: 'header', children: [jsx(IconButton, { type: 'button', onClick: goToInitialDynamicWidgetView, "data-testid": 'back-button', children: jsx(SvgArrowLeft, {}) }), jsx(Typography, { variant: 'title', color: 'primary', as: 'h1', copykey: 'global_wallet.connect_to_apps', children: t('global_wallet.connect_to_apps') }), isMobile() && (jsx(IconButton, { type: 'button', onClick: () => {
                    pushView('global-wallet-info');
                    setShowAuthFlow(true, {
                        ignoreIfIsEmbeddedWidget: false,
                        performMultiWalletChecks: false,
                    });
                }, "data-testid": 'info-button', children: jsx(SvgQuestionMark, {}) }))] }));
    const renderScanner = () => isMobile() && (jsxs(Fragment, { children: [jsxs("div", { className: 'scanner-wrapper', children: [jsx(GlobalWalletScanner, { onScan: handleScan, jsQR: globalWallet.qrScanner }), jsxs("div", { className: 'scanner-overlay', children: [jsxs("div", { className: 'scanner-frame', children: [jsx("div", { className: 'corner top-left' }), jsx("div", { className: 'corner top-right' }), jsx("div", { className: 'corner bottom-left' }), jsx("div", { className: 'corner bottom-right' })] }), jsxs("div", { className: 'scanner-overlay-content', children: [jsx(SvgBlueWalletconnect, { className: 'scanner-icon' }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'white', copykey: 'global_wallet.scan_qr_code', children: t('global_wallet.scan_qr_code') })] })] })] }), jsx(Divider, { text: t('global_wallet.or') })] }));
    const renderInput = () => (jsxs("div", { className: 'wallet-connect-card', children: [jsx("div", { className: 'input-group', children: jsx(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 && (jsx("div", { className: `banner ${bannerMessage.type}`, children: jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'primary', copykey: 'global_wallet.banner.message', children: bannerMessage.message }) }))] }));
    const renderInfoCard = () => !isMobile() && (jsx("div", { className: 'info-card', children: jsxs("div", { className: 'wrapper', children: [jsx(Typography, { variant: 'body_small', weight: 'bold', color: 'primary', as: 'h2', copykey: 'global_wallet.help.title', children: t('global_wallet.help.title') }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.1', children: t('global_wallet.help.step.1') }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.2', children: t('global_wallet.help.step.2') }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.3', children: jsxs("span", { className: 'inline-logo-text', children: ["3. Open WalletConnect", jsx(SvgBlueWalletconnect, { className: 'inline-logo' }), " from the list"] }) }), jsx(Typography, { variant: 'body_small', weight: 'regular', color: 'secondary', copykey: 'global_wallet.help.step.4', children: jsxs("span", { className: 'inline-logo-text', children: ["4. Locate and click ", jsx(SvgCopy, { className: 'inline-logo' }), " to copy the URI code"] }) })] }) }));
    return (jsxs("div", { className: 'connect-dapps-view', children: [renderHeader(), renderScanner(), renderInput(), renderInfoCard()] }));
};

export { GlobalWalletView, GlobalWalletView as default };
