import { createContext, useContext, type ReactNode } from 'react';
import type { MessagingAdapter } from './adapter';

const AdapterContext = createContext<MessagingAdapter | null>(null);

export function MessagingProvider({
  adapter,
  children,
}: {
  adapter: MessagingAdapter;
  children: ReactNode;
}) {
  return <AdapterContext.Provider value={adapter}>{children}</AdapterContext.Provider>;
}

/** Access the host-injected adapter. Throws outside a provider — a missing provider is
 *  a wiring bug, and failing loudly beats a confusing null-deref three layers down. */
export function useAdapter(): MessagingAdapter {
  const adapter = useContext(AdapterContext);
  if (!adapter) throw new Error('useAdapter must be used within a <MessagingProvider>');
  return adapter;
}
