import { createContext, useContext, type ReactNode } from 'react';
import { usePlaybackSync, type PlaybackSyncApi } from '../hooks/usePlaybackSync';

/**
 * One sync session per app, shared by everything that draws a transport
 * control. Mounting the hook twice would open two streams and register the same
 * browser as two devices.
 */
export const PlaybackSyncContext = createContext<PlaybackSyncApi | null>(null);

export function PlaybackSyncProvider({ children }: { children: ReactNode }) {
  const sync = usePlaybackSync();
  return <PlaybackSyncContext.Provider value={sync}>{children}</PlaybackSyncContext.Provider>;
}

export function usePlaybackSyncContext(): PlaybackSyncApi {
  const value = useContext(PlaybackSyncContext);
  if (!value) throw new Error('usePlaybackSyncContext must be used inside PlaybackSyncProvider');
  return value;
}

/**
 * The same session, or nothing when the caller sits outside the provider — a
 * test rendering one control, for instance. Callers that only need to know
 * whether the audio is elsewhere use this and treat absence as "play here".
 */
export function useOptionalPlaybackSync(): PlaybackSyncApi | null {
  return useContext(PlaybackSyncContext);
}
