'use client' import { create } from 'zustand' import { persist } from 'zustand/middleware' import { debouncedPersistJSONStorage } from '@/lib/stores/debounced-json-storage' import { useQueryClient } from '@tanstack/react-query' import { clearClientAuthState } from '@/lib/auth/clear-client-auth-state' import { useMailAccounts } from '@/lib/api/hooks/use-mail-queries' import { getOidcEndSessionPath, POST_LOGOUT_PATH } from '@/lib/auth/oidc-config' import { useNativeRuntime } from '@/lib/platform' import type { ApiMailAccount } from '@/lib/api/types' type AccountStoreState = { activeAccountId: string | null otherAccountsExpanded: boolean } type AccountStoreActions = { setActiveAccountId: (id: string | null) => void setOtherAccountsExpanded: (expanded: boolean) => void toggleOtherAccountsExpanded: () => void } export const useAccountStore = create()( persist( (set) => ({ activeAccountId: null, otherAccountsExpanded: true, setActiveAccountId: (id) => set({ activeAccountId: id }), setOtherAccountsExpanded: (expanded) => set({ otherAccountsExpanded: expanded }), toggleOtherAccountsExpanded: () => set((s) => ({ otherAccountsExpanded: !s.otherAccountsExpanded })), }), { name: 'ultimail-accounts', storage: debouncedPersistJSONStorage, partialize: (s) => ({ activeAccountId: s.activeAccountId, otherAccountsExpanded: s.otherAccountsExpanded, }), }, ), ) export function useActiveAccount(): ApiMailAccount | null { const activeAccountId = useAccountStore((s) => s.activeAccountId) const { data: accounts } = useMailAccounts() return accounts?.find((a) => a.id === activeAccountId) ?? accounts?.[0] ?? null } export function useSignOutAll() { const queryClient = useQueryClient() const native = useNativeRuntime() return async () => { await fetch("/api/auth/logout", { method: "POST", credentials: "include" }) clearClientAuthState(queryClient) if (native) { window.location.href = POST_LOGOUT_PATH return } window.location.assign(getOidcEndSessionPath()) } }