import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { createContext, useCallback, useContext, useEffect, useMemo } from "react";
import { ModalProvider } from "../modal/modalContext";
import { Toaster } from "../toast/Toaster";
import { TooltipProvider } from "../tooltip/tooltip";
import { useWalletConnector, useSessionStorage, OrderlyConfigProvider, useAccountInstance, OrderlyContext, useChains } from "@orderly.network/hooks";
import toast, { useToasterStore } from "react-hot-toast";
import { LocalProvider } from "../i18n";
import { isTestnet, praseChainIdToNumber } from "@orderly.network/utils";
import { PnLDefaultProps } from "../block/shared/shareConfigProps";
export const OrderlyAppContext = /*#__PURE__*/ createContext({});
export const OrderlyAppProvider = (props)=>{
    const { appIcons: logos, theme, configStore, keyStore, getWalletAdapter, brokerId, brokerName, networkId, includeTestnet, contracts, toastLimitCount, onChainChanged, footerStatusBarProps, shareOptions, chainFilter, customChains, referral, accountMenuItems, onClickAccountMenuItem, topBar, topBarProps } = props;
    return /*#__PURE__*/ _jsx(OrderlyConfigProvider, {
        configStore: configStore,
        keyStore: keyStore,
        getWalletAdapter: getWalletAdapter,
        brokerId: brokerId,
        brokerName: brokerName,
        networkId: networkId,
        contracts: contracts,
        chainFilter: chainFilter,
        children: /*#__PURE__*/ _jsx(InnerProvider, {
            appIcons: logos,
            theme: theme,
            toastLimitCount: toastLimitCount,
            onChainChanged: onChainChanged,
            brokerName: brokerName,
            footerStatusBarProps: footerStatusBarProps,
            shareOptions: {
                ...PnLDefaultProps,
                ...shareOptions
            },
            customChains: customChains,
            accountMenuItems: accountMenuItems,
            onClickAccountMenuItem: onClickAccountMenuItem,
            topBar: topBar,
            topBarProps: topBarProps,
            referral: referral,
            children: props.children
        })
    });
};
const InnerProvider = (props)=>{
    const { theme, appIcons: logos, brokerName, toastLimitCount = 1, onChainChanged, footerStatusBarProps, shareOptions, customChains, accountMenuItems, onClickAccountMenuItem, topBar, topBarProps, referral } = props;
    const { toasts } = useToasterStore();
    const { connect, disconnect, wallet: currentWallet, setChain } = useWalletConnector();
    const account = useAccountInstance();
    const { networkId } = useContext(OrderlyContext);
    const [orderlyChains] = useChains();
    const chains = useMemo(()=>{
        const _chains = customChains || orderlyChains;
        if (!_chains) {
            return [];
        }
        return [
            ..._chains?.mainnet,
            ..._chains.testnet
        ];
    }, [
        customChains,
        orderlyChains
    ]);
    const [errors, setErrors] = useSessionStorage("APP_ERRORS", {
        ChainNetworkNotSupport: false,
        IpNotSupport: false,
        NetworkError: false
    });
    const checkChainId = useCallback((chainId)=>{
        if (!chainId || !chains) {
            return false;
        }
        // if (typeof chainId === "number") {
        //   chainId = `0x${Number(chainId).toString(16)}`;
        // }
        // check whether chain id and network id match
        // const chainIdNum = parseInt(chainId, 16);
        if (networkId === "mainnet" && isTestnet(chainId) || networkId === "testnet" && !isTestnet(chainId)) {
            return false;
        }
        const isSupport = chains.some((item)=>{
            const _chainId = item.network_infos?.chain_id;
            if (typeof _chainId === "string") {
                // return `0x${Number(_chainId).toString(16)}` === chainId;
                return parseInt(_chainId, 16) === chainId;
            }
            return _chainId === chainId;
        });
        return isSupport;
    }, [
        chains,
        networkId
    ]);
    const _onWalletConnect = useCallback(async ()=>{
        if (connect) {
            const walletState = await connect();
            if (Array.isArray(walletState) && walletState.length > 0 && walletState[0] && walletState[0].accounts.length > 0) {
                const wallet = walletState[0];
                ////// check chainid ///////
                const chainId = praseChainIdToNumber(wallet.chains[0].id);
                if (!checkChainId(chainId)) {
                    return false;
                }
                //
                if (!account) {
                    throw new Error("account is not initialized");
                }
                ;
                // account.address = wallet.accounts[0].address;
                const status = await account.setAddress(wallet.accounts[0].address, {
                    provider: wallet.provider,
                    chain: {
                        id: praseChainIdToNumber(wallet.chains[0].id)
                    },
                    wallet: {
                        name: wallet.label
                    }
                });
                return {
                    wallet,
                    status
                };
            }
        } else {
            throw new Error("walletProvider is required");
        }
    }, [
        connect,
        account,
        networkId
    ]);
    const _onWalletDisconnect = useCallback(async ()=>{
        if (typeof disconnect === "function" && currentWallet) {
            ;
            return disconnect(currentWallet).then(()=>{
                return account.disconnect();
            });
        }
    }, [
        disconnect,
        currentWallet,
        account
    ]);
    const _onSetChain = useCallback((chainId)=>{
        return setChain({
            chainId
        }).then((success)=>{
            if (success) {
                // @ts-ignore
                setErrors((errors)=>({
                        ...errors,
                        ChainNetworkNotSupport: false
                    }));
            }
            return success;
        });
    }, []);
    const currentAddress = useMemo(()=>{
        if (!currentWallet) {
            return null;
        }
        return currentWallet.accounts[0].address;
    }, [
        currentWallet
    ]);
    // current connected chain id
    const currentChainId = useMemo(()=>{
        if (!currentWallet) {
            return null;
        }
        const id = currentWallet.chains[0].id;
        return praseChainIdToNumber(id);
    }, [
        currentWallet
    ]);
    useEffect(()=>{
        // currentWallet?.provider.detectNetwork().then((x) =>
        if (!chains || chains.length === 0 || !currentChainId) {
            return;
        }
        // console.log("currentWallet", currentWallet, account, currentChainId);
        if (!!currentWallet && Array.isArray(currentWallet.accounts) && currentWallet.accounts.length > 0 && account) {
            if (account.address === currentAddress && currentChainId === account.chainId) {
                return;
            }
            if (!checkChainId(currentChainId)) {
                // @ts-ignore
                setErrors((errors)=>({
                        ...errors,
                        ChainNetworkNotSupport: true
                    }));
                ;
            // return;
            } else {
                setErrors((errors)=>({
                        ...errors,
                        ChainNetworkNotSupport: false
                    }));
            }
            if (currentAddress !== account.address) {
                account.setAddress(currentWallet.accounts[0].address, {
                    provider: currentWallet.provider,
                    chain: {
                        id: currentChainId
                    },
                    wallet: {
                        name: currentWallet.label
                    }
                });
            } else if (currentChainId !== account.chainId) {
                account.switchChainId(currentChainId);
            }
        }
    // }
    // }, [ready, currentWallet]);
    }, [
        currentAddress,
        currentChainId,
        chains,
        account,
        networkId
    ]);
    // limit toast count
    useEffect(()=>{
        toasts.filter((t)=>t.visible) // Only consider visible toasts
        .filter((_, i)=>i >= toastLimitCount) // Is toast index over limit
        .forEach((t)=>toast.dismiss(t.id)); // Dismiss – Use toast.remove(t.id) removal without animation
    }, [
        toasts
    ]);
    useEffect(()=>{
        const searchParams = new URLSearchParams(window.location.search);
        const refCode = searchParams.get("ref");
        if (refCode) {
            localStorage.setItem("referral_code", refCode);
        }
    }, []);
    return /*#__PURE__*/ _jsxs(OrderlyAppContext.Provider, {
        value: {
            appIcons: logos,
            theme,
            errors,
            onWalletConnect: _onWalletConnect,
            onWalletDisconnect: _onWalletDisconnect,
            onSetChain: _onSetChain,
            onChainChanged,
            brokerName,
            footerStatusBarProps,
            shareOptions,
            customChains: props.customChains,
            accountMenuItems,
            onClickAccountMenuItem,
            topBar,
            topBarProps,
            referral
        },
        children: [
            /*#__PURE__*/ _jsx(TooltipProvider, {
                children: /*#__PURE__*/ _jsx(LocalProvider, {
                    children: /*#__PURE__*/ _jsx(ModalProvider, {
                        children: props.children
                    })
                })
            }),
            /*#__PURE__*/ _jsx(Toaster, {})
        ]
    });
};

//# sourceMappingURL=appProvider.js.map