import { create } from 'zustand';

export type CloudSync = 'idle' | 'saving' | 'saved' | 'error';

interface ConnectivityState {
  /** browser online/offline (navigator.onLine + events) */
  online: boolean;
  /** cloud autosave state, surfaced in the shell */
  cloudSync: CloudSync;
  lastSavedAt: number | null;
  setOnline: (online: boolean) => void;
  setCloudSync: (cloudSync: CloudSync) => void;
}

/** Ephemeral connectivity + sync status (intentionally not persisted). */
export const useConnectivityStore = create<ConnectivityState>((set) => ({
  online: typeof navigator === 'undefined' ? true : navigator.onLine,
  cloudSync: 'idle',
  lastSavedAt: null,
  setOnline: (online) => set({ online }),
  setCloudSync: (cloudSync) =>
    set((s) => ({ cloudSync, lastSavedAt: cloudSync === 'saved' ? Date.now() : s.lastSavedAt })),
}));
