import React, { createContext, FC, useLayoutEffect, useState } from 'react';

import useResizeObserver from '../hooks/useResizeObserver';

type Props = {
  documentSizeThrottleTimeoutMS?: number;
};

export const DocumentSizeContext = createContext<ResizeObserverEntry[]>([]);

export const DocumentSizeProvider: FC<Props> = ({
  documentSizeThrottleTimeoutMS = 150,
  children,
}) => {
  const [resizeEntries, setResizeEntries] = useState<ResizeObserverEntry[]>([]);

  const setElementToObserve = useResizeObserver(
    setResizeEntries,
    documentSizeThrottleTimeoutMS,
  );

  useLayoutEffect(() => {
    setElementToObserve(document.body);
  }, [setElementToObserve]);

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