import { useEffect } from 'react'; import { createProfileWalletStore } from '@/packages/shared/src/stores/createProfileWalletStore'; import { getPlatformProfileRechargeCenter } from '@/src/services/platform-entry/platformProfileClient.ts'; export const usePlatformWalletStore = createProfileWalletStore({ getRechargeCenter: (signal) => getPlatformProfileRechargeCenter({ signal }), }); export function usePlatformWalletLifecycle( currentUserId: string | null, canAccessProtectedData: boolean, ) { const setWalletOwner = usePlatformWalletStore( (state) => state.setWalletOwner, ); const onWalletBalanceMayHaveChanged = usePlatformWalletStore( (state) => state.onWalletBalanceMayHaveChanged, ); const resetWalletBalance = usePlatformWalletStore( (state) => state.resetWalletBalance, ); useEffect(() => { const ownerUserId = canAccessProtectedData && currentUserId ? currentUserId : null; setWalletOwner(ownerUserId); if (!ownerUserId) { return () => { resetWalletBalance(); }; } void onWalletBalanceMayHaveChanged(); let foregroundRefreshTimer: number | null = null; const scheduleWalletRefresh = () => { if (foregroundRefreshTimer !== null) { return; } foregroundRefreshTimer = window.setTimeout(() => { foregroundRefreshTimer = null; void onWalletBalanceMayHaveChanged(); }, 0); }; const refreshVisibleWallet = () => { if (document.visibilityState === 'visible') { scheduleWalletRefresh(); } }; window.addEventListener('focus', scheduleWalletRefresh); document.addEventListener('visibilitychange', refreshVisibleWallet); return () => { window.removeEventListener('focus', scheduleWalletRefresh); document.removeEventListener('visibilitychange', refreshVisibleWallet); if (foregroundRefreshTimer !== null) { window.clearTimeout(foregroundRefreshTimer); } resetWalletBalance(); }; }, [ canAccessProtectedData, currentUserId, onWalletBalanceMayHaveChanged, resetWalletBalance, setWalletOwner, ]); }