<?php
/**
 * Event bus for extensibility (plugins listen without coupling).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Core;

final class EventBus {

	/** @var array<string, list<callable>> */
	private array $listeners = array();

	public function on( string $event, callable $callback ): void {
		$this->listeners[ $event ][] = $callback;
	}

	public function off( string $event, ?callable $callback = null ): void {
		if ( null === $callback ) {
			unset( $this->listeners[ $event ] );
			return;
		}
		if ( empty( $this->listeners[ $event ] ) ) {
			return;
		}
		$this->listeners[ $event ] = array_values(
			array_filter(
				$this->listeners[ $event ],
				static fn( $cb ) => $cb !== $callback
			)
		);
	}

	/**
	 * @param array<string, mixed> $payload
	 */
	public function emit( string $event, array $payload = array() ): void {
		foreach ( $this->listeners[ $event ] ?? array() as $cb ) {
			$cb( $payload );
		}
		// WordPress bridge for third-party plugins.
		do_action( 'aptb_' . str_replace( '.', '_', $event ), $payload );
	}
}
