'use client'
import { useRef } from 'react';
import { createDynamicClient, hasExtension } from '@dynamic-labs-sdk/client';
import { registerExtension } from '@dynamic-labs-sdk/client/core';
import { setDynamicClient, hasDynamicClient, getDynamicClient } from '../../../client.js';
import { CLIENT_EXTENSION_NAME } from '../../constants.js';
import ApiEndpoint from '../../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../../shared/consts/index.js';
import { getApiHeaders } from './getApiHeaders/getApiHeaders.js';
import { syncEvents } from './syncEvents/syncEvents.js';

const useInitializeSdkClient = ({ settings, client: clientFromProps, }) => {
    const lastClientDependencyKey = useRef(null);
    /**
     * Sets the client to the state and setup the extensions.
     */
    const setClient = (client) => {
        if (hasExtension({ extensionKey: CLIENT_EXTENSION_NAME }, client)) {
            return;
        }
        setDynamicClient(client);
        registerExtension({ extensionKey: CLIENT_EXTENSION_NAME }, client);
        syncEvents(client);
    };
    /**
     * If a client is provided by the props, we should use it instead of
     * creating a new one.
     */
    if (clientFromProps) {
        if (!hasDynamicClient() || getDynamicClient() !== clientFromProps) {
            setClient(clientFromProps);
        }
        return;
    }
    const clientDependencyKey = [
        settings.apiBaseUrl,
        settings.environmentId,
    ].join('-');
    logger.logVerboseTroubleshootingMessage('[useInitializeSdkClient] Checking if DynamicClient needs to be created...', {
        clientDependencyKey,
        lastClientDependencyKey: lastClientDependencyKey.current,
    });
    if (lastClientDependencyKey.current === clientDependencyKey)
        return;
    lastClientDependencyKey.current = clientDependencyKey;
    logger.logVerboseTroubleshootingMessage('[useInitializeSdkClient] Creating DynamicClient...');
    const client = createDynamicClient({
        coreConfig: {
            apiBaseUrl: ApiEndpoint.getBaseUrl(),
            getApiHeaders,
        },
        environmentId: settings.environmentId,
        logLevel: settings.logLevel === 'DEBUG' ? 'debug' : undefined,
    });
    setClient(client);
};

export { useInitializeSdkClient };
