import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import rtlPlugin from 'stylis-plugin-rtl';
import { prefixer } from 'stylis';

// This provider configures Emotion's cache to support RTL.
export const RtlProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { i18n } = useTranslation();

  const cacheRtl = useMemo(() => {
    const isRtl = i18n.dir(i18n.language) === 'rtl';
    return createCache({
      key: isRtl ? 'muirtl' : 'muiltr',
      stylisPlugins: isRtl ? [prefixer, rtlPlugin] : [],
    });
  }, [i18n, i18n.language]);

  return <CacheProvider value={cacheRtl}>{children}</CacheProvider>;
};
