type Listener<T = any> = (payload: T) => void;

export class EventEmitter {
    private events: Map<string, Listener[]> = new Map();

    public on(event: string, listener: Listener): () => void {
        if (!this.events.has(event)) {
            this.events.set(event, []);
        }
        this.events.get(event)!.push(listener);

        // Return unsubscribe function
        return () => this.off(event, listener);
    }

    public off(event: string, listener: Listener): void {
        const listeners = this.events.get(event);
        if (!listeners) return;

        const index = listeners.indexOf(listener);
        if (index !== -1) {
            listeners.splice(index, 1);
        }
    }

    public emit(event: string, payload?: any): void {
        const listeners = this.events.get(event);
        if (listeners) {
            listeners.forEach(listener => {
                try {
                    listener(payload);
                } catch (error) {
                    console.error(`[EventEmitter] Error in listener for event "${event}":`, error);
                }
            });
        }
    }

    public clear(): void {
        this.events.clear();
    }
}
