import { PropsWithChildren, ReactElement, createContext, useContext, useMemo } from 'react';

interface TruncatedGroupContextValue {
  hiddenElements: ReactElement[];
}

/**
 * Contains elements which cannot be displayed
 */
const TruncatedGroupContext = createContext<TruncatedGroupContextValue | undefined>(undefined);

export function TruncatedGroupContextProvider({
  hiddenElements,
  children,
}: PropsWithChildren<TruncatedGroupContextValue>) {
  const value = useMemo(() => ({ hiddenElements }), [hiddenElements]);
  return <TruncatedGroupContext.Provider value={value}>{children}</TruncatedGroupContext.Provider>;
}

export function useTruncatedGroupHiddenElements() {
  const context = useContext(TruncatedGroupContext);
  if (!context) {
    throw new Error(
      'useTruncatedGroupHiddenElements should be used only inside TruncatedGroupContextProvider',
    );
  }
  return context.hiddenElements;
}
