import React, { createContext, useContext, useState } from 'react';
import { useAuth } from './AuthContext';
import { ApiService } from '../services/api';

interface RefreshContextType {
  refreshing: boolean;
  refreshAll: () => Promise<void>;
}

const RefreshContext = createContext<RefreshContextType | undefined>(undefined);

export function RefreshProvider({ children }: { children: React.ReactNode }) {
  const [refreshing, setRefreshing] = useState(false);
  const { syncUser } = useAuth();

  const refreshAll = async () => {
    setRefreshing(true);
    try {
      // Sync User Data
      await syncUser();
      // You can add more global syncs here (e.g., config, notifications)
    } catch (e) {
      console.error('Global refresh failed', e);
    } finally {
      setRefreshing(false);
    }
  };

  return (
    <RefreshContext.Provider value={{ refreshing, refreshAll }}>
      {children}
    </RefreshContext.Provider>
  );
}

export function useRefresh() {
  const context = useContext(RefreshContext);
  if (context === undefined) throw new Error('useRefresh must be used within a RefreshProvider');
  return context;
}
