"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    OrderlyAppContext: function() {
        return OrderlyAppContext;
    },
    OrderlyAppProvider: function() {
        return OrderlyAppProvider;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _modalContext = require("../modal/modalContext");
const _Toaster = require("../toast/Toaster");
const _tooltip = require("../tooltip/tooltip");
const _hooks = require("@orderly.network/hooks");
const _reacthottoast = /*#__PURE__*/ _interop_require_wildcard(require("react-hot-toast"));
const _i18n = require("../i18n");
const _utils = require("@orderly.network/utils");
const _shareConfigProps = require("../block/shared/shareConfigProps");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const OrderlyAppContext = /*#__PURE__*/ (0, _react.createContext)({});
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__*/ (0, _jsxruntime.jsx)(_hooks.OrderlyConfigProvider, {
        configStore: configStore,
        keyStore: keyStore,
        getWalletAdapter: getWalletAdapter,
        brokerId: brokerId,
        brokerName: brokerName,
        networkId: networkId,
        contracts: contracts,
        chainFilter: chainFilter,
        children: /*#__PURE__*/ (0, _jsxruntime.jsx)(InnerProvider, {
            appIcons: logos,
            theme: theme,
            toastLimitCount: toastLimitCount,
            onChainChanged: onChainChanged,
            brokerName: brokerName,
            footerStatusBarProps: footerStatusBarProps,
            shareOptions: {
                ..._shareConfigProps.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 } = (0, _reacthottoast.useToasterStore)();
    const { connect, disconnect, wallet: currentWallet, setChain } = (0, _hooks.useWalletConnector)();
    const account = (0, _hooks.useAccountInstance)();
    const { networkId } = (0, _react.useContext)(_hooks.OrderlyContext);
    const [orderlyChains] = (0, _hooks.useChains)();
    const chains = (0, _react.useMemo)(()=>{
        const _chains = customChains || orderlyChains;
        if (!_chains) {
            return [];
        }
        return [
            ..._chains?.mainnet,
            ..._chains.testnet
        ];
    }, [
        customChains,
        orderlyChains
    ]);
    const [errors, setErrors] = (0, _hooks.useSessionStorage)("APP_ERRORS", {
        ChainNetworkNotSupport: false,
        IpNotSupport: false,
        NetworkError: false
    });
    const checkChainId = (0, _react.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" && (0, _utils.isTestnet)(chainId) || networkId === "testnet" && !(0, _utils.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 = (0, _react.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 = (0, _utils.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: (0, _utils.praseChainIdToNumber)(wallet.chains[0].id)
                    },
                    wallet: {
                        name: wallet.label
                    }
                });
                return {
                    wallet,
                    status
                };
            }
        } else {
            throw new Error("walletProvider is required");
        }
    }, [
        connect,
        account,
        networkId
    ]);
    const _onWalletDisconnect = (0, _react.useCallback)(async ()=>{
        if (typeof disconnect === "function" && currentWallet) {
            ;
            return disconnect(currentWallet).then(()=>{
                return account.disconnect();
            });
        }
    }, [
        disconnect,
        currentWallet,
        account
    ]);
    const _onSetChain = (0, _react.useCallback)((chainId)=>{
        return setChain({
            chainId
        }).then((success)=>{
            if (success) {
                // @ts-ignore
                setErrors((errors)=>({
                        ...errors,
                        ChainNetworkNotSupport: false
                    }));
            }
            return success;
        });
    }, []);
    const currentAddress = (0, _react.useMemo)(()=>{
        if (!currentWallet) {
            return null;
        }
        return currentWallet.accounts[0].address;
    }, [
        currentWallet
    ]);
    // current connected chain id
    const currentChainId = (0, _react.useMemo)(()=>{
        if (!currentWallet) {
            return null;
        }
        const id = currentWallet.chains[0].id;
        return (0, _utils.praseChainIdToNumber)(id);
    }, [
        currentWallet
    ]);
    (0, _react.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
    (0, _react.useEffect)(()=>{
        toasts.filter((t)=>t.visible) // Only consider visible toasts
        .filter((_, i)=>i >= toastLimitCount) // Is toast index over limit
        .forEach((t)=>_reacthottoast.default.dismiss(t.id)); // Dismiss – Use toast.remove(t.id) removal without animation
    }, [
        toasts
    ]);
    (0, _react.useEffect)(()=>{
        const searchParams = new URLSearchParams(window.location.search);
        const refCode = searchParams.get("ref");
        if (refCode) {
            localStorage.setItem("referral_code", refCode);
        }
    }, []);
    return /*#__PURE__*/ (0, _jsxruntime.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__*/ (0, _jsxruntime.jsx)(_tooltip.TooltipProvider, {
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_i18n.LocalProvider, {
                    children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_modalContext.ModalProvider, {
                        children: props.children
                    })
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_Toaster.Toaster, {})
        ]
    });
};

//# sourceMappingURL=appProvider.js.map