'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var types = require('@dynamic-labs/types');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var index = require('../../functions/getEnabledOAuthProviders/index.cjs');
var getEnabledSocialSignInProvidersAsProviderEnum = require('../../functions/getEnabledSocialSignInProvidersAsProviderEnum/getEnabledSocialSignInProvidersAsProviderEnum.cjs');
require('../../../store/state/nonce/nonce.cjs');
var isSocialKycEnabled = require('../../functions/isSocialKycEnabled/isSocialKycEnabled.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
var oauth = require('../../../data/api/oauth/oauth.cjs');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
var primaryWalletId = 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('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
var SocialRedirectContext = require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
var useSocialAuth = require('../useSocialAuth/useSocialAuth.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');
require('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../components/IconButton/IconButton.cjs');
require('../../../components/InlineWidget/InlineWidget.cjs');
require('../../../components/Input/Input.cjs');
require('../../../components/IsBrowser/IsBrowser.cjs');
require('../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../components/OverlayCard/OverlayCard.cjs');
require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../components/Popper/Popper/Popper.cjs');
require('../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../context/OnrampContext/OnrampContext.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../index.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../store/state/tokenBalances.cjs');
require('../../../store/state/multichainBalances.cjs');
require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

// Hook exposed to customers and used internally to handle social account linking
const useSocialAccounts = () => {
    var _a;
    const { environmentId, user, projectSettings } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView } = ViewContext.useViewContext();
    const { setSocialProvider } = SocialRedirectContext.useSocialRedirectContext();
    // Provider-specific processing states
    const [processingStates, setProcessingStates] = React.useState(new Map());
    // Helper functions for provider-specific processing state
    const setProcessingForProvider = React.useCallback((provider, isProcessing) => {
        setProcessingStates((prev) => new Map(prev).set(provider, isProcessing));
    }, []);
    const isProcessingForProvider = React.useCallback((provider) => { var _a; return (_a = processingStates.get(provider)) !== null && _a !== void 0 ? _a : false; }, [processingStates]);
    const handleFarcasterUrl = React.useCallback((url) => pushView('farcaster-connect-view', { url }, {
        onBackClick: () => {
            setSocialProvider(undefined);
            dynamicEvents.dynamicEvents.emit('farcasterConnectCancelled');
            dynamicEvents.dynamicEvents.emit('authFailure', {
                option: sdkApiCore.ProviderEnum.Farcaster,
                provider: sdkApiCore.ProviderEnum.Farcaster,
                type: 'social',
            }, 'user-cancelled');
        },
    }), [pushView, setSocialProvider]);
    const { handleError, setError, checkValidProvider, error, connectSocialAccount, } = useSocialAuth.useSocialAuth({
        onFarcasterUrl: handleFarcasterUrl,
    });
    const verifiedOAuthCredentialsMap = React.useMemo(() => {
        var _a, _b;
        const verifiedOAuthCredential = (_b = (_a = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.filter((credential) => credential.format === 'oauth')) !== null && _b !== void 0 ? _b : [];
        const credentialMap = new Map();
        verifiedOAuthCredential.forEach((credential) => {
            var _a, _b;
            const key = (_a = credential.oauthProvider) !== null && _a !== void 0 ? _a : credential.id;
            const existing = (_b = credentialMap.get(key)) !== null && _b !== void 0 ? _b : [];
            credentialMap.set(key, [...existing, credential]);
        });
        return Object.fromEntries(credentialMap);
    }, [user === null || user === void 0 ? void 0 : user.verifiedCredentials]);
    const checkValidOAuthLinking = React.useCallback((provider) => {
        if (!isSocialKycEnabled.isSocialKycEnabled(projectSettings)) {
            handleError(provider, types.SocialOAuthErrorCode.SOCIAL_LINKING_NOT_ENABLED, 'Social linking is not enabled in Information Capture on the dashboard', { raiseAuthFailure: false });
            return false;
        }
        const oauthProviders = index.getEnabledOAuthProviders(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
        const oauthProvider = oauthProviders === null || oauthProviders === void 0 ? void 0 : oauthProviders.find((p) => p.provider === provider);
        if (!oauthProvider) {
            handleError(provider, types.SocialOAuthErrorCode.PROVIDER_NOT_ENABLED, `Social linking provider is not enabled in Information Capture on the dashboard: ${provider}`, { raiseAuthFailure: false });
            return false;
        }
        return true;
    }, [handleError, projectSettings]);
    const linkSocialAccount = React.useCallback((provider_1, ...args_1) => _tslib.__awaiter(void 0, [provider_1, ...args_1], void 0, function* (provider, { forcePopup, redirectUrl, showWidgetAfterConnection, triggerFundFromExchangeOnSuccess, payingWithDynamic, } = {
        forcePopup: false,
        payingWithDynamic: undefined,
        redirectUrl: undefined,
        showWidgetAfterConnection: false,
        triggerFundFromExchangeOnSuccess: undefined,
    }) {
        setProcessingForProvider(provider, true);
        try {
            yield connectSocialAccount({
                authMode: 'link',
                forcePopup,
                payingWithDynamic,
                provider,
                redirectUrl,
                showWidgetAfterConnection,
                triggerFundFromExchangeOnSuccess,
                validator: checkValidOAuthLinking,
            });
        }
        finally {
            setProcessingForProvider(provider, false);
        }
    }), [checkValidOAuthLinking, connectSocialAccount, setProcessingForProvider]);
    const findVerifiedCredentialById = React.useCallback((provider, verifiedCredentialId) => {
        var _a;
        const verifiedCredentials = (_a = verifiedOAuthCredentialsMap[provider]) !== null && _a !== void 0 ? _a : [];
        const verifiedCredential = verifiedCredentialId
            ? verifiedCredentials.find((cred) => cred.id === verifiedCredentialId)
            : verifiedCredentials[0];
        return verifiedCredential;
    }, [verifiedOAuthCredentialsMap]);
    const unlinkSocialAccount = React.useCallback((provider, verifiedCredentialId) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _b;
        setError(undefined);
        setProcessingForProvider(provider, true);
        if (!checkValidProvider(provider, 'unlink')) {
            setProcessingForProvider(provider, false);
            return;
        }
        const verifiedCredential = findVerifiedCredentialById(provider, verifiedCredentialId);
        if (!verifiedCredential) {
            handleError(provider, types.SocialOAuthErrorCode.NO_ACCOUNT_LINKED, `No account linked for provider: ${provider}`, { raiseAuthFailure: false });
            setProcessingForProvider(provider, false);
            return;
        }
        try {
            const primaryWalletId$1 = primaryWalletId.getPrimaryWalletId();
            const response = yield oauth.unlinkOAuth({
                environmentId,
                primaryWalletId: primaryWalletId$1,
                verifiedCredentialId: (_b = verifiedCredential.id) !== null && _b !== void 0 ? _b : '',
            });
            if (!response) {
                handleError(provider, types.SocialOAuthErrorCode.UNLINK_ERROR, `Failed to unlink social account: ${provider} | ${verifiedCredential.id}`, { raiseAuthFailure: false });
                return;
            }
        }
        catch (err) {
            handleError(provider, types.SocialOAuthErrorCode.GENERAL_ERROR, `Failed to unlink social account: ${provider} | ${verifiedCredential.id}`, { raiseAuthFailure: false });
        }
        finally {
            setProcessingForProvider(provider, false);
        }
    }), [
        checkValidProvider,
        environmentId,
        handleError,
        setError,
        setProcessingForProvider,
        findVerifiedCredentialById,
    ]);
    const isLinked = React.useCallback((provider) => { var _a; return Boolean((_a = verifiedOAuthCredentialsMap[provider]) === null || _a === void 0 ? void 0 : _a.length); }, [verifiedOAuthCredentialsMap]);
    const getAccountInformation = (verifiedCredential) => {
        const { id, oauthAccountId, oauthAccountPhotos, oauthDisplayName, oauthEmails, oauthProvider, oauthUsername, publicIdentifier, } = verifiedCredential;
        return {
            accountId: oauthAccountId !== null && oauthAccountId !== void 0 ? oauthAccountId : undefined,
            avatar: oauthAccountPhotos === null || oauthAccountPhotos === void 0 ? void 0 : oauthAccountPhotos[0],
            displayName: oauthDisplayName !== null && oauthDisplayName !== void 0 ? oauthDisplayName : undefined,
            email: oauthEmails === null || oauthEmails === void 0 ? void 0 : oauthEmails[0],
            id,
            provider: oauthProvider,
            publicIdentifier,
            username: oauthUsername,
        };
    };
    const getLinkedAccountInformation = React.useCallback((provider, verifiedCredentialId) => {
        const verifiedCredential = findVerifiedCredentialById(provider, verifiedCredentialId);
        if (!verifiedCredential) {
            return;
        }
        return getAccountInformation(verifiedCredential);
    }, [findVerifiedCredentialById]);
    const getLinkedAccounts = React.useCallback((provider) => {
        var _a;
        const verifiedCredentials = (_a = verifiedOAuthCredentialsMap[provider]) !== null && _a !== void 0 ? _a : [];
        return verifiedCredentials.map((credential) => getAccountInformation(credential));
    }, [verifiedOAuthCredentialsMap]);
    const getAllLinkedAccounts = React.useCallback(() => Object.values(verifiedOAuthCredentialsMap)
        .flat()
        .map((credential) => getAccountInformation(credential)), [verifiedOAuthCredentialsMap]);
    const checkValidOAuthSignIn = React.useCallback((provider) => {
        var _a;
        const oauthProvider = getEnabledSocialSignInProvidersAsProviderEnum.getEnabledSocialSignInProvidersAsProviderEnum((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.socialSignIn) === null || _a === void 0 ? void 0 : _a.providers).find((socialProvider) => socialProvider === provider);
        if (!oauthProvider) {
            handleError(provider, types.SocialOAuthErrorCode.PROVIDER_NOT_ENABLED, `Provider is not enabled for sign-in on the dashboard: ${provider}`, { raiseAuthFailure: true });
            return false;
        }
        return true;
    }, [handleError, (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.socialSignIn) === null || _a === void 0 ? void 0 : _a.providers]);
    const signInWithSocialAccount = React.useCallback((provider_2, ...args_2) => _tslib.__awaiter(void 0, [provider_2, ...args_2], void 0, function* (provider, { redirectUrl, payingWithDynamic, showWidgetAfterConnection, triggerFundFromExchangeOnSuccess, } = {
        redirectUrl: undefined,
    }) {
        setProcessingForProvider(provider, true);
        try {
            yield connectSocialAccount({
                authMode: 'signin',
                isHeadlessSocialSignIn: true,
                payingWithDynamic,
                provider,
                redirectUrl,
                showWidgetAfterConnection,
                triggerFundFromExchangeOnSuccess,
                validator: checkValidOAuthSignIn,
            });
        }
        finally {
            setProcessingForProvider(provider, false);
        }
    }), [checkValidOAuthSignIn, connectSocialAccount, setProcessingForProvider]);
    // Maintain backwards compatibility for global isProcessing
    const isProcessingGlobal = React.useMemo(() => Array.from(processingStates.values()).some(Boolean), [processingStates]);
    return React.useMemo(() => ({
        error,
        getAllLinkedAccounts,
        getLinkedAccountInformation,
        getLinkedAccounts,
        isLinked,
        isProcessing: isProcessingGlobal, // Backwards compatible
        isProcessingForProvider, // New provider-specific function
        linkSocialAccount,
        signInWithSocialAccount,
        unlinkSocialAccount,
    }), [
        error,
        getLinkedAccountInformation,
        getLinkedAccounts,
        isLinked,
        isProcessingGlobal,
        isProcessingForProvider,
        linkSocialAccount,
        signInWithSocialAccount,
        unlinkSocialAccount,
        getAllLinkedAccounts,
    ]);
};

exports.useSocialAccounts = useSocialAccounts;
