import { UpdateController } from "@hitplay/playable_template";

/**
 * Centralized game loop. Instead of each controller registering separately with UpdateController,
 * they register with GameLoop. This gives us:
 * - Single point of entry for all per-frame updates
 * - Explicit ordering of controller ticks
 * - Easy to add/remove/reorder without touching UpdateController
 */

type UpdateFn = (delta: number) => void;

export class GameLoop {
  private static updates: UpdateFn[] = [];
  private static started = false;

  /**
   * Register an update function to be called each frame.
   * The first call to register() sets up the UpdateController listener.
   */
  static register(fn: UpdateFn) {
    this.updates.push(fn);
    if (!this.started) {
      UpdateController.Instance.onUpdate.addDelegate((delta) => this.tick(delta));
      this.started = true;
    }
  }

  private static tick(delta: number) {
    for (const fn of this.updates) {
      fn(delta);
    }
  }
}
