import { create } from 'zustand';

/**
 * Single source of truth for "is stream playback paused." Each component that
 * wants to pause playback registers a unique id via `useSuspendPlayback`; the
 * label is for devtools only. Playback is paused while any id is registered.
 */
interface PlaybackPauseState {
  activeIds: Record<string, string>;
  add: (id: string, label: string) => void;
  remove: (id: string) => void;
}

export const usePlaybackPauseStore = create<PlaybackPauseState>((set) => ({
  activeIds: {},
  add: (id, label) =>
    set((s) => ({ activeIds: { ...s.activeIds, [id]: label } })),
  remove: (id) =>
    set((s) => {
      if (!(id in s.activeIds)) return s;
      const { [id]: _, ...rest } = s.activeIds;
      return { activeIds: rest };
    }),
}));

export const selectIsPaused = (s: PlaybackPauseState) =>
  Object.keys(s.activeIds).length > 0;
