type ReaderEventType =
  | "readerReady"
  | "pageChanged"
  | "chapterChanged"
  | "zoomChanged"
  | "themeChanged"
  | "progressUpdated"
  | "beforePageChange"
  | "afterPageChange";

class EventBus {
  private listeners = new Map<ReaderEventType, Function[]>();

  on(event: ReaderEventType, handler: Function): void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event)!.push(handler);
  }

  off(event: ReaderEventType, handler: Function): void {
    const handlers = this.listeners.get(event);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
      }
    }
  }

  emit(event: ReaderEventType, data?: any): void {
    this.listeners.get(event)?.forEach((handler) => handler(data));
  }

  clear(): void {
    this.listeners.clear();
  }
}

export const readerEvents = new EventBus();
export type { ReaderEventType };
