type Subscriber<T> = (event: T) => void;

export type AppEvent =
  | { type: 'NAVIGATE'; payload: { path: string; params?: Record<string, any> } }
  | { type: 'NAVIGATE_BACK' }
  | { type: 'SHOW_VERIFICATION_MODAL' }
  | { type: 'VIBRATE'; payload: { type: 'message' | 'group_message' | 'call' } }
  | { type: 'SHOW_TOAST'; payload: { message: string; type: 'success' | 'error' | 'info' } }
  | { type: 'AUTH_LOGOUT' }
  | { type: 'AUTH_LOGIN'; payload: { userId: string } };

class EventBusClass {
  private subscribers: Set<Subscriber<AppEvent>> = new Set();

  emit(event: AppEvent): void {
    this.subscribers.forEach(subscriber => {
      try {
        subscriber(event);
      } catch (error) {
        console.error('[EventBus] Subscriber error:', error);
      }
    });
  }

  subscribe(subscriber: Subscriber<AppEvent>): () => void {
    this.subscribers.add(subscriber);
    return () => this.subscribers.delete(subscriber);
  }
}

export const eventBus = new EventBusClass();
