import { create } from 'zustand';
import { offlineSyncManager } from '../lib/offlineSync';

interface NetworkStore {
  isOnline: boolean;
  isSyncing: boolean;
  pendingCount: number;
  setOnline: (isOnline: boolean) => void;
  setSyncing: (isSyncing: boolean) => void;
  setPendingCount: (count: number) => void;
  updatePendingCount: () => void;
}

export const useNetworkStore = create<NetworkStore>((set) => ({
  isOnline: true,
  isSyncing: false,
  pendingCount: 0,

  setOnline: (isOnline) => set({ isOnline }),
  setSyncing: (isSyncing) => set({ isSyncing }),
  setPendingCount: (count) => set({ pendingCount: count }),
  
  updatePendingCount: () => {
    const count = offlineSyncManager.getPendingCount();
    set({ pendingCount: count });
  },
}));

// Listen to network changes
offlineSyncManager.onNetworkChange((isOnline) => {
  useNetworkStore.getState().setOnline(isOnline);
  useNetworkStore.getState().updatePendingCount();
});
