import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react"; import type { AuthResult } from "../api/types"; import { sessionStore, type Session } from "./store"; interface SessionApi { session: Session | null; signIn: (auth: AuthResult) => void; /** Leaves the account. Anonymous history is always wiped: it cannot be restored anyway. */ signOut: (opts?: { wipe?: boolean }) => void; } const Ctx = createContext(null); export function SessionProvider({ children }: { children: ReactNode }) { // The old shared demo account ("tok-andrey") is retired: every visitor now gets a private copy. const [session, setSession] = useState(() => { const s = sessionStore.load(); return s && s.token === "tok-andrey" ? null : s; }); const signIn = useCallback((auth: AuthResult) => { const next: Session = { token: auth.token, mode: auth.mode, displayName: auth.display_name }; sessionStore.save(next); setSession(next); }, []); const signOut = useCallback((opts?: { wipe?: boolean }) => { setSession((current) => { sessionStore.clear(current, opts?.wipe ?? current?.mode === "anonymous"); return null; }); }, []); const value = useMemo(() => ({ session, signIn, signOut }), [session, signIn, signOut]); return {children}; } export function useSession(): SessionApi { const value = useContext(Ctx); if (!value) throw new Error("useSession outside SessionProvider"); return value; }