import React, { createContext, useContext } from 'react';

import type { RootStore } from '../stores/RootStore';

const StoreContext = createContext<RootStore | null>(null);

export function useStore(): RootStore {
  const store = useContext(StoreContext);
  if (store === null) {
    throw new Error('useStore can only be called inside of StoreProvider');
  }
  return store;
}

export function StoreProvider({ children, store }: {
  children: JSX.Element | JSX.Element[],
  store: RootStore,
}): JSX.Element {
  return (
    <StoreContext.Provider value={store}>
      {children}
    </StoreContext.Provider>
  );
}
