import { Fragment, type ReactNode, useEffect, useState } from "react";
import { LOCALE_STORAGE_KEY } from "../../../../common/core/i18n";

type LocaleRefreshBoundaryProps = {
  children: ReactNode;
};

function LocaleRefreshBoundary({ children }: LocaleRefreshBoundaryProps) {
  const [localeVersion, setLocaleVersion] = useState(0);

  useEffect(() => {
    const syncLocale = () => {
      setLocaleVersion((current) => current + 1);
    };

    const syncLocaleFromStorage = (event: StorageEvent) => {
      if (event.key !== LOCALE_STORAGE_KEY && event.key !== null) {
        return;
      }
      syncLocale();
    };

    window.addEventListener("localechange", syncLocale);
    window.addEventListener("storage", syncLocaleFromStorage);

    return () => {
      window.removeEventListener("localechange", syncLocale);
      window.removeEventListener("storage", syncLocaleFromStorage);
    };
  }, []);

  return <Fragment key={localeVersion}>{children}</Fragment>;
}

export default LocaleRefreshBoundary;
