// 事件服务 - 用于全站无感刷新
class EventService {
  private static instance: EventService;
  private eventTarget: EventTarget;
  private listeners: Map<string, Set<EventListener>>;

  private constructor() {
    this.eventTarget = new EventTarget();
    this.listeners = new Map();
  }

  public static getInstance(): EventService {
    if (!EventService.instance) {
      EventService.instance = new EventService();
    }
    return EventService.instance;
  }

  // 订阅事件
  public subscribe(eventType: string, callback: EventListener): () => void {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, new Set());
    }
    
    this.listeners.get(eventType)!.add(callback);
    this.eventTarget.addEventListener(eventType, callback);

    // 返回取消订阅函数
    return () => {
      this.unsubscribe(eventType, callback);
    };
  }

  // 取消订阅
  public unsubscribe(eventType: string, callback: EventListener): void {
    const listeners = this.listeners.get(eventType);
    if (listeners) {
      listeners.delete(callback);
      if (listeners.size === 0) {
        this.listeners.delete(eventType);
      }
    }
    this.eventTarget.removeEventListener(eventType, callback);
  }

  // 发布事件
  public emit(eventType: string, data?: unknown): void {
    const event = new CustomEvent(eventType, { detail: data });
    this.eventTarget.dispatchEvent(event);
  }

  // 清理所有监听器
  public cleanup(): void {
    for (const [eventType, listeners] of this.listeners) {
      for (const listener of listeners) {
        this.eventTarget.removeEventListener(eventType, listener);
      }
    }
    this.listeners.clear();
  }
}

// 事件类型常量
export const EVENT_TYPES = {
  PRIZE_DRAWN: 'prize_drawn',           // 奖品被抽中
  PRIZES_UPDATED: 'prizes_updated',     // 奖品数据更新
  RECORDS_UPDATED: 'records_updated',   // 抽奖记录更新
  PROBABILITY_CHANGED: 'probability_changed', // 概率发生变化
  STUDENT_DRAWN: 'student_drawn',       // 学生完成抽奖
  STUDENT_UPDATED: 'student_updated',   // 学生数据更新
  SYSTEM_CONFIG_UPDATED: 'system_config_updated', // 系统配置更新
  DATA_CLEARED: 'data_cleared',         // 数据清空
  SYSTEM_RESET: 'system_reset',         // 系统重置
  FORCE_RESET: 'force_reset'            // 强制重置
} as const;

export type EventType = typeof EVENT_TYPES[keyof typeof EVENT_TYPES];

// 事件数据接口
export interface PrizeDrawnEventData {
  studentId: string;
  prizeId: string;
  prizeName: string;
  prizeLevel: number;
  remainingQuantity: number;
  timestamp: number;
}

export interface PrizesUpdatedEventData {
  updatedPrizes: Array<{
    id: string;
    remainingQuantity: number;
    totalQuantity: number;
  }>;
  timestamp: number;
}

export interface ProbabilityChangedEventData {
  prizeId: string;
  oldProbability: number;
  newProbability: number;
  timestamp: number;
}

export default EventService;