/**
 * EventBus singleton for component communication
 * Inspired by fusecommerce-pro pattern
 */
let instance;
const instanceKey = 'shopypress_event_bus_2024';

class EventBus {
    constructor(key) {
        if (key !== instanceKey) {
            throw new Error('Cannot instantiate EventBus directly. Use EventBus.getInstance()');
        }
        this._events = [];
    }

    /**
     * Register event listener
     * @param {string} eventKey - Event key
     * @param {Function} callback - Callback function
     */
    on(eventKey, callback) {
        if (typeof callback !== 'function') {
            console.error('EventBus: Callback must be a function');
            return;
        }

        this._events.push({
            key: eventKey,
            callback: callback,
        });
    }

    /**
     * Trigger event
     * @param {string} eventKey - Event key
     * @param {*} payload - Event payload
     */
    trigger(eventKey, payload) {
        this._events.forEach(event => {
            if (event.key === eventKey && typeof event.callback === 'function') {
                try {
                    event.callback(payload);
                } catch (error) {
                    console.error(`EventBus: Error in callback for ${eventKey}`, error);
                }
            }
        });
    }

    /**
     * Remove event listener
     * @param {string} eventKey - Event key
     * @param {Function} callback - Callback function
     */
    off(eventKey, callback) {
        this._events = this._events.filter(event => {
            return !(event.key === eventKey && event.callback === callback);
        });
    }

    /**
     * Get singleton instance
     * @returns {EventBus} - EventBus instance
     */
    static getInstance() {
        if (!instance) {
            instance = new EventBus(instanceKey);
        }
        return instance;
    }
}

export default EventBus;
