import {
  createContext,
  useContext,
  useMemo,
  type ReactNode,
} from 'react';

import {
  DEFAULT_PRESENTATION_ID,
  getPresentationComponents,
} from './registry';
import type { PresentationComponents } from './types';
import type { PresentationId } from './types';

export type PresentationContextValue = {
  id: PresentationId;
  components: PresentationComponents;
};

const PresentationContext = createContext<PresentationContextValue | null>(
  null
);

type PresentationProviderProps = {
  id?: PresentationId;
  children: ReactNode;
};

export function PresentationProvider({
  id = DEFAULT_PRESENTATION_ID,
  children,
}: PresentationProviderProps) {
  const value = useMemo<PresentationContextValue>(
    () => ({
      id,
      components: getPresentationComponents(id),
    }),
    [id]
  );

  return (
    <PresentationContext.Provider value={value}>
      {children}
    </PresentationContext.Provider>
  );
}

export function usePresentation(): PresentationContextValue {
  const ctx = useContext(PresentationContext);
  if (!ctx) {
    throw new Error('usePresentation must be used within PresentationProvider');
  }
  return ctx;
}
