// assets/js/core/EventBus.js
export default class EventBus {

    constructor() {
        this.events = new Map();
    }

    on(event, callback) {
        if (!this.events.has(event)) {
            this.events.set(event, new Set());
        }
        this.events.get(event).add(callback);
        return () => this.off(event, callback);
    }

    off(event, callback) {
        if (!this.events.has(event)) return;

        this.events.get(event).delete(callback);

        if (this.events.get(event).size === 0) {
            this.events.delete(event);
        }
    }

    emit(event, data = null) {
        if (!this.events.has(event)) return;

        const listeners = this.events.get(event);

        for (const callback of listeners) {
            try {
                callback(data);
            } catch (e) {
                console.error("EventBus listener error:", e);
            }
        }
    }

    once(event, callback) {
        const wrapper = (data) => {
            callback(data);
            this.off(event, wrapper);
        };
        this.on(event, wrapper);
    }
}
