import { useSyncExternalStore } from 'react'; /** * Small in-memory client view of RevenueCat access. The RevenueCat bridge updates * it at launch and on purchase changes; Convex independently validates the same * entitlement before allowing cloud reads or writes. Local task features never * depend on this state. * * Development helpers: * • long-press the "Glide" wordmark to cycle states * • from the Metro debugger: `__glideSub('grace')` */ export type SubscriptionState = 'free' | 'subscribed' | 'grace' | 'billing'; const ORDER: SubscriptionState[] = ['free', 'subscribed', 'grace', 'billing']; let state: SubscriptionState = 'free'; let graceEndsAt: number | null = null; const listeners = new Set<() => void>(); function emit(): void { listeners.forEach((listener) => listener()); } export function getSubscriptionState(): SubscriptionState { return state; } export function setSubscriptionState( next: SubscriptionState, options?: { graceEndsAt?: number } ): void { const nextGraceEndsAt = next === 'grace' ? options?.graceEndsAt ?? graceEndsAt ?? Date.now() + 15 * 24 * 60 * 60 * 1000 : null; if (state === next && graceEndsAt === nextGraceEndsAt) return; state = next; graceEndsAt = nextGraceEndsAt; emit(); } export function cycleSubscriptionState(): void { setSubscriptionState(ORDER[(ORDER.indexOf(state) + 1) % ORDER.length]); } export function getGraceDaysLeft(): number { if (graceEndsAt === null) return 0; return Math.max(0, Math.ceil((graceEndsAt - Date.now()) / (24 * 60 * 60 * 1000))); } function subscribe(listener: () => void): () => void { listeners.add(listener); return () => listeners.delete(listener); } export function useSubscriptionState(): SubscriptionState { return useSyncExternalStore(subscribe, getSubscriptionState, getSubscriptionState); } export function useGraceDaysLeft(): number { return useSyncExternalStore(subscribe, getGraceDaysLeft, getGraceDaysLeft); } if (__DEV__) { (globalThis as Record).__glideSub = setSubscriptionState; }