// HTTP shim of `wailsjs/runtime/runtime` — only the event APIs the frontend
// uses are exposed. `EventsOn` polls /diagnostics every 1.5s and emits stub
// events with the new room/timeline counts so consumers see updates without
// needing the real Wails event bus.

type Handler = (...args: any[]) => void;
const handlers = new Map<string, Set<Handler>>();
let pollTimer: ReturnType<typeof setInterval> | null = null;
let lastDiag: any = {};

const API: string =
  (import.meta as any).env?.VITE_E2E_API || "http://127.0.0.1:8767";

async function pollOnce() {
  try {
    const r = await fetch(API + "/diagnostics");
    if (!r.ok) return;
    const d = await r.json();
    if (d.rooms_count !== lastDiag.rooms_count) {
      emit("matrix:rooms_changed", d);
    }
    if (d.sync_active !== lastDiag.sync_active) {
      emit("matrix:sync_changed", d);
    }
    lastDiag = d;
  } catch {
    /* ignore */
  }
}

function emit(event: string, ...args: any[]) {
  const set = handlers.get(event);
  if (!set) return;
  for (const h of set) {
    try {
      h(...args);
    } catch {
      /* ignore */
    }
  }
}

function ensurePolling() {
  if (pollTimer) return;
  pollTimer = setInterval(pollOnce, 1500);
}

export function EventsOn(event: string, handler: Handler): () => void {
  if (!handlers.has(event)) handlers.set(event, new Set());
  handlers.get(event)!.add(handler);
  ensurePolling();
  return () => {
    handlers.get(event)?.delete(handler);
  };
}

export function EventsOnce(event: string, handler: Handler): () => void {
  const off = EventsOn(event, (...args) => {
    off();
    handler(...args);
  });
  return off;
}

export function EventsEmit(_event: string, ..._args: any[]): void {
  // no-op in dev
}

export function EventsOff(event: string, ..._handlers: Handler[]): void {
  handlers.delete(event);
}
