// lib/evolution/event.bus.ts
import { appendEvolutionSnapshot } from './history.collector';
import { alignEvolutionTimeline } from './timeline.align';

/**
 * Event Bus بسيط للأحداث الزمنية داخل النظام.
 * عند كل حدث جديد، بنسجّل snapshot ونحدّث الخط الزمني aligned.
 */

type EventHandler = (payload?: any) => void;
const listeners: Record<string, EventHandler[]> = {};

export function on(event: string, handler: EventHandler) {
  listeners[event] = listeners[event] || [];
  listeners[event].push(handler);
}

export function emit(event: string, payload?: any) {
  if (event === 'evolution:update') {
    // كل تحديث للنظام ⇒ snapshot + alignment
    appendEvolutionSnapshot();
    const aligned = alignEvolutionTimeline('daily');
    localStorage.setItem('ALIGNED_TIMELINE', JSON.stringify(aligned));
  }
  (listeners[event] || []).forEach((fn) => fn(payload));
}

export function getAlignedTimeline() {
  try {
    return JSON.parse(localStorage.getItem('ALIGNED_TIMELINE') || '[]');
  } catch {
    return [];
  }
}
