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

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

  useEffect(() => {
    const newDir = i18n.dir(i18n.language);

    const newCache = createCache({
      key: 'css',
      stylisPlugins: newDir === 'rtl' ? [rtlPlugin] : [],
    });
    setCache(newCache);
  }, [i18n, i18n.language]);

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