import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import type { BindPayload } from '@/lib/types' import { clearBindPayload, loadBindPayload, saveBindPayload } from '@/lib/storage' type Ctx = { bind: BindPayload | null ready: boolean setBind: (p: BindPayload | null) => Promise clear: () => Promise } const BindContext = createContext(null) export function BindProvider({ children }: { children: React.ReactNode }) { const [bind, setBindState] = useState(null) const [ready, setReady] = useState(false) useEffect(() => { void (async () => { const p = await loadBindPayload() setBindState(p) setReady(true) })() }, []) const setBind = useCallback(async (p: BindPayload | null) => { setBindState(p) if (p) await saveBindPayload(p) else await clearBindPayload() }, []) const clear = useCallback(async () => { setBindState(null) await clearBindPayload() }, []) const value = useMemo( () => ({ bind, ready, setBind, clear }), [bind, ready, setBind, clear], ) return {children} } export function useBind(): Ctx { const c = useContext(BindContext) if (!c) throw new Error('useBind outside BindProvider') return c }