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

// Hook exposed to customers and used internally to handle social account linking
const useSocialAccounts = () => {
    var _a;
    const { environmentId, user, projectSettings } = useInternalDynamicContext();
    const { pushView } = useViewContext();
    const { setSocialProvider } = useSocialRedirectContext();
    // Provider-specific processing states
    const [processingStates, setProcessingStates] = useState(new Map());
    // Helper functions for provider-specific processing state
    const setProcessingForProvider = useCallback((provider, isProcessing) => {
        setProcessingStates((prev) => new Map(prev).set(provider, isProcessing));
    }, []);
    const isProcessingForProvider = useCallback((provider) => { var _a; return (_a = processingStates.get(provider)) !== null && _a !== void 0 ? _a : false; }, [processingStates]);
    const handleFarcasterUrl = useCallback((url) => pushView('farcaster-connect-view', { url }, {
        onBackClick: () => {
            setSocialProvider(undefined);
            dynamicEvents.emit('farcasterConnectCancelled');
            dynamicEvents.emit('authFailure', {
                option: ProviderEnum.Farcaster,
                provider: ProviderEnum.Farcaster,
                type: 'social',
            }, 'user-cancelled');
        },
    }), [pushView, setSocialProvider]);
    const { handleError, setError, checkValidProvider, error, connectSocialAccount, } = useSocialAuth({
        onFarcasterUrl: handleFarcasterUrl,
    });
    const verifiedOAuthCredentialsMap = 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 = useCallback((provider) => {
        if (!isSocialKycEnabled(projectSettings)) {
            handleError(provider, SocialOAuthErrorCode.SOCIAL_LINKING_NOT_ENABLED, 'Social linking is not enabled in Information Capture on the dashboard', { raiseAuthFailure: false });
            return false;
        }
        const oauthProviders = 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, 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 = useCallback((provider_1, ...args_1) => __awaiter(void 0, [provider_1, ...args_1], void 0, function* (provider, { redirectUrl, showWidgetAfterConnection, triggerFundFromExchangeOnSuccess, payingWithDynamic, } = {
        payingWithDynamic: undefined,
        redirectUrl: undefined,
        showWidgetAfterConnection: false,
        triggerFundFromExchangeOnSuccess: undefined,
    }) {
        setProcessingForProvider(provider, true);
        try {
            yield connectSocialAccount({
                authMode: 'link',
                payingWithDynamic,
                provider,
                redirectUrl,
                showWidgetAfterConnection,
                triggerFundFromExchangeOnSuccess,
                validator: checkValidOAuthLinking,
            });
        }
        finally {
            setProcessingForProvider(provider, false);
        }
    }), [checkValidOAuthLinking, connectSocialAccount, setProcessingForProvider]);
    const findVerifiedCredentialById = 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 = useCallback((provider, verifiedCredentialId) => __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, SocialOAuthErrorCode.NO_ACCOUNT_LINKED, `No account linked for provider: ${provider}`, { raiseAuthFailure: false });
            setProcessingForProvider(provider, false);
            return;
        }
        try {
            const primaryWalletId = getPrimaryWalletId();
            const response = yield unlinkOAuth({
                environmentId,
                primaryWalletId,
                verifiedCredentialId: (_b = verifiedCredential.id) !== null && _b !== void 0 ? _b : '',
            });
            if (!response) {
                handleError(provider, SocialOAuthErrorCode.UNLINK_ERROR, `Failed to unlink social account: ${provider} | ${verifiedCredential.id}`, { raiseAuthFailure: false });
                return;
            }
        }
        catch (err) {
            handleError(provider, 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 = 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 = useCallback((provider, verifiedCredentialId) => {
        const verifiedCredential = findVerifiedCredentialById(provider, verifiedCredentialId);
        if (!verifiedCredential) {
            return;
        }
        return getAccountInformation(verifiedCredential);
    }, [findVerifiedCredentialById]);
    const getLinkedAccounts = useCallback((provider) => {
        var _a;
        const verifiedCredentials = (_a = verifiedOAuthCredentialsMap[provider]) !== null && _a !== void 0 ? _a : [];
        return verifiedCredentials.map((credential) => getAccountInformation(credential));
    }, [verifiedOAuthCredentialsMap]);
    const getAllLinkedAccounts = useCallback(() => Object.values(verifiedOAuthCredentialsMap)
        .flat()
        .map((credential) => getAccountInformation(credential)), [verifiedOAuthCredentialsMap]);
    const checkValidOAuthSignIn = useCallback((provider) => {
        var _a;
        const oauthProvider = 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, 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 = useCallback((provider_2, ...args_2) => __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 = useMemo(() => Array.from(processingStates.values()).some(Boolean), [processingStates]);
    return 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,
    ]);
};

export { useSocialAccounts };
