// Imperative store for high-frequency audio levels.
// React never re-renders on `set()`; consumers read via getCurrent() in their
// own rAF (typically the live waveform canvas). See ADR-001 §LevelsCtx.

export type LevelsStore = {
  subscribe: (cb: () => void) => () => void;
  getCurrent: () => Float32Array;
  set: (next: Float32Array) => void;
  setActive: (active: boolean) => void;
  isActive: () => boolean;
};

export function createLevelsStore(initial?: Float32Array): LevelsStore {
  let current = initial ?? new Float32Array(0);
  let active = false;
  const listeners = new Set<() => void>();

  return {
    subscribe(cb) {
      listeners.add(cb);
      return () => listeners.delete(cb);
    },
    getCurrent() {
      return current;
    },
    set(next) {
      current = next;
      for (const cb of listeners) cb();
    },
    setActive(value) {
      active = value;
    },
    isActive() {
      return active;
    },
  };
}
