import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';

interface SubscriptionEventsContextType {
  subscriptionVersion: number;
  notifySubscriptionChanged: () => void;
  subscribeToChanges: (callback: () => void) => () => void;
}

const SubscriptionEventsContext = createContext<SubscriptionEventsContextType | undefined>(undefined);

export const SubscriptionEventsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [subscriptionVersion, setSubscriptionVersion] = useState(0);
  const subscribersRef = React.useRef<Set<() => void>>(new Set());

  const notifySubscriptionChanged = useCallback(() => {
    setSubscriptionVersion(prev => prev + 1);

    // Notify all subscribers
    subscribersRef.current.forEach(callback => {
      try {
        callback();
      } catch (error) {
        console.warn('Error notifying subscription change subscriber:', error);
      }
    });
  }, []); // Empty dependency array - function is now stable

  const subscribeToChanges = useCallback((callback: () => void) => {
    subscribersRef.current.add(callback);

    // Return unsubscribe function
    return () => {
      subscribersRef.current.delete(callback);
    };
  }, []);

  const value = {
    subscriptionVersion,
    notifySubscriptionChanged,
    subscribeToChanges
  };

  return (
    <SubscriptionEventsContext.Provider value={value}>
      {children}
    </SubscriptionEventsContext.Provider>
  );
};

export const useSubscriptionEvents = () => {
  const context = useContext(SubscriptionEventsContext);
  if (context === undefined) {
    throw new Error('useSubscriptionEvents must be used within a SubscriptionEventsProvider');
  }
  return context;
};
