'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var Button = require('../../../../components/Button/Button.cjs');
var Skeleton = require('../../../../components/Skeleton/Skeleton.cjs');
require('../../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('@dynamic-labs/iconic');
var midnightShielded = require('../../../../shared/assets/midnight-shielded.cjs');
var midnightUnshielded = require('../../../../shared/assets/midnight-unshielded.cjs');
require('../../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../../shared/consts/index.cjs');
var classNames = require('../../../../utils/functions/classNames/classNames.cjs');
var usePromise = require('../../../../utils/hooks/usePromise/usePromise.cjs');

const DUST_SEGMENTS = 20;
// Stable keys for the fixed-length decorative dust bar so the segments don't
// rely on the array index as their React key.
const DUST_SEGMENT_KEYS = Array.from({ length: DUST_SEGMENTS }, (_, i) => `dust-segment-${i}`);
const truncateToDecimals = (value, decimals) => {
    const [whole, fractional] = value.split('.');
    if (!fractional || decimals <= 0)
        return whole;
    const sliced = fractional.slice(0, decimals);
    let end = sliced.length;
    while (end > 0 && sliced[end - 1] === '0') {
        end -= 1;
    }
    const trimmed = sliced.slice(0, end);
    return trimmed.length > 0 ? `${whole}.${trimmed}` : whole;
};
const getDustFillCount = (balance, cap) => {
    const b = parseFloat(balance);
    const c = parseFloat(cap);
    if (!c || isNaN(b) || isNaN(c))
        return 0;
    return Math.round(Math.min(b / c, 1) * DUST_SEGMENTS);
};
const TABS = [
    {
        copykey: 'dyn_active_wallet_info.midnight_shielded_balance',
        id: 'shielded',
    },
    {
        copykey: 'dyn_active_wallet_info.midnight_unshielded_balance',
        id: 'unshielded',
    },
];
const ActiveMidnightWalletBalance = ({ isLoading = false, }) => {
    const { t } = reactI18next.useTranslation();
    const { primaryWallet, network } = useInternalDynamicContext.useInternalDynamicContext();
    const [activeTab, setActiveTab] = React.useState('shielded');
    const walletAddress = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address;
    const enabled = Boolean(!isLoading && primaryWallet && walletConnectorCore.isMidnightConnector(primaryWallet.connector));
    // Balance reads resolve on shielded+unshielded; dust finishes in the
    // background. While dust is still syncing we re-fetch on an interval so the
    // dust gauge fills in once it's ready (shielded/unshielded already final).
    const [dustPollTick, setDustPollTick] = React.useState(0);
    const { data: balances, isLoading: balancesLoading } = usePromise.usePromise(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!primaryWallet ||
            !walletConnectorCore.isMidnightConnector(primaryWallet.connector) ||
            !walletConnectorCore.isMidnightWallet(primaryWallet)) {
            return undefined;
        }
        return primaryWallet.getFormattedBalances();
    }), {
        // `network` is in the deps so switching the picker re-fetches against the
        // newly-selected network (the connector passes it through to the wallet
        // client, which syncs/serves that network's balances). `balancesLoading`
        // then drives the syncing/skeleton state while the new network syncs.
        deps: [walletAddress, primaryWallet, dustPollTick, network],
        enabled,
    });
    const { dustBalance, shieldedTokenCount, unshieldedBalance, dustSyncing } = balances !== null && balances !== void 0 ? balances : {};
    // Track which network the currently-held `balances` belong to. On a network
    // switch `usePromise` keeps the previous network's data while it refetches, so
    // without this we'd briefly show the old network's balance. We treat the view
    // as "switching" until a fetch COMPLETES for the selected network — gated on
    // the loading true→false transition: at the switch commit this effect still
    // sees the previous fetch's settled `balancesLoading=false` in its closure,
    // so an ungated update would re-arm immediately and let the stale value
    // render. Background dust polls don't change `network`, so they never
    // trigger this.
    const [balancesNetwork, setBalancesNetwork] = React.useState(network);
    const balancesWereLoadingRef = React.useRef(balancesLoading);
    React.useEffect(() => {
        if (balancesWereLoadingRef.current && !balancesLoading && balances) {
            setBalancesNetwork(network);
        }
        balancesWereLoadingRef.current = balancesLoading;
    }, [balancesLoading, balances, network]);
    const isNetworkSwitching = Boolean(balances) && balancesNetwork !== network;
    React.useEffect(() => {
        // Don't poll while switching networks: the held `dustSyncing` still reflects
        // the previous network, and the new network's wallet is (re)syncing — extra
        // polls would just pile redundant balance reads onto the switch.
        if (!dustSyncing || isNetworkSwitching)
            return undefined;
        // Poll frequently while syncing so the gauge appears within a couple
        // seconds of dust completing (sync now finishes in ~4s). The effect stops
        // the moment `dustSyncing` flips false, so this adds no steady-state load.
        const id = setInterval(() => setDustPollTick((tick) => tick + 1), 2500);
        return () => clearInterval(id);
    }, [dustSyncing, isNetworkSwitching]);
    // `registerDust` is a WaaS-only connector method (external/injected Midnight
    // wallets manage dust themselves). When the embedded wallet has no dust
    // registered yet, we surface a "Register DUST" button instead of the gauge.
    const isWaasWallet = Boolean(primaryWallet && walletConnectorCore.isDynamicWaasConnector(primaryWallet.connector));
    // True once registered. balance/cap can't tell us this on load (cap reads 0
    // on current wallet-client builds), so we track it after a register call to
    // flip from the "Register DUST" prompt to the generating state. Dust is
    // per-network, so a switch resets the flag — otherwise the register prompt
    // stays hidden on a network where dust was never registered.
    const [dustRegistered, setDustRegistered] = React.useState(false);
    React.useEffect(() => {
        setDustRegistered(false);
    }, [network]);
    // Returns the promise so <Button> shows its built-in spinner while the heavy
    // registerDust call runs.
    const handleRegisterDust = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const connector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
        if (!(connector === null || connector === void 0 ? void 0 : connector.registerDust))
            return;
        try {
            const result = yield connector.registerDust();
            if ((result === null || result === void 0 ? void 0 : result.status) === 'registered' ||
                (result === null || result === void 0 ? void 0 : result.status) === 'already_registered' ||
                (result === null || result === void 0 ? void 0 : result.status) === 'already_has_dust') {
                setDustRegistered(true);
            }
            setDustPollTick((tick) => tick + 1);
        }
        catch (err) {
            // Leave the prompt up so the user can retry rather than failing silently.
            logger.logger.error('Failed to register dust', err);
        }
    });
    // Show the full skeleton on the very first load AND while switching networks
    // (so the previous network's stale value isn't shown until the new one
    // arrives). Background dust polls keep `balances` for the same network, so
    // they never flash the skeleton.
    if (((isLoading || balancesLoading) && !balances) || isNetworkSwitching) {
        return (jsxRuntime.jsx("div", { className: 'active-midnight-balance', children: jsxRuntime.jsx(Skeleton.Skeleton, { className: 'active-midnight-balance__skeleton' }) }));
    }
    const dustFill = dustBalance
        ? getDustFillCount(dustBalance.balance, dustBalance.cap)
        : 0;
    const dustBalanceDisplay = dustBalance
        ? {
            balance: truncateToDecimals(dustBalance.balance, 2),
            cap: truncateToDecimals(dustBalance.cap, 2),
        }
        : undefined;
    // Unshielded shows the native NIGHT amount; shielded has no NIGHT, so it
    // shows the count of token types held in the pool instead.
    const tokenCount = shieldedTokenCount !== null && shieldedTokenCount !== void 0 ? shieldedTokenCount : 0;
    const shieldedDisplay = `${tokenCount} ${tokenCount === 1 ? 'token' : 'tokens'}`;
    // Dust section has three mutually exclusive states (syncing, generating with
    // a balance, and the WaaS "register dust" prompt). Resolved via a helper to
    // avoid nesting ternaries in the JSX below.
    const renderDustSection = () => {
        if (dustSyncing) {
            return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: 'active-midnight-balance__dust', children: jsxRuntime.jsx("div", { className: 'active-midnight-balance__dust-header', children: jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust-title', children: [jsxRuntime.jsx("svg", { className: 'active-midnight-balance__dust-icon', width: '12', height: '12', viewBox: '0 0 24 24', children: jsxRuntime.jsx("path", { d: 'M13 2L3 14h9l-1 8 10-12h-9l1-8z' }) }), jsxRuntime.jsx("span", { className: 'active-midnight-balance__dust-label', "data-copykey": 'dyn_active_wallet_info.midnight_dust_syncing', children: t('dyn_active_wallet_info.midnight_dust_syncing') })] }) }) }), jsxRuntime.jsx("div", { className: 'active-midnight-balance__divider' })] }));
        }
        // Generating gauge: shown with a dust balance, or once registered (balance
        // still 0 during the grace period). Bar renders either way; count only
        // shows with a real balance.
        if (dustBalance || (isWaasWallet && dustRegistered)) {
            return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust', children: [jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust-header', children: [jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust-title', children: [jsxRuntime.jsx("svg", { className: 'active-midnight-balance__dust-icon', width: '12', height: '12', viewBox: '0 0 24 24', children: jsxRuntime.jsx("path", { d: 'M13 2L3 14h9l-1 8 10-12h-9l1-8z' }) }), jsxRuntime.jsx("span", { className: 'active-midnight-balance__dust-label', "data-copykey": 'dyn_active_wallet_info.midnight_dust_generating', children: t('dyn_active_wallet_info.midnight_dust_generating') })] }), dustBalanceDisplay && (jsxRuntime.jsxs("span", { className: 'active-midnight-balance__dust-count', children: [dustBalanceDisplay.balance, "/", dustBalanceDisplay.cap] }))] }), jsxRuntime.jsx("div", { className: 'active-midnight-balance__dust-bar', children: DUST_SEGMENT_KEYS.map((segmentKey, i) => (jsxRuntime.jsx("div", { className: [
                                        'active-midnight-balance__dust-segment',
                                        i === 0 && 'active-midnight-balance__dust-segment--first',
                                        i === DUST_SEGMENTS - 1 &&
                                            'active-midnight-balance__dust-segment--last',
                                        i < dustFill &&
                                            'active-midnight-balance__dust-segment--filled',
                                    ]
                                        .filter(Boolean)
                                        .join(' ') }, segmentKey))) })] }), jsxRuntime.jsx("div", { className: 'active-midnight-balance__divider' })] }));
        }
        if (isWaasWallet) {
            return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust', children: [jsxRuntime.jsx("div", { className: 'active-midnight-balance__dust-header', children: jsxRuntime.jsxs("div", { className: 'active-midnight-balance__dust-title', children: [jsxRuntime.jsx("svg", { className: 'active-midnight-balance__dust-icon', width: '12', height: '12', viewBox: '0 0 24 24', children: jsxRuntime.jsx("path", { d: 'M13 2L3 14h9l-1 8 10-12h-9l1-8z' }) }), jsxRuntime.jsx("span", { className: 'active-midnight-balance__dust-label', "data-copykey": 'dyn_active_wallet_info.midnight_dust_not_registered', children: t('dyn_active_wallet_info.midnight_dust_not_registered') })] }) }), jsxRuntime.jsx(Button.Button, { buttonPadding: 'small', buttonVariant: 'secondary', buttonClassName: 'active-midnight-balance__register-dust-button', onClick: handleRegisterDust, "data-copykey": 'dyn_active_wallet_info.midnight_register_dust', children: t('dyn_active_wallet_info.midnight_register_dust') })] }), jsxRuntime.jsx("div", { className: 'active-midnight-balance__divider' })] }));
        }
        return null;
    };
    return (jsxRuntime.jsx("div", { className: 'active-midnight-balance', children: jsxRuntime.jsxs("div", { className: 'active-midnight-balance__card', children: [renderDustSection(), jsxRuntime.jsx("div", { className: 'active-midnight-balance__tab-bar', children: TABS.map(({ id, copykey }) => (jsxRuntime.jsx("button", { className: classNames.classNames('active-midnight-balance__tab', {
                            'active-midnight-balance__tab--active': activeTab === id,
                        }), "data-copykey": copykey, onClick: () => setActiveTab(id), children: t(copykey) }, id))) }), jsxRuntime.jsxs("div", { className: 'active-midnight-balance__pocket', children: [activeTab === 'shielded' ? (jsxRuntime.jsx(midnightShielded.ReactComponent, { className: 'active-midnight-balance__pocket-icon' })) : (jsxRuntime.jsx(midnightUnshielded.ReactComponent, { className: 'active-midnight-balance__pocket-icon' })), jsxRuntime.jsx("span", { className: 'active-midnight-balance__amount', children: activeTab === 'shielded'
                                ? shieldedDisplay
                                : `${unshieldedBalance !== null && unshieldedBalance !== void 0 ? unshieldedBalance : '—'} NIGHT` })] })] }) }));
};

exports.ActiveMidnightWalletBalance = ActiveMidnightWalletBalance;
